faiss 0.6.3 → 0.6.5

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 (255) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +8 -0
  3. data/ext/faiss/extconf.rb +1 -1
  4. data/lib/faiss/version.rb +1 -1
  5. data/vendor/faiss/faiss/AutoTune.cpp +175 -0
  6. data/vendor/faiss/faiss/Clustering.cpp +150 -60
  7. data/vendor/faiss/faiss/Clustering.h +37 -0
  8. data/vendor/faiss/faiss/IVFlib.cpp +99 -0
  9. data/vendor/faiss/faiss/IVFlib.h +15 -0
  10. data/vendor/faiss/faiss/Index.cpp +44 -0
  11. data/vendor/faiss/faiss/Index.h +18 -13
  12. data/vendor/faiss/faiss/IndexBinary.cpp +8 -0
  13. data/vendor/faiss/faiss/IndexBinary.h +8 -0
  14. data/vendor/faiss/faiss/IndexBinaryFromFloat.cpp +23 -2
  15. data/vendor/faiss/faiss/IndexBinaryHNSW.cpp +94 -144
  16. data/vendor/faiss/faiss/IndexBinaryHNSW.h +18 -5
  17. data/vendor/faiss/faiss/IndexBinaryIVF.cpp +40 -14
  18. data/vendor/faiss/faiss/IndexBinaryIVF.h +8 -1
  19. data/vendor/faiss/faiss/IndexFastScan.cpp +33 -17
  20. data/vendor/faiss/faiss/IndexFastScan.h +6 -3
  21. data/vendor/faiss/faiss/IndexFlat.cpp +64 -4
  22. data/vendor/faiss/faiss/IndexFlat.h +33 -2
  23. data/vendor/faiss/faiss/IndexFlatCodes.cpp +6 -1
  24. data/vendor/faiss/faiss/IndexHNSW.cpp +755 -99
  25. data/vendor/faiss/faiss/IndexHNSW.h +69 -7
  26. data/vendor/faiss/faiss/IndexIDMap.cpp +43 -6
  27. data/vendor/faiss/faiss/IndexIDMap.h +7 -0
  28. data/vendor/faiss/faiss/IndexIVF.cpp +297 -32
  29. data/vendor/faiss/faiss/IndexIVF.h +53 -1
  30. data/vendor/faiss/faiss/IndexIVFFastScan.cpp +46 -14
  31. data/vendor/faiss/faiss/IndexIVFFastScan.h +4 -2
  32. data/vendor/faiss/faiss/IndexIVFFlat.cpp +33 -0
  33. data/vendor/faiss/faiss/IndexIVFFlat.h +16 -0
  34. data/vendor/faiss/faiss/IndexIVFPQ.cpp +9 -1
  35. data/vendor/faiss/faiss/IndexIVFPQ.h +11 -0
  36. data/vendor/faiss/faiss/IndexIVFPQFastScan.cpp +1 -0
  37. data/vendor/faiss/faiss/IndexIVFRaBitQ.cpp +3 -20
  38. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.cpp +50 -14
  39. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.h +5 -2
  40. data/vendor/faiss/faiss/IndexIVFSQFastScan.cpp +855 -0
  41. data/vendor/faiss/faiss/IndexIVFSQFastScan.h +145 -0
  42. data/vendor/faiss/faiss/IndexNNDescent.cpp +0 -3
  43. data/vendor/faiss/faiss/IndexPiPNN.cpp +201 -0
  44. data/vendor/faiss/faiss/IndexPiPNN.h +83 -0
  45. data/vendor/faiss/faiss/IndexRaBitQFastScan.cpp +6 -3
  46. data/vendor/faiss/faiss/IndexRaBitQFastScan.h +10 -4
  47. data/vendor/faiss/faiss/IndexReplicas.cpp +20 -0
  48. data/vendor/faiss/faiss/IndexReplicas.h +9 -0
  49. data/vendor/faiss/faiss/IndexSQFastScan.cpp +648 -0
  50. data/vendor/faiss/faiss/IndexSQFastScan.h +129 -0
  51. data/vendor/faiss/faiss/IndexShards.cpp +13 -3
  52. data/vendor/faiss/faiss/IndexShards.h +5 -0
  53. data/vendor/faiss/faiss/IndexShardsIVF.cpp +4 -3
  54. data/vendor/faiss/faiss/SuperKMeans.cpp +87 -22
  55. data/vendor/faiss/faiss/SuperKMeans.h +12 -6
  56. data/vendor/faiss/faiss/VectorTransform.cpp +40 -1
  57. data/vendor/faiss/faiss/VectorTransform.h +3 -0
  58. data/vendor/faiss/faiss/clone_index.cpp +27 -0
  59. data/vendor/faiss/faiss/gpu/Dataset.h +112 -0
  60. data/vendor/faiss/faiss/gpu/GpuCloner.cpp +16 -13
  61. data/vendor/faiss/faiss/gpu/GpuCloner.h +4 -0
  62. data/vendor/faiss/faiss/gpu/GpuClonerOptions.h +4 -5
  63. data/vendor/faiss/faiss/gpu/GpuDistance.h +2 -5
  64. data/vendor/faiss/faiss/gpu/GpuIndex.h +8 -18
  65. data/vendor/faiss/faiss/gpu/GpuIndexBinaryCagra.h +26 -13
  66. data/vendor/faiss/faiss/gpu/GpuIndexCagra.h +109 -63
  67. data/vendor/faiss/faiss/gpu/GpuIndexFlat.h +11 -0
  68. data/vendor/faiss/faiss/gpu/GpuIndexIVF.h +6 -0
  69. data/vendor/faiss/faiss/gpu/test/TestGpuDatasetHeader.cpp +18 -0
  70. data/vendor/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp +215 -0
  71. data/vendor/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp +98 -0
  72. data/vendor/faiss/faiss/gpu/utils/DeviceUtils.h +11 -0
  73. data/vendor/faiss/faiss/gpu/utils/StackDeviceMemory.cpp +1 -1
  74. data/vendor/faiss/faiss/gpu_metal/MetalCloner.h +11 -0
  75. data/vendor/faiss/faiss/gpu_metal/MetalDistance.h +92 -0
  76. data/vendor/faiss/faiss/gpu_metal/MetalIndex.h +4 -0
  77. data/vendor/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.h +69 -0
  78. data/vendor/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h +38 -0
  79. data/vendor/faiss/faiss/gpu_metal/MetalKernels.h +106 -0
  80. data/vendor/faiss/faiss/gpu_metal/MetalPythonBridge.h +10 -0
  81. data/vendor/faiss/faiss/impl/AdditiveQuantizer.cpp +1 -1
  82. data/vendor/faiss/faiss/impl/AuxIndexStructures.cpp +2 -0
  83. data/vendor/faiss/faiss/impl/AuxIndexStructures.h +1 -6
  84. data/vendor/faiss/faiss/impl/ClusteringHelpers.cpp +134 -45
  85. data/vendor/faiss/faiss/impl/ClusteringHelpers.h +36 -0
  86. data/vendor/faiss/faiss/impl/ClusteringInitialization.cpp +287 -134
  87. data/vendor/faiss/faiss/impl/DistanceComputer.cpp +63 -0
  88. data/vendor/faiss/faiss/impl/DistanceComputer.h +3 -29
  89. data/vendor/faiss/faiss/impl/HNSW.cpp +465 -125
  90. data/vendor/faiss/faiss/impl/HNSW.h +118 -7
  91. data/vendor/faiss/faiss/impl/IDSelector.h +44 -0
  92. data/vendor/faiss/faiss/impl/LocalSearchQuantizer.cpp +6 -19
  93. data/vendor/faiss/faiss/impl/NNDescent.cpp +12 -4
  94. data/vendor/faiss/faiss/impl/NSG.cpp +3 -2
  95. data/vendor/faiss/faiss/impl/Panorama.h +14 -4
  96. data/vendor/faiss/faiss/impl/PiPNN.cpp +822 -0
  97. data/vendor/faiss/faiss/impl/PiPNN.h +122 -0
  98. data/vendor/faiss/faiss/impl/ProductQuantizer.cpp +58 -15
  99. data/vendor/faiss/faiss/impl/RaBitQUtils.cpp +1 -1
  100. data/vendor/faiss/faiss/impl/RaBitQUtils.h +1 -1
  101. data/vendor/faiss/faiss/impl/RaBitQuantizer.cpp +150 -60
  102. data/vendor/faiss/faiss/impl/RaBitQuantizer.h +62 -4
  103. data/vendor/faiss/faiss/impl/RaBitQuantizerMultiBit.cpp +2 -2
  104. data/vendor/faiss/faiss/impl/ResultHandler.h +9 -3
  105. data/vendor/faiss/faiss/impl/ScalarQuantizer.cpp +61 -30
  106. data/vendor/faiss/faiss/impl/ScalarQuantizer.h +7 -16
  107. data/vendor/faiss/faiss/impl/approx_topk/avx2.cpp +0 -4
  108. data/vendor/faiss/faiss/impl/approx_topk/neon.cpp +0 -4
  109. data/vendor/faiss/faiss/impl/binary_hamming/IndexBinaryHash_impl.h +5 -2
  110. data/vendor/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h +89 -13
  111. data/vendor/faiss/faiss/impl/binary_hamming/avx2.cpp +0 -4
  112. data/vendor/faiss/faiss/impl/binary_hamming/avx512.cpp +0 -4
  113. data/vendor/faiss/faiss/impl/binary_hamming/neon.cpp +0 -4
  114. data/vendor/faiss/faiss/impl/binary_hamming/rvv.cpp +0 -4
  115. data/vendor/faiss/faiss/impl/expanded_scanners.h +93 -1
  116. data/vendor/faiss/faiss/impl/fast_scan/FastScanDistancePostProcessing.h +4 -0
  117. data/vendor/faiss/faiss/impl/fast_scan/accumulate_loops.h +61 -64
  118. data/vendor/faiss/faiss/impl/fast_scan/accumulate_loops_512.h +13 -14
  119. data/vendor/faiss/faiss/impl/fast_scan/decompose_qbs.h +18 -129
  120. data/vendor/faiss/faiss/impl/fast_scan/dispatching.h +25 -19
  121. data/vendor/faiss/faiss/impl/fast_scan/fast_scan.cpp +5 -0
  122. data/vendor/faiss/faiss/impl/fast_scan/impl-avx2.cpp +0 -4
  123. data/vendor/faiss/faiss/impl/fast_scan/impl-avx512.cpp +0 -4
  124. data/vendor/faiss/faiss/impl/fast_scan/impl-neon.cpp +0 -88
  125. data/vendor/faiss/faiss/impl/fast_scan/impl-riscv.cpp +0 -4
  126. data/vendor/faiss/faiss/impl/fast_scan/kernels_neon.h +155 -0
  127. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd256.h +22 -1
  128. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd512.h +3 -2
  129. data/vendor/faiss/faiss/impl/fast_scan/simd_result_handlers.h +41 -23
  130. data/vendor/faiss/faiss/impl/hnsw/avx2.cpp +0 -4
  131. data/vendor/faiss/faiss/impl/hnsw/avx512.cpp +0 -4
  132. data/vendor/faiss/faiss/impl/index_read.cpp +302 -29
  133. data/vendor/faiss/faiss/impl/index_write.cpp +126 -26
  134. data/vendor/faiss/faiss/impl/pipnn/HashPrune.cpp +159 -0
  135. data/vendor/faiss/faiss/impl/pipnn/HashPrune.h +69 -0
  136. data/vendor/faiss/faiss/impl/pipnn/Partition.cpp +587 -0
  137. data/vendor/faiss/faiss/impl/pipnn/Partition.h +93 -0
  138. data/vendor/faiss/faiss/impl/pipnn/kernels.cpp +326 -0
  139. data/vendor/faiss/faiss/impl/pipnn/kernels.h +92 -0
  140. data/vendor/faiss/faiss/impl/platform_macros.h +45 -0
  141. data/vendor/faiss/faiss/impl/polysemous_training/avx512.cpp +0 -4
  142. data/vendor/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h +152 -43
  143. data/vendor/faiss/faiss/impl/pq_code_distance/PQDistanceComputer_impl.h +6 -0
  144. data/vendor/faiss/faiss/impl/pq_code_distance/avx2.cpp +0 -4
  145. data/vendor/faiss/faiss/impl/pq_code_distance/avx512.cpp +0 -4
  146. data/vendor/faiss/faiss/impl/pq_code_distance/neon.cpp +0 -4
  147. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx2.h +4 -0
  148. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx512.h +4 -1
  149. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.cpp +23 -4
  150. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.h +6 -6
  151. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-inl.h +131 -6
  152. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-sve.cpp +0 -4
  153. data/vendor/faiss/faiss/impl/pq_code_distance/pq_rvv_kernel.h +89 -0
  154. data/vendor/faiss/faiss/impl/pq_code_distance/pq_scan_impl.h +21 -10
  155. data/vendor/faiss/faiss/impl/pq_code_distance/rvv.cpp +45 -18
  156. data/vendor/faiss/faiss/impl/residual_quantizer_encode_steps.cpp +2 -1
  157. data/vendor/faiss/faiss/impl/result_handler/avx2.cpp +0 -4
  158. data/vendor/faiss/faiss/impl/result_handler/avx512.cpp +0 -4
  159. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx2.cpp +0 -4
  160. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx512.cpp +0 -4
  161. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp +6 -1
  162. data/vendor/faiss/faiss/impl/scalar_quantizer/distance_computers.h +7 -3
  163. data/vendor/faiss/faiss/impl/scalar_quantizer/quantizers.h +28 -52
  164. data/vendor/faiss/faiss/impl/scalar_quantizer/scanners.h +59 -11
  165. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp +232 -79
  166. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h +482 -103
  167. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp +2 -149
  168. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp +3 -698
  169. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-dispatch.h +101 -72
  170. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp +203 -99
  171. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-rvv.cpp +3185 -144
  172. data/vendor/faiss/faiss/impl/scalar_quantizer/sq8_coefficients.h +48 -0
  173. data/vendor/faiss/faiss/impl/scalar_quantizer/sq8_rvv_kernel.h +546 -0
  174. data/vendor/faiss/faiss/impl/scalar_quantizer/training.cpp +2 -2
  175. data/vendor/faiss/faiss/impl/simd_dispatch.h +47 -22
  176. data/vendor/faiss/faiss/impl/simdlib/simdlib_avx2.h +14 -0
  177. data/vendor/faiss/faiss/impl/simdlib/simdlib_dispatch.h +7 -8
  178. data/vendor/faiss/faiss/impl/sq_fastscan_utils.h +232 -0
  179. data/vendor/faiss/faiss/index_factory.cpp +84 -1
  180. data/vendor/faiss/faiss/invlists/InvertedLists.cpp +10 -5
  181. data/vendor/faiss/faiss/invlists/OnDiskInvertedLists.cpp +10 -4
  182. data/vendor/faiss/faiss/svs/IndexSVSVamana.cpp +16 -4
  183. data/vendor/faiss/faiss/svs/IndexSVSVamana.h +11 -3
  184. data/vendor/faiss/faiss/svs/IndexSVSVamanaLVQ.cpp +4 -2
  185. data/vendor/faiss/faiss/svs/IndexSVSVamanaLVQ.h +2 -1
  186. data/vendor/faiss/faiss/svs/IndexSVSVamanaLeanVec.cpp +9 -2
  187. data/vendor/faiss/faiss/svs/IndexSVSVamanaLeanVec.h +2 -1
  188. data/vendor/faiss/faiss/utils/AlignedTable.h +6 -1
  189. data/vendor/faiss/faiss/utils/Heap.cpp +4 -3
  190. data/vendor/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h +16 -5
  191. data/vendor/faiss/faiss/utils/bf16.h +36 -0
  192. data/vendor/faiss/faiss/utils/distances.cpp +246 -28
  193. data/vendor/faiss/faiss/utils/distances.h +34 -0
  194. data/vendor/faiss/faiss/utils/distances_dispatch.h +36 -28
  195. data/vendor/faiss/faiss/utils/distances_fused/avx512.cpp +2 -5
  196. data/vendor/faiss/faiss/utils/distances_fused/distances_fused.cpp +1 -15
  197. data/vendor/faiss/faiss/utils/distances_fused/rvv.cpp +25 -0
  198. data/vendor/faiss/faiss/utils/distances_fused/simdlib_based.cpp +0 -4
  199. data/vendor/faiss/faiss/utils/distances_fused/simdlib_based_neon.cpp +0 -4
  200. data/vendor/faiss/faiss/utils/distances_fused/simdlib_kernel-inl.h +2 -1
  201. data/vendor/faiss/faiss/utils/distances_simd.cpp +9 -0
  202. data/vendor/faiss/faiss/utils/fp16-fp16c.h +4 -0
  203. data/vendor/faiss/faiss/utils/fp16-inl.h +26 -52
  204. data/vendor/faiss/faiss/utils/hamming.cpp +15 -9
  205. data/vendor/faiss/faiss/utils/hamming.h +10 -1
  206. data/vendor/faiss/faiss/utils/hamming_distance/common.h +14 -3
  207. data/vendor/faiss/faiss/utils/hamming_distance/hamming_avx2.cpp +0 -4
  208. data/vendor/faiss/faiss/utils/hamming_distance/hamming_avx512.cpp +0 -4
  209. data/vendor/faiss/faiss/utils/hamming_distance/hamming_avx512_vpopcnt.cpp +20 -0
  210. data/vendor/faiss/faiss/utils/hamming_distance/hamming_computer-avx512.h +34 -6
  211. data/vendor/faiss/faiss/utils/hamming_distance/hamming_computer-avx512_vpopcnt.h +217 -0
  212. data/vendor/faiss/faiss/utils/hamming_distance/hamming_computer-neon.h +0 -4
  213. data/vendor/faiss/faiss/utils/hamming_distance/hamming_impl.h +143 -1
  214. data/vendor/faiss/faiss/utils/hamming_distance/hamming_neon.cpp +0 -4
  215. data/vendor/faiss/faiss/utils/hamming_distance/hamming_rvv.cpp +0 -4
  216. data/vendor/faiss/faiss/utils/pq_code_distance.h +8 -4
  217. data/vendor/faiss/faiss/utils/prefetch.h +1 -26
  218. data/vendor/faiss/faiss/utils/quantize_lut.cpp +26 -27
  219. data/vendor/faiss/faiss/utils/quantize_lut.h +11 -0
  220. data/vendor/faiss/faiss/utils/rabitq_simd.h +51 -16
  221. data/vendor/faiss/faiss/utils/simd_impl/distances_aarch64.cpp +9 -4
  222. data/vendor/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp +231 -35
  223. data/vendor/faiss/faiss/utils/simd_impl/distances_avx2.cpp +64 -5
  224. data/vendor/faiss/faiss/utils/simd_impl/distances_avx512.cpp +64 -5
  225. data/vendor/faiss/faiss/utils/simd_impl/distances_rvv.cpp +428 -108
  226. data/vendor/faiss/faiss/utils/simd_impl/distances_rvv_kernel.h +68 -0
  227. data/vendor/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h +93 -0
  228. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels.h +76 -0
  229. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels_avx2.cpp +52 -0
  230. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels_avx512.cpp +52 -0
  231. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels_neon.cpp +48 -0
  232. data/vendor/faiss/faiss/utils/simd_impl/masked_sum-avx2.h +44 -0
  233. data/vendor/faiss/faiss/utils/simd_impl/masked_sum-avx512.h +43 -0
  234. data/vendor/faiss/faiss/utils/simd_impl/masked_sum.h +38 -0
  235. data/vendor/faiss/faiss/utils/simd_impl/partitioning_avx2.cpp +0 -4
  236. data/vendor/faiss/faiss/utils/simd_impl/partitioning_neon.cpp +0 -4
  237. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp +54 -15
  238. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp +89 -55
  239. data/vendor/faiss/faiss/utils/simd_impl/{rabitq_avx512_spr.cpp → rabitq_avx512_vpopcnt.cpp} +70 -36
  240. data/vendor/faiss/faiss/utils/simd_impl/rabitq_neon.cpp +297 -10
  241. data/vendor/faiss/faiss/utils/simd_impl/rabitq_rvv.cpp +0 -4
  242. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_dispatch.h +2 -7
  243. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_kernels.h +6 -1
  244. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx2.cpp +0 -4
  245. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx512.cpp +0 -4
  246. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_kernels_sve.cpp +30 -0
  247. data/vendor/faiss/faiss/utils/simd_levels.cpp +191 -70
  248. data/vendor/faiss/faiss/utils/simd_levels.h +100 -16
  249. data/vendor/faiss/faiss/utils/transpose/transpose-avx2-inl.h +0 -4
  250. data/vendor/faiss/faiss/utils/transpose/transpose-avx512-inl.h +0 -4
  251. data/vendor/faiss/faiss/utils/utils.cpp +80 -0
  252. data/vendor/faiss/faiss/utils/utils.h +24 -0
  253. metadata +38 -5
  254. data/vendor/faiss/faiss/utils/hamming_distance/hamming_avx512_spr.cpp +0 -15
  255. data/vendor/faiss/faiss/utils/hamming_distance/hamming_computer-avx512_spr.h +0 -171
@@ -7,9 +7,12 @@
7
7
 
8
8
  #include <faiss/IndexHNSW.h>
9
9
 
10
- #include <omp.h>
10
+ #include <faiss/IndexRaBitQ.h>
11
+
12
+ #include <algorithm>
11
13
  #include <atomic>
12
14
  #include <cinttypes>
15
+ #include <cmath>
13
16
  #include <cstdio>
14
17
  #include <cstdlib>
15
18
  #include <cstring>
@@ -17,7 +20,6 @@
17
20
  #include <limits>
18
21
  #include <memory>
19
22
  #include <queue>
20
- #include <random>
21
23
 
22
24
  #include <cstdint>
23
25
  #include "faiss/Index.h"
@@ -30,9 +32,12 @@
30
32
  #include <faiss/impl/FaissException.h>
31
33
  #include <faiss/impl/ResultHandler.h>
32
34
  #include <faiss/impl/VisitedTable.h>
35
+ #include <faiss/impl/hnsw/LockVector.h>
33
36
  #include <faiss/impl/hnsw/MinimaxHeap.h>
37
+ #include <faiss/impl/platform_macros.h>
34
38
  #include <faiss/utils/random.h>
35
39
  #include <faiss/utils/sorting.h>
40
+ #include <faiss/utils/utils.h>
36
41
 
37
42
  namespace faiss {
38
43
 
@@ -41,6 +46,13 @@ using NodeDistFarther = HNSW::NodeDistFarther;
41
46
 
42
47
  HNSWStats hnsw_stats;
43
48
 
49
+ void HNSWStats::combine_atomic(const HNSWStats& other) {
50
+ detail::atomic_fetch_add_relaxed(n1, other.n1);
51
+ detail::atomic_fetch_add_relaxed(n2, other.n2);
52
+ detail::atomic_fetch_add_relaxed(ndis, other.ndis);
53
+ detail::atomic_fetch_add_relaxed(nhops, other.nhops);
54
+ }
55
+
44
56
  /**************************************************************
45
57
  * add / search blocks of descriptors
46
58
  **************************************************************/
@@ -60,19 +72,29 @@ DistanceComputer* storage_distance_computer(const Index* storage) {
60
72
  return storage->get_distance_computer();
61
73
  }
62
74
 
63
- void hnsw_add_vertices(
64
- IndexHNSW& index_hnsw,
75
+ } // namespace
76
+
77
+ // Deterministic HNSW graph build inspired by ParlayANN: points are bucketed by
78
+ // level and inserted in prefix-doubling batches. Phase A computes forward
79
+ // links against a frozen snapshot and records reverse edges; phase B merges
80
+ // those in a fixed order.
81
+ // https://arxiv.org/abs/2305.04359
82
+ void hnsw_add_vertices_deterministic(
83
+ HNSW& hnsw,
65
84
  size_t n0,
66
85
  size_t n,
67
- const float* x,
86
+ int d,
87
+ bool init_level0,
88
+ bool keep_max_size_level0,
89
+ bool preset_levels,
68
90
  bool verbose,
69
- bool preset_levels = false) {
70
- size_t d = index_hnsw.d;
71
- HNSW& hnsw = index_hnsw.hnsw;
91
+ const std::function<DistanceComputer*()>& make_distance_computer,
92
+ const std::function<void(DistanceComputer&, HNSW::storage_idx_t)>&
93
+ set_query) {
72
94
  size_t ntotal = n0 + n;
73
95
  double t0 = getmillisecs();
74
96
  if (verbose) {
75
- printf("hnsw_add_vertices: adding %zd elements on top of %zd "
97
+ printf("hnsw_add_vertices_deterministic: adding %zd elements on top of %zd "
76
98
  "(preset_levels=%d)\n",
77
99
  n,
78
100
  n0,
@@ -83,16 +105,16 @@ void hnsw_add_vertices(
83
105
  return;
84
106
  }
85
107
 
86
- int max_level = hnsw.prepare_level_tab(n, preset_levels);
108
+ // init_level0=false (CAGRA import) skips the level-0-only bucket; higher-
109
+ // level points still build their own level-0 links.
110
+ const int min_bucket_level = init_level0 ? 0 : 1;
87
111
 
112
+ int max_level = hnsw.prepare_level_tab(n, preset_levels);
88
113
  if (verbose) {
89
114
  printf(" max_level = %d\n", max_level);
90
115
  }
91
116
 
92
- auto& locks = index_hnsw.locks;
93
- locks.prepare(ntotal);
94
-
95
- // add vectors from highest to lowest level
117
+ // Bucket the new points by level, highest first.
96
118
  std::vector<int> hist;
97
119
  std::vector<int> order(n);
98
120
 
@@ -122,98 +144,243 @@ void hnsw_add_vertices(
122
144
  }
123
145
  }
124
146
 
125
- idx_t check_period = InterruptCallback::get_period_hint(
126
- max_level * index_hnsw.d * hnsw.efConstruction);
147
+ // Upper bound on batch size (ParlayANN's theta), 2% of the index.
148
+ const size_t theta =
149
+ std::max<size_t>(1, static_cast<size_t>(0.02 * ntotal));
127
150
 
128
- { // perform add
129
- RandomGenerator rng2(789);
151
+ // Polled inside phase A: a batch can be 2% of ntotal, so cancelling only
152
+ // at batch boundaries would take minutes on large indexes.
153
+ const idx_t check_period = InterruptCallback::get_period_hint(
154
+ max_level * d * hnsw.efConstruction);
130
155
 
131
- size_t i1 = static_cast<int>(n);
156
+ RandomGenerator rng2(789);
157
+ size_t i1 = n;
132
158
 
133
- for (int pt_level = static_cast<int>(hist.size()) - 1;
134
- pt_level >= int(!index_hnsw.init_level0);
135
- pt_level--) {
136
- size_t i0 = i1 - hist[pt_level];
159
+ for (int pt_level = static_cast<int>(hist.size()) - 1;
160
+ pt_level >= min_bucket_level;
161
+ pt_level--) {
162
+ size_t i0 = i1 - hist[pt_level];
163
+ if (i0 == i1) {
164
+ continue;
165
+ }
137
166
 
138
- if (verbose) {
139
- printf("Adding %zu elements at level %d\n", i1 - i0, pt_level);
140
- }
167
+ if (verbose) {
168
+ printf("Adding %zu elements at level %d\n", i1 - i0, pt_level);
169
+ }
170
+
171
+ // random permutation to get rid of dataset order bias
172
+ for (size_t j = i0; j < i1; j++) {
173
+ std::swap(
174
+ order[j],
175
+ order[j + rng2.rand_int(static_cast<int>(i1 - j))]);
176
+ }
141
177
 
142
- // random permutation to get rid of dataset order bias
143
- for (size_t j = i0; j < i1; j++) {
144
- std::swap(
145
- order[j],
146
- order[j + rng2.rand_int(static_cast<int>(i1 - j))]);
178
+ // Bootstrap only when the graph is empty. Raising entry_point to a
179
+ // point that is not yet linked orphans everything already inserted,
180
+ // which on an incremental add() is the entire prior graph. order[i0]
181
+ // is the sole member of the first batch below, so defer until then.
182
+ bool raise_entry_point = false;
183
+ if (hnsw.entry_point == -1) {
184
+ hnsw.max_level = pt_level;
185
+ hnsw.entry_point = order[i0];
186
+ } else if (pt_level > hnsw.max_level) {
187
+ raise_entry_point = true;
188
+ }
189
+
190
+ // Prefix-doubling batches within this bucket.
191
+ size_t s = i0;
192
+ while (s < i1) {
193
+ size_t done = s - i0;
194
+ size_t grow = std::min(done == 0 ? size_t(1) : done, theta);
195
+ size_t e = std::min(i1, s + grow);
196
+
197
+ // Phase A: compute forward links against the snapshot
198
+ // A reverse edge: `dest` gains an incoming link from `src`.
199
+ struct Edge {
200
+ int level;
201
+ HNSW::storage_idx_t dest;
202
+ HNSW::storage_idx_t src;
203
+ };
204
+
205
+ // One buffer, sized to an upper bound so it never reallocates.
206
+ // The fill order is nondeterministic but harmless: phase B
207
+ // regroups by destination.
208
+ size_t cap_sum = 0;
209
+ for (int64_t i = s; i < static_cast<int64_t>(e); i++) {
210
+ storage_idx_t pid = order[i];
211
+ cap_sum += hnsw.offsets[pid + 1] - hnsw.offsets[pid];
147
212
  }
213
+ // Default-initialised to skip a memset per sub-batch; safe because
214
+ // edge_counter only hands out slots that are written before read.
215
+ std::unique_ptr<Edge[]> reverse_edges(new Edge[cap_sum]);
216
+ std::atomic<size_t> edge_counter{0};
148
217
 
218
+ // Thrown after the region (cannot throw out of one); the
219
+ // unsynchronized write costs at most one extra poll.
149
220
  bool interrupt = false;
150
221
 
151
- #pragma omp parallel if (i1 > i0 + 100)
222
+ #pragma omp parallel if (e - s > 100)
152
223
  {
153
224
  std::unique_ptr<VisitedTable> vt =
154
225
  VisitedTable::create(ntotal, hnsw.use_visited_hashset);
155
226
 
156
- std::unique_ptr<DistanceComputer> dis(
157
- storage_distance_computer(index_hnsw.storage));
158
- bool do_display = verbose && omp_get_thread_num() == 0;
159
- size_t prev_display = 0;
227
+ std::unique_ptr<DistanceComputer> dis(make_distance_computer());
228
+ std::vector<std::pair<HNSW::storage_idx_t, int>>
229
+ pt_reverse_edges;
160
230
  size_t counter = 0;
161
231
 
162
- // here we should do schedule(dynamic) but this segfaults for
163
- // some versions of LLVM. The performance impact should not be
164
- // too large when (i1 - i0) / num_threads >> 1
165
232
  #pragma omp for schedule(static)
166
- for (int64_t i = i0; i < i1; i++) {
167
- storage_idx_t pt_id = order[i];
168
- dis->set_query(x + (pt_id - n0) * d);
169
-
170
- // cannot break
233
+ for (int64_t i = s; i < static_cast<int64_t>(e); i++) {
171
234
  if (interrupt) {
172
- continue;
235
+ continue; // cannot break out of an OpenMP for loop
173
236
  }
237
+ storage_idx_t pt_id = order[i];
238
+ int lvl = hnsw.levels[pt_id] - 1;
239
+ set_query(*dis, pt_id);
174
240
 
175
- hnsw.add_with_locks(
241
+ pt_reverse_edges.clear();
242
+ hnsw.compute_forward_links_deterministic(
176
243
  *dis,
177
- pt_level,
244
+ lvl,
178
245
  pt_id,
179
- locks,
180
246
  *vt,
181
- index_hnsw.keep_max_size_level0 && (pt_level == 0));
182
-
183
- if (do_display && i - i0 > prev_display + 10000) {
184
- prev_display = i - i0;
185
- printf(" %zu / %zu\r", i - i0, i1 - i0);
186
- fflush(stdout);
247
+ pt_reverse_edges,
248
+ keep_max_size_level0);
249
+
250
+ size_t off = edge_counter.fetch_add(
251
+ pt_reverse_edges.size(), std::memory_order_relaxed);
252
+ for (size_t k = 0; k < pt_reverse_edges.size(); k++) {
253
+ reverse_edges[off + k] = {
254
+ pt_reverse_edges[k].second,
255
+ pt_reverse_edges[k].first,
256
+ pt_id};
187
257
  }
188
- if (counter % check_period == 0) {
189
- if (InterruptCallback::is_interrupted()) {
190
- interrupt = true;
191
- }
258
+
259
+ if (counter++ % check_period == 0 &&
260
+ InterruptCallback::is_interrupted()) {
261
+ interrupt = true;
192
262
  }
193
- counter++;
194
263
  }
195
264
  }
196
265
  if (interrupt) {
197
266
  FAISS_THROW_MSG("computation interrupted");
198
267
  }
199
- i1 = i0;
200
- }
201
- if (index_hnsw.init_level0) {
202
- FAISS_ASSERT(i1 == 0);
203
- } else {
204
- FAISS_ASSERT((i1 - hist[0]) == 0);
268
+
269
+ // Phase B: merge the reverse edges
270
+ // Group by destination so each node is merged by exactly one
271
+ // thread: lock-free and thread-count-independent.
272
+ const size_t total = edge_counter.load();
273
+
274
+ constexpr int kBucketBits = 8;
275
+ constexpr uint32_t kNumBuckets = 1u << kBucketBits;
276
+ constexpr uint32_t kBucketMask = kNumBuckets - 1;
277
+
278
+ // bstart[b]..bstart[b+1] delimits bucket b after partitioning.
279
+ std::vector<size_t> bstart(kNumBuckets + 1, 0);
280
+ for (size_t idx = 0; idx < total; idx++) {
281
+ bstart[(static_cast<uint32_t>(reverse_edges[idx].dest) &
282
+ kBucketMask) +
283
+ 1]++;
284
+ }
285
+ for (uint32_t b = 0; b < kNumBuckets; b++) {
286
+ bstart[b + 1] += bstart[b];
287
+ }
288
+
289
+ // In-place partition (cycle sort): each step lands at least one
290
+ // edge in its bucket, so O(total) with no auxiliary buffer.
291
+ {
292
+ std::vector<size_t> head(bstart.begin(), bstart.end() - 1);
293
+ for (uint32_t b = 0; b < kNumBuckets; b++) {
294
+ size_t end_b = bstart[b + 1];
295
+ while (head[b] < end_b) {
296
+ Edge cur_e = reverse_edges[head[b]];
297
+ if ((static_cast<uint32_t>(cur_e.dest) & kBucketMask) ==
298
+ b) {
299
+ head[b]++;
300
+ continue;
301
+ }
302
+ while ((static_cast<uint32_t>(cur_e.dest) &
303
+ kBucketMask) != b) {
304
+ uint32_t tb = static_cast<uint32_t>(cur_e.dest) &
305
+ kBucketMask;
306
+ std::swap(cur_e, reverse_edges[head[tb]]);
307
+ head[tb]++;
308
+ }
309
+ reverse_edges[head[b]] = cur_e;
310
+ head[b]++;
311
+ }
312
+ }
313
+ }
314
+ Edge* base = reverse_edges.get();
315
+
316
+ #pragma omp parallel if (total > 100)
317
+ {
318
+ std::unique_ptr<DistanceComputer> dis(make_distance_computer());
319
+ // Not schedule(dynamic): the libomp dynamic dispatcher
320
+ // segfaults in some build configs.
321
+ #pragma omp for schedule(static)
322
+ for (int64_t b = 0; b < static_cast<int64_t>(kNumBuckets);
323
+ b++) {
324
+ Edge* p = base + bstart[b];
325
+ size_t m = bstart[b + 1] - bstart[b];
326
+ if (m == 0) {
327
+ continue;
328
+ }
329
+ // src order does not matter; the merge re-sorts each set.
330
+ std::sort(p, p + m, [](const Edge& a, const Edge& c) {
331
+ if (a.level != c.level) {
332
+ return a.level < c.level;
333
+ }
334
+ return a.dest < c.dest;
335
+ });
336
+ std::vector<HNSW::storage_idx_t> incoming;
337
+ size_t g = 0;
338
+ while (g < m) {
339
+ size_t h = g + 1;
340
+ while (h < m && p[h].level == p[g].level &&
341
+ p[h].dest == p[g].dest) {
342
+ h++;
343
+ }
344
+ incoming.clear();
345
+ incoming.reserve(h - g);
346
+ for (size_t kk = g; kk < h; kk++) {
347
+ incoming.push_back(p[kk].src);
348
+ }
349
+ hnsw.merge_reverse_links_deterministic(
350
+ *dis,
351
+ p[g].dest,
352
+ p[g].level,
353
+ incoming,
354
+ keep_max_size_level0 && (p[g].level == 0));
355
+ g = h;
356
+ }
357
+ }
358
+ }
359
+
360
+ InterruptCallback::check();
361
+ s = e;
362
+
363
+ if (raise_entry_point) {
364
+ hnsw.max_level = pt_level;
365
+ hnsw.entry_point = order[i0];
366
+ raise_entry_point = false;
367
+ }
205
368
  }
369
+
370
+ i1 = i0;
371
+ }
372
+
373
+ if (init_level0) {
374
+ FAISS_ASSERT(i1 == 0);
375
+ } else {
376
+ FAISS_ASSERT((i1 - hist[0]) == 0);
206
377
  }
378
+
207
379
  if (verbose) {
208
380
  printf("Done in %.3f ms\n", getmillisecs() - t0);
209
381
  }
210
- if (!index_hnsw.retain_locks) {
211
- locks.clear();
212
- }
213
382
  }
214
383
 
215
- } // namespace
216
-
217
384
  /**************************************************************
218
385
  * IndexHNSW implementation
219
386
  **************************************************************/
@@ -269,9 +436,11 @@ void hnsw_search(
269
436
  }
270
437
  }
271
438
  size_t n1 = 0, n2 = 0, ndis = 0, nhops = 0;
439
+ size_t n_rabitq_1bit = 0, n_rabitq_refine = 0;
272
440
 
273
441
  idx_t check_period = InterruptCallback::get_period_hint(
274
442
  hnsw.max_level * index->d * efSearch);
443
+ check_period *= omp_get_max_threads();
275
444
 
276
445
  for (idx_t i0 = 0; i0 < n; i0 += check_period) {
277
446
  idx_t i1 = std::min(i0 + check_period, n);
@@ -294,7 +463,9 @@ void hnsw_search(
294
463
  omp_capture_exception(ex, [&] { interrupt = true; });
295
464
  }
296
465
 
297
- #pragma omp for reduction(+ : n1, n2, ndis, nhops) schedule(guided)
466
+ #pragma omp for reduction( \
467
+ + : n1, n2, ndis, nhops, n_rabitq_1bit, n_rabitq_refine) \
468
+ schedule(guided)
298
469
  for (idx_t i = i0; i < i1; i++) {
299
470
  if (interrupt.load(std::memory_order_relaxed)) {
300
471
  continue;
@@ -302,15 +473,25 @@ void hnsw_search(
302
473
  try {
303
474
  res->begin(i);
304
475
  dis->set_query(x + i * index->d);
476
+ auto* rq = dynamic_cast<RaBitQDistanceComputer*>(dis.get());
477
+ if (rq) {
478
+ rq->stats.reset();
479
+ }
305
480
 
481
+ // HNSW::search owns the per-query generation advance. The
482
+ // reusable-table acquisition above only clears stale TLS
483
+ // state before this thread starts processing queries.
306
484
  HNSWStats stats =
307
485
  hnsw.search(*dis, index, *res, *vt, params);
308
486
  n1 += stats.n1;
309
487
  n2 += stats.n2;
310
488
  ndis += stats.ndis;
311
489
  nhops += stats.nhops;
490
+ if (rq) {
491
+ n_rabitq_1bit += rq->stats.n_1bit;
492
+ n_rabitq_refine += rq->stats.n_refine;
493
+ }
312
494
  res->end();
313
- vt->advance();
314
495
  } catch (...) {
315
496
  omp_capture_exception(ex, [&] { interrupt = true; });
316
497
  }
@@ -320,7 +501,10 @@ void hnsw_search(
320
501
  InterruptCallback::check();
321
502
  }
322
503
 
323
- hnsw_stats.combine({n1, n2, ndis, nhops});
504
+ if (get_search_stats_enabled()) {
505
+ hnsw_stats.combine_atomic({n1, n2, ndis, nhops});
506
+ rabitq_stats.add_atomic({n_rabitq_1bit, n_rabitq_refine});
507
+ }
324
508
  }
325
509
 
326
510
  } // anonymous namespace
@@ -384,18 +568,25 @@ void IndexHNSW::add(idx_t n, const float* x) {
384
568
  storage->add(n, x);
385
569
  ntotal = storage->ntotal;
386
570
 
387
- hnsw_add_vertices(
388
- *this,
571
+ bool preset_levels = hnsw.levels.size() == static_cast<size_t>(ntotal);
572
+
573
+ hnsw_add_vertices_deterministic(
574
+ hnsw,
389
575
  n0,
390
576
  n,
391
- x,
577
+ d,
578
+ init_level0,
579
+ keep_max_size_level0,
580
+ preset_levels,
392
581
  verbose,
393
- hnsw.levels.size() == static_cast<size_t>(ntotal));
582
+ [this] { return storage_distance_computer(storage); },
583
+ [this, x, n0](DistanceComputer& dc, HNSW::storage_idx_t pt_id) {
584
+ dc.set_query(x + (pt_id - n0) * d);
585
+ });
394
586
  }
395
587
 
396
588
  void IndexHNSW::reset() {
397
589
  hnsw.reset();
398
- locks.clear();
399
590
  storage->reset();
400
591
  ntotal = 0;
401
592
  }
@@ -479,6 +670,7 @@ void IndexHNSW::search_level_0(
479
670
  {
480
671
  std::unique_ptr<DistanceComputer> qdis;
481
672
  HNSWStats search_stats;
673
+ RaBitQStats rq_search_stats;
482
674
  VisitedTable* vt = nullptr;
483
675
  std::unique_ptr<typename RH::SingleResultHandler> res;
484
676
  try {
@@ -498,6 +690,11 @@ void IndexHNSW::search_level_0(
498
690
  try {
499
691
  res->begin(i);
500
692
  qdis->set_query(x + i * d);
693
+ auto* rq =
694
+ dynamic_cast<RaBitQDistanceComputer*>(qdis.get());
695
+ if (rq) {
696
+ rq->stats.reset();
697
+ }
501
698
 
502
699
  hnsw.search_level_0(
503
700
  *qdis.get(),
@@ -509,15 +706,18 @@ void IndexHNSW::search_level_0(
509
706
  search_stats,
510
707
  *vt,
511
708
  params);
709
+ if (rq) {
710
+ rq_search_stats.add(rq->stats);
711
+ }
512
712
  res->end();
513
713
  vt->advance();
514
714
  } catch (...) {
515
715
  omp_capture_exception(ex, [&] { interrupt = true; });
516
716
  }
517
717
  }
518
- #pragma omp critical
519
- {
520
- hnsw_stats.combine(search_stats);
718
+ if (get_search_stats_enabled()) {
719
+ hnsw_stats.combine_atomic(search_stats);
720
+ rabitq_stats.add_atomic(rq_search_stats);
521
721
  }
522
722
  }
523
723
  omp_rethrow_if_exception(ex);
@@ -576,7 +776,7 @@ void IndexHNSW::init_level_0_from_entry_points(
576
776
  int n,
577
777
  const storage_idx_t* points,
578
778
  const storage_idx_t* nearests) {
579
- locks.prepare(ntotal);
779
+ LockVector locks(ntotal);
580
780
 
581
781
  #pragma omp parallel
582
782
  {
@@ -587,7 +787,7 @@ void IndexHNSW::init_level_0_from_entry_points(
587
787
  storage_distance_computer(storage));
588
788
  std::vector<float> vec(storage->d);
589
789
 
590
- #pragma omp for schedule(dynamic)
790
+ #pragma omp for schedule(FAISS_OMP_DYNAMIC)
591
791
  for (int i = 0; i < n; i++) {
592
792
  storage_idx_t pt_id = points[i];
593
793
  storage_idx_t nearest = nearests[i];
@@ -606,10 +806,6 @@ void IndexHNSW::init_level_0_from_entry_points(
606
806
  if (verbose) {
607
807
  printf("\n");
608
808
  }
609
-
610
- if (!retain_locks) {
611
- locks.clear();
612
- }
613
809
  }
614
810
 
615
811
  void IndexHNSW::reorder_links() {
@@ -714,6 +910,433 @@ IndexHNSWFlat::IndexHNSWFlat(int d_in, int M, MetricType metric)
714
910
  is_trained = true;
715
911
  }
716
912
 
913
+ /**************************************************************
914
+ * IndexHNSW::add_level_0_links_from_sample
915
+ **************************************************************/
916
+
917
+ namespace {
918
+
919
+ // Relative difference below which two distances are equal: float rounding,
920
+ // or near-duplicate nodes. Exact duplicates give equal distances already.
921
+ constexpr float kSinkDistanceTolerance = 1e-5f;
922
+
923
+ // True when distance (or similarity) a is better than b by more than the
924
+ // tolerance.
925
+ bool is_better(float a, float b, bool similarity) {
926
+ const float tolerance =
927
+ kSinkDistanceTolerance * std::max(std::fabs(a), std::fabs(b));
928
+ return similarity ? a > b + tolerance : a < b - tolerance;
929
+ }
930
+
931
+ constexpr size_t kSinkChunk = 16384;
932
+
933
+ struct SinkScan {
934
+ size_t n_exact_searches = 0;
935
+ std::vector<idx_t> sinks; // sorted
936
+ // For each sink, the nearest nodes of its wrong vectors with their
937
+ // counts, most frequent first. Ties go to the smaller node ID.
938
+ std::vector<std::vector<std::pair<idx_t, idx_t>>> targets;
939
+ };
940
+
941
+ // Finds the sinks from the HNSW labels of the sample vectors. Searches the
942
+ // vectors that arrive at candidate sinks also with the exact search, unless
943
+ // their exact result is already known. exact[i] is the nearer node that the
944
+ // exact search found for labels[i], or labels[i] if none (-1: not computed).
945
+ SinkScan find_sinks(
946
+ size_t ntotal,
947
+ const HNSWLinkSampleSearch& sample,
948
+ const HNSWLevel0LinkParameters& params,
949
+ const std::vector<idx_t>& labels,
950
+ std::vector<idx_t>& exact) {
951
+ const idx_t n = sample.n;
952
+ std::vector<idx_t> counts(ntotal, 0);
953
+ for (idx_t i = 0; i < n; i++) {
954
+ if (labels[i] >= 0) {
955
+ counts[labels[i]]++;
956
+ }
957
+ }
958
+
959
+ const double min_count =
960
+ std::max(2.0, params.min_mean_factor * double(n) / ntotal);
961
+ // candidates: vectors that arrive at candidate sinks
962
+ std::vector<idx_t> candidates, unknown, found;
963
+ candidates.reserve(n);
964
+ for (idx_t i = 0; i < n; i++) {
965
+ if (labels[i] >= 0 && counts[labels[i]] >= min_count) {
966
+ candidates.push_back(i);
967
+ if (exact[i] < 0) {
968
+ unknown.push_back(i);
969
+ found.push_back(labels[i]);
970
+ }
971
+ }
972
+ }
973
+ std::vector<idx_t> exact_labels(unknown.size());
974
+ std::vector<uint8_t> nearer(unknown.size(), 0);
975
+ sample.search_exact(
976
+ unknown.size(),
977
+ unknown.data(),
978
+ found.data(),
979
+ exact_labels.data(),
980
+ nearer.data());
981
+ for (size_t j = 0; j < unknown.size(); j++) {
982
+ exact[unknown[j]] = nearer[j] ? exact_labels[j] : found[j];
983
+ }
984
+
985
+ // (sink candidate, nearest node) for each vector with a nearer node
986
+ std::vector<std::pair<idx_t, idx_t>> wrong;
987
+ wrong.reserve(candidates.size());
988
+ std::vector<idx_t> closer(ntotal, 0);
989
+ for (size_t j = 0; j < candidates.size(); j++) {
990
+ const idx_t i = candidates[j];
991
+ if (exact[i] != labels[i]) {
992
+ closer[labels[i]]++;
993
+ wrong.emplace_back(labels[i], exact[i]);
994
+ }
995
+ }
996
+ std::sort(wrong.begin(), wrong.end());
997
+
998
+ SinkScan scan;
999
+ scan.n_exact_searches = unknown.size();
1000
+ for (size_t a = 0; a < wrong.size();) {
1001
+ const idx_t sink = wrong[a].first;
1002
+ size_t b = a;
1003
+ while (b < wrong.size() && wrong[b].first == sink) {
1004
+ b++;
1005
+ }
1006
+ if (closer[sink] >= params.min_closer_fraction * counts[sink]) {
1007
+ std::vector<std::pair<idx_t, idx_t>> targets;
1008
+ for (size_t c = a; c < b;) {
1009
+ size_t e = c;
1010
+ while (e < b && wrong[e].second == wrong[c].second) {
1011
+ e++;
1012
+ }
1013
+ targets.emplace_back(wrong[c].second, e - c);
1014
+ c = e;
1015
+ }
1016
+ std::sort(
1017
+ targets.begin(),
1018
+ targets.end(),
1019
+ [](const auto& p, const auto& q) {
1020
+ return p.second != q.second ? p.second > q.second
1021
+ : p.first < q.first;
1022
+ });
1023
+ scan.sinks.push_back(sink);
1024
+ scan.targets.push_back(std::move(targets));
1025
+ }
1026
+ a = b;
1027
+ }
1028
+ return scan;
1029
+ }
1030
+
1031
+ // Gives `sink` level-0 links to up to `max_links` targets that it does not
1032
+ // link to yet: first in free slots, then in place of its farthest links. It
1033
+ // keeps at least half of its links. Returns (links added, links replaced).
1034
+ std::pair<size_t, size_t> link_sink(
1035
+ HNSW& hnsw,
1036
+ DistanceComputer& dis,
1037
+ HNSW::storage_idx_t sink,
1038
+ const std::vector<std::pair<idx_t, idx_t>>& targets,
1039
+ int max_links,
1040
+ bool similarity) {
1041
+ size_t begin, end;
1042
+ hnsw.neighbor_range(sink, 0, &begin, &end);
1043
+ size_t degree = 0;
1044
+ while (begin + degree < end && hnsw.neighbors[begin + degree] >= 0) {
1045
+ degree++;
1046
+ }
1047
+
1048
+ std::vector<HNSW::storage_idx_t> fresh;
1049
+ for (const auto& [target, count] : targets) {
1050
+ if (static_cast<int>(fresh.size()) >= max_links) {
1051
+ break;
1052
+ }
1053
+ bool linked = target == sink;
1054
+ for (size_t k = begin; k < begin + degree && !linked; k++) {
1055
+ linked = hnsw.neighbors[k] == target;
1056
+ }
1057
+ if (!linked) {
1058
+ fresh.push_back(static_cast<HNSW::storage_idx_t>(target));
1059
+ }
1060
+ }
1061
+
1062
+ const size_t added = std::min(fresh.size(), (end - begin) - degree);
1063
+ for (size_t k = 0; k < added; k++) {
1064
+ hnsw.neighbors[begin + degree + k] = fresh[k];
1065
+ }
1066
+
1067
+ size_t replaced = 0;
1068
+ if (added < fresh.size()) {
1069
+ // (distance from the sink, slot), farthest first
1070
+ std::vector<std::pair<float, size_t>> links;
1071
+ for (size_t k = begin; k < begin + degree; k++) {
1072
+ links.emplace_back(dis.symmetric_dis(sink, hnsw.neighbors[k]), k);
1073
+ }
1074
+ std::sort(
1075
+ links.begin(), links.end(), [&](const auto& p, const auto& q) {
1076
+ if (p.first != q.first) {
1077
+ return similarity ? p.first < q.first
1078
+ : p.first > q.first;
1079
+ }
1080
+ return p.second < q.second;
1081
+ });
1082
+ const size_t replaceable = degree / 2;
1083
+ for (size_t k = added; k < fresh.size() && replaced < replaceable;
1084
+ k++, replaced++) {
1085
+ hnsw.neighbors[links[replaced].second] = fresh[k];
1086
+ }
1087
+ }
1088
+ return {added, replaced};
1089
+ }
1090
+
1091
+ // The sample of an IndexHNSW: fp32 or packed fp16 rows, or rows encoded by a
1092
+ // codec.
1093
+ struct IndexHNSWLinkSample : HNSWLinkSampleSearch {
1094
+ const IndexHNSW& index;
1095
+ const uint8_t* x;
1096
+ NumericType numeric_type;
1097
+ const Index* codec;
1098
+
1099
+ IndexHNSWLinkSample(
1100
+ const IndexHNSW& index,
1101
+ idx_t n,
1102
+ const uint8_t* x,
1103
+ NumericType numeric_type,
1104
+ const Index* codec)
1105
+ : index(index), x(x), numeric_type(numeric_type), codec(codec) {
1106
+ this->n = n;
1107
+ }
1108
+
1109
+ size_t line_size() const {
1110
+ return codec ? codec->sa_code_size()
1111
+ : get_numeric_type_size(numeric_type) * index.d;
1112
+ }
1113
+
1114
+ // Decodes m contiguous rows to fp32.
1115
+ void decode(size_t m, const uint8_t* rows, float* out) const {
1116
+ if (codec) {
1117
+ codec->sa_decode(m, rows, out);
1118
+ } else if (numeric_type == NumericType::Float16) {
1119
+ fp16_to_fp32(
1120
+ m * index.d, reinterpret_cast<const uint16_t*>(rows), out);
1121
+ } else {
1122
+ memcpy(out, rows, m * index.d * sizeof(float));
1123
+ }
1124
+ }
1125
+
1126
+ void decode_rows(
1127
+ size_t begin,
1128
+ size_t m,
1129
+ const idx_t* ids,
1130
+ std::vector<uint8_t>& rows,
1131
+ float* out) const {
1132
+ const size_t ls = line_size();
1133
+ if (!ids) {
1134
+ decode(m, x + begin * ls, out);
1135
+ return;
1136
+ }
1137
+ if (!codec && numeric_type == NumericType::Float32) {
1138
+ for (size_t j = 0; j < m; j++) {
1139
+ memcpy(out + j * index.d, x + ids[begin + j] * ls, ls);
1140
+ }
1141
+ return;
1142
+ }
1143
+ rows.resize(m * ls);
1144
+ for (size_t j = 0; j < m; j++) {
1145
+ memcpy(rows.data() + j * ls, x + ids[begin + j] * ls, ls);
1146
+ }
1147
+ decode(m, rows.data(), out);
1148
+ }
1149
+
1150
+ // Decodes the sample vectors by blocks of kSinkChunk.
1151
+ void search(
1152
+ const SearchParametersHNSW* params,
1153
+ size_t m_total,
1154
+ const idx_t* ids,
1155
+ idx_t* labels) const override {
1156
+ if (!ids && !codec && numeric_type == NumericType::Float32) {
1157
+ std::vector<float> distances(m_total);
1158
+ index.search(
1159
+ m_total,
1160
+ reinterpret_cast<const float*>(x),
1161
+ 1,
1162
+ distances.data(),
1163
+ labels,
1164
+ params);
1165
+ return;
1166
+ }
1167
+ std::vector<uint8_t> rows;
1168
+ std::vector<float> block, distances(kSinkChunk);
1169
+ for (size_t i0 = 0; i0 < m_total; i0 += kSinkChunk) {
1170
+ const size_t m = std::min(kSinkChunk, m_total - i0);
1171
+ block.resize(m * index.d);
1172
+ decode_rows(i0, m, ids, rows, block.data());
1173
+ index.search(
1174
+ m, block.data(), 1, distances.data(), labels + i0, params);
1175
+ }
1176
+ }
1177
+
1178
+ void search_exact(
1179
+ size_t m_total,
1180
+ const idx_t* ids,
1181
+ const idx_t* found,
1182
+ idx_t* exact,
1183
+ uint8_t* nearer) const override {
1184
+ const size_t d = index.d;
1185
+ const bool similarity = is_similarity_metric(index.metric_type);
1186
+ std::vector<float> exact_distances(kSinkChunk);
1187
+ std::vector<uint8_t> rows;
1188
+ std::vector<float> chunk;
1189
+ for (size_t begin = 0; begin < m_total; begin += kSinkChunk) {
1190
+ const size_t m = std::min(kSinkChunk, m_total - begin);
1191
+ chunk.resize(m * d);
1192
+ decode_rows(begin, m, ids, rows, chunk.data());
1193
+ index.storage->search(
1194
+ m, chunk.data(), 1, exact_distances.data(), exact + begin);
1195
+
1196
+ // Compute both distances again with the same distance function.
1197
+ // The batched exact search and the HNSW search round
1198
+ // differently, which can make a node look nearer when the two
1199
+ // distances are almost equal.
1200
+ #pragma omp parallel
1201
+ {
1202
+ std::unique_ptr<DistanceComputer> dis(
1203
+ storage_distance_computer(index.storage));
1204
+ #pragma omp for schedule(static)
1205
+ for (int64_t j = 0; j < static_cast<int64_t>(m); j++) {
1206
+ const idx_t e = exact[begin + j], f = found[begin + j];
1207
+ if (e < 0 || e == f) {
1208
+ continue;
1209
+ }
1210
+ dis->set_query(chunk.data() + j * d);
1211
+ nearer[begin + j] =
1212
+ is_better((*dis)(e), (*dis)(f), similarity);
1213
+ }
1214
+ }
1215
+ }
1216
+ }
1217
+ };
1218
+
1219
+ HNSWLevel0LinkStats add_level_0_links_impl(
1220
+ IndexHNSW& index,
1221
+ const IndexHNSWLinkSample& sample,
1222
+ const HNSWLevel0LinkParameters& params) {
1223
+ FAISS_THROW_IF_NOT_MSG(
1224
+ index.storage, "add_level_0_links_from_sample needs storage");
1225
+ std::unique_ptr<DistanceComputer> dis(
1226
+ storage_distance_computer(index.storage));
1227
+ return hnsw_add_level_0_links_from_sample(
1228
+ index.hnsw,
1229
+ index.ntotal,
1230
+ *dis,
1231
+ is_similarity_metric(index.metric_type),
1232
+ sample,
1233
+ params);
1234
+ }
1235
+
1236
+ } // namespace
1237
+
1238
+ HNSWLevel0LinkStats hnsw_add_level_0_links_from_sample(
1239
+ HNSW& hnsw,
1240
+ size_t ntotal,
1241
+ DistanceComputer& dis,
1242
+ bool similarity,
1243
+ const HNSWLinkSampleSearch& sample,
1244
+ const HNSWLevel0LinkParameters& params) {
1245
+ FAISS_THROW_IF_NOT(params.max_rounds >= 0 && params.max_links_per_sink > 0);
1246
+ HNSWLevel0LinkStats stats;
1247
+ if (ntotal == 0 || sample.n == 0) {
1248
+ return stats;
1249
+ }
1250
+ std::vector<idx_t> labels(sample.n), exact(sample.n, -1);
1251
+ sample.search(params.search_params, sample.n, nullptr, labels.data());
1252
+ for (int round = 0;; round++) {
1253
+ const SinkScan scan = find_sinks(ntotal, sample, params, labels, exact);
1254
+ stats.n_exact_searches += scan.n_exact_searches;
1255
+ if (round == 0) {
1256
+ stats.n_sinks_found = scan.sinks.size();
1257
+ }
1258
+ stats.n_sinks_remaining = scan.sinks.size();
1259
+ if (scan.sinks.empty() || round == params.max_rounds) {
1260
+ break;
1261
+ }
1262
+ size_t changed = 0;
1263
+ for (size_t i = 0; i < scan.sinks.size(); i++) {
1264
+ const auto [added, replaced] = link_sink(
1265
+ hnsw,
1266
+ dis,
1267
+ static_cast<HNSW::storage_idx_t>(scan.sinks[i]),
1268
+ scan.targets[i],
1269
+ params.max_links_per_sink,
1270
+ similarity);
1271
+ stats.n_links_added += added;
1272
+ stats.n_links_replaced += replaced;
1273
+ changed += added + replaced;
1274
+ }
1275
+ if (changed == 0) {
1276
+ break;
1277
+ }
1278
+ stats.n_rounds++;
1279
+
1280
+ // The new links leave from the sinks, so search again only the
1281
+ // vectors that arrived at a sink.
1282
+ // Approximate: searches that only pass through a sink can change too.
1283
+ std::vector<idx_t> ids;
1284
+ for (idx_t i = 0; i < sample.n; i++) {
1285
+ if (std::binary_search(
1286
+ scan.sinks.begin(), scan.sinks.end(), labels[i])) {
1287
+ ids.push_back(i);
1288
+ }
1289
+ }
1290
+ std::vector<idx_t> found(ids.size());
1291
+ sample.search(
1292
+ params.search_params, ids.size(), ids.data(), found.data());
1293
+ for (size_t j = 0; j < ids.size(); j++) {
1294
+ if (labels[ids[j]] != found[j]) {
1295
+ labels[ids[j]] = found[j];
1296
+ exact[ids[j]] = -1;
1297
+ }
1298
+ }
1299
+ }
1300
+ return stats;
1301
+ }
1302
+
1303
+ HNSWLevel0LinkStats IndexHNSW::add_level_0_links_from_sample(
1304
+ idx_t n,
1305
+ const float* x,
1306
+ const HNSWLevel0LinkParameters& params) {
1307
+ return add_level_0_links_from_sample_ex(n, x, NumericType::Float32, params);
1308
+ }
1309
+
1310
+ HNSWLevel0LinkStats IndexHNSW::add_level_0_links_from_sample_ex(
1311
+ idx_t n,
1312
+ const void* x,
1313
+ NumericType numeric_type,
1314
+ const HNSWLevel0LinkParameters& params) {
1315
+ FAISS_THROW_IF_NOT_MSG(
1316
+ numeric_type == NumericType::Float32 ||
1317
+ numeric_type == NumericType::Float16,
1318
+ "add_level_0_links_from_sample_ex supports Float32 and Float16");
1319
+ const IndexHNSWLinkSample sample(
1320
+ *this, n, static_cast<const uint8_t*>(x), numeric_type, nullptr);
1321
+ return add_level_0_links_impl(*this, sample, params);
1322
+ }
1323
+
1324
+ HNSWLevel0LinkStats IndexHNSW::add_level_0_links_from_sample_encoded(
1325
+ idx_t n,
1326
+ const uint8_t* x,
1327
+ const Index* codec,
1328
+ const HNSWLevel0LinkParameters& params) {
1329
+ FAISS_THROW_IF_NOT_MSG(
1330
+ codec, "add_level_0_links_from_sample_encoded needs a codec");
1331
+ FAISS_THROW_IF_NOT_FMT(
1332
+ codec->d == d,
1333
+ "codec dimension %d is not the index dimension %d",
1334
+ int(codec->d),
1335
+ int(d));
1336
+ const IndexHNSWLinkSample sample(*this, n, x, NumericType::Float32, codec);
1337
+ return add_level_0_links_impl(*this, sample, params);
1338
+ }
1339
+
717
1340
  /**************************************************************
718
1341
  * IndexHNSWFlatPanorama implementation
719
1342
  **************************************************************/
@@ -741,7 +1364,7 @@ IndexHNSWFlatPanorama::IndexHNSWFlatPanorama(
741
1364
  // Enable Panorama search mode.
742
1365
  // This is not ideal, but is still more simple than making a subclass of
743
1366
  // HNSW and overriding the search logic.
744
- hnsw.is_panorama = true;
1367
+ hnsw.search_method = HNSW::SM_PANORAMA;
745
1368
  }
746
1369
 
747
1370
  void IndexHNSWFlatPanorama::add(idx_t n, const float* x) {
@@ -808,6 +1431,38 @@ IndexHNSWSQ::IndexHNSWSQ(
808
1431
 
809
1432
  IndexHNSWSQ::IndexHNSWSQ() = default;
810
1433
 
1434
+ /**************************************************************
1435
+ * IndexHNSWRaBitQ implementation
1436
+ **************************************************************/
1437
+
1438
+ IndexHNSWRaBitQ::IndexHNSWRaBitQ() = default;
1439
+
1440
+ namespace {
1441
+
1442
+ IndexRaBitQ* make_hnsw_rabitq_storage(
1443
+ int d,
1444
+ uint8_t nb_bits,
1445
+ MetricType metric) {
1446
+ FAISS_THROW_IF_NOT_MSG(
1447
+ metric == METRIC_L2, "IndexHNSWRaBitQ supports only the L2 metric");
1448
+ return new IndexRaBitQ(d, metric, nb_bits);
1449
+ }
1450
+
1451
+ } // namespace
1452
+
1453
+ IndexHNSWRaBitQ::IndexHNSWRaBitQ(
1454
+ int d,
1455
+ int M,
1456
+ uint8_t nb_bits,
1457
+ MetricType metric)
1458
+ : IndexHNSW(make_hnsw_rabitq_storage(d, nb_bits, metric), M) {
1459
+ own_fields = true;
1460
+ is_trained = storage->is_trained;
1461
+ // 1-bit codes store plain SignBitFactors with no f_error, so there is no
1462
+ // bound to prune with and the staged path does not apply.
1463
+ hnsw.search_method = nb_bits >= 2 ? HNSW::SM_RABITQ : HNSW::SM_DEFAULT;
1464
+ }
1465
+
811
1466
  /**************************************************************
812
1467
  * IndexHNSW2Level implementation
813
1468
  **************************************************************/
@@ -1017,7 +1672,9 @@ void IndexHNSW2Level::search(
1017
1672
  }
1018
1673
  omp_rethrow_if_exception(ex);
1019
1674
 
1020
- hnsw_stats.combine({n1, n2, ndis, nhops});
1675
+ if (get_search_stats_enabled()) {
1676
+ hnsw_stats.combine_atomic({n1, n2, ndis, nhops});
1677
+ }
1021
1678
  }
1022
1679
  }
1023
1680
 
@@ -1123,13 +1780,11 @@ void IndexHNSWCagra::search(
1123
1780
  // first real candidate will always be strictly better.
1124
1781
  nearest_d[i] = C::neutral();
1125
1782
 
1126
- std::random_device rd;
1127
- std::mt19937 gen(rd());
1128
- std::uniform_int_distribution<idx_t> distrib(
1129
- 0, this->ntotal - 1);
1783
+ // Seeded per query so entrypoints are reproducible.
1784
+ SplitMix64RandomGenerator gen(i);
1130
1785
 
1131
1786
  for (idx_t j = 0; j < num_base_level_search_entrypoints; j++) {
1132
- auto idx = distrib(gen);
1787
+ idx_t idx = gen.rand_int64() % this->ntotal;
1133
1788
  auto distance = (*dis)(idx);
1134
1789
  if (C::cmp(nearest_d[i], distance)) {
1135
1790
  nearest[i] = static_cast<storage_idx_t>(idx);
@@ -1188,12 +1843,11 @@ void IndexHNSWCagra::range_search(
1188
1843
  // real candidate will always be strictly better.
1189
1844
  float nearest_d = C::neutral();
1190
1845
 
1191
- std::random_device rd;
1192
- std::mt19937 gen(rd());
1193
- std::uniform_int_distribution<idx_t> distrib(0, ntotal - 1);
1846
+ // For reproducible entrypoint.
1847
+ SplitMix64RandomGenerator gen(i);
1194
1848
 
1195
1849
  for (idx_t j = 0; j < num_base_level_search_entrypoints; j++) {
1196
- auto idx = distrib(gen);
1850
+ idx_t idx = gen.rand_int64() % ntotal;
1197
1851
  auto distance = (*dis)(idx);
1198
1852
  // C::cmp(nearest_d, distance) is true iff distance is
1199
1853
  // strictly better than the current nearest_d.
@@ -1222,7 +1876,9 @@ void IndexHNSWCagra::range_search(
1222
1876
  result->do_allocation();
1223
1877
  pres.copy_result();
1224
1878
 
1225
- hnsw_stats.combine({n1, n2, ndis, nhops});
1879
+ if (get_search_stats_enabled()) {
1880
+ hnsw_stats.combine_atomic({n1, n2, ndis, nhops});
1881
+ }
1226
1882
  };
1227
1883
 
1228
1884
  if (is_similarity_metric(metric_type)) {