faiss 0.6.4 → 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 (301) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +9 -0
  3. data/ext/faiss/extconf.rb +2 -1
  4. data/ext/faiss/index.cpp +42 -0
  5. data/lib/faiss/version.rb +1 -1
  6. data/vendor/faiss/faiss/AutoTune.cpp +175 -0
  7. data/vendor/faiss/faiss/Clustering.cpp +150 -60
  8. data/vendor/faiss/faiss/Clustering.h +29 -0
  9. data/vendor/faiss/faiss/IVFlib.cpp +147 -51
  10. data/vendor/faiss/faiss/IVFlib.h +21 -2
  11. data/vendor/faiss/faiss/Index.cpp +44 -0
  12. data/vendor/faiss/faiss/Index.h +18 -13
  13. data/vendor/faiss/faiss/IndexBinary.cpp +8 -0
  14. data/vendor/faiss/faiss/IndexBinary.h +8 -0
  15. data/vendor/faiss/faiss/IndexBinaryFlat.cpp +1 -0
  16. data/vendor/faiss/faiss/IndexBinaryHNSW.cpp +85 -4
  17. data/vendor/faiss/faiss/IndexBinaryHNSW.h +19 -0
  18. data/vendor/faiss/faiss/IndexBinaryIVF.cpp +40 -11
  19. data/vendor/faiss/faiss/IndexFastScan.cpp +34 -18
  20. data/vendor/faiss/faiss/IndexFastScan.h +6 -3
  21. data/vendor/faiss/faiss/IndexFlat.cpp +57 -1
  22. data/vendor/faiss/faiss/IndexFlat.h +31 -0
  23. data/vendor/faiss/faiss/IndexFlatCodes.cpp +6 -1
  24. data/vendor/faiss/faiss/IndexHNSW.cpp +461 -13
  25. data/vendor/faiss/faiss/IndexHNSW.h +40 -5
  26. data/vendor/faiss/faiss/IndexIDMap.cpp +45 -0
  27. data/vendor/faiss/faiss/IndexIDMap.h +15 -3
  28. data/vendor/faiss/faiss/IndexIVF.cpp +349 -68
  29. data/vendor/faiss/faiss/IndexIVF.h +90 -2
  30. data/vendor/faiss/faiss/IndexIVFFastScan.cpp +51 -29
  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 +22 -6
  34. data/vendor/faiss/faiss/IndexIVFPQFastScan.cpp +2 -1
  35. data/vendor/faiss/faiss/IndexIVFRaBitQ.cpp +3 -20
  36. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.cpp +78 -58
  37. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.h +7 -13
  38. data/vendor/faiss/faiss/IndexIVFRaBitQSSD.cpp +1694 -0
  39. data/vendor/faiss/faiss/IndexIVFRaBitQSSD.h +288 -0
  40. data/vendor/faiss/faiss/IndexIVFSQFastScan.cpp +860 -0
  41. data/vendor/faiss/faiss/IndexIVFSQFastScan.h +145 -0
  42. data/vendor/faiss/faiss/IndexNNDescent.cpp +21 -3
  43. data/vendor/faiss/faiss/IndexPiPNN.cpp +201 -0
  44. data/vendor/faiss/faiss/IndexPiPNN.h +83 -0
  45. data/vendor/faiss/faiss/IndexRaBitQ.cpp +189 -41
  46. data/vendor/faiss/faiss/IndexRaBitQ.h +5 -0
  47. data/vendor/faiss/faiss/IndexRaBitQFastScan.cpp +7 -4
  48. data/vendor/faiss/faiss/IndexRaBitQFastScan.h +12 -6
  49. data/vendor/faiss/faiss/IndexReplicas.cpp +20 -0
  50. data/vendor/faiss/faiss/IndexReplicas.h +9 -0
  51. data/vendor/faiss/faiss/IndexSQFastScan.cpp +648 -0
  52. data/vendor/faiss/faiss/IndexSQFastScan.h +129 -0
  53. data/vendor/faiss/faiss/IndexShards.cpp +10 -0
  54. data/vendor/faiss/faiss/IndexShards.h +5 -0
  55. data/vendor/faiss/faiss/SuperKMeans.cpp +59 -17
  56. data/vendor/faiss/faiss/SuperKMeans.h +9 -4
  57. data/vendor/faiss/faiss/VectorTransform.cpp +159 -11
  58. data/vendor/faiss/faiss/VectorTransform.h +24 -1
  59. data/vendor/faiss/faiss/clone_index.cpp +24 -0
  60. data/vendor/faiss/faiss/factory_tools.cpp +19 -1
  61. data/vendor/faiss/faiss/gpu/Dataset.h +164 -0
  62. data/vendor/faiss/faiss/gpu/GpuCloner.cpp +16 -13
  63. data/vendor/faiss/faiss/gpu/GpuCloner.h +4 -0
  64. data/vendor/faiss/faiss/gpu/GpuClonerOptions.h +3 -0
  65. data/vendor/faiss/faiss/gpu/GpuIndex.h +4 -13
  66. data/vendor/faiss/faiss/gpu/GpuIndexBinaryCagra.h +32 -13
  67. data/vendor/faiss/faiss/gpu/GpuIndexCagra.h +51 -22
  68. data/vendor/faiss/faiss/gpu/GpuIndexFlat.h +11 -0
  69. data/vendor/faiss/faiss/gpu/GpuIndexIVF.h +6 -0
  70. data/vendor/faiss/faiss/gpu/impl/optimal_kmeans/GpuOptimalKMeans.h +184 -0
  71. data/vendor/faiss/faiss/gpu/test/TestCodePacking.cpp +12 -4
  72. data/vendor/faiss/faiss/gpu/test/TestGpuDatasetHeader.cpp +18 -0
  73. data/vendor/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp +215 -0
  74. data/vendor/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp +98 -0
  75. data/vendor/faiss/faiss/gpu/test/TestUtils.cpp +6 -5
  76. data/vendor/faiss/faiss/gpu/utils/DeviceUtils.h +11 -0
  77. data/vendor/faiss/faiss/gpu/utils/StackDeviceMemory.cpp +1 -1
  78. data/vendor/faiss/faiss/gpu_metal/GpuIndexFlat.h +1 -1
  79. data/vendor/faiss/faiss/gpu_metal/MetalCloner.h +12 -1
  80. data/vendor/faiss/faiss/gpu_metal/MetalDistance.h +93 -1
  81. data/vendor/faiss/faiss/gpu_metal/MetalFlatKernels.h +1 -1
  82. data/vendor/faiss/faiss/gpu_metal/MetalIndex.h +5 -1
  83. data/vendor/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.h +69 -0
  84. data/vendor/faiss/faiss/gpu_metal/MetalIndexFlat.h +1 -1
  85. data/vendor/faiss/faiss/gpu_metal/MetalIndexIVFFlat.h +1 -1
  86. data/vendor/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h +39 -1
  87. data/vendor/faiss/faiss/gpu_metal/MetalKernels.h +107 -1
  88. data/vendor/faiss/faiss/gpu_metal/MetalPythonBridge.h +11 -1
  89. data/vendor/faiss/faiss/gpu_metal/MetalResources.h +1 -1
  90. data/vendor/faiss/faiss/gpu_metal/StandardMetalResources.h +1 -1
  91. data/vendor/faiss/faiss/gpu_metal/impl/MetalIVFFlat.h +1 -1
  92. data/vendor/faiss/faiss/gpu_metal/impl/MetalIVFPQ.h +1 -1
  93. data/vendor/faiss/faiss/impl/AuxIndexStructures.cpp +3 -1
  94. data/vendor/faiss/faiss/impl/AuxIndexStructures.h +1 -6
  95. data/vendor/faiss/faiss/impl/ClusteringHelpers.cpp +134 -45
  96. data/vendor/faiss/faiss/impl/ClusteringHelpers.h +36 -0
  97. data/vendor/faiss/faiss/impl/ClusteringInitialization.cpp +267 -136
  98. data/vendor/faiss/faiss/impl/ClusteringInitialization.h +0 -15
  99. data/vendor/faiss/faiss/impl/CodePacker.cpp +2 -2
  100. data/vendor/faiss/faiss/impl/CodePackerRaBitQ.cpp +2 -2
  101. data/vendor/faiss/faiss/impl/DeterministicNNDescent.cpp +2167 -0
  102. data/vendor/faiss/faiss/impl/DeterministicNNDescent.h +301 -0
  103. data/vendor/faiss/faiss/impl/DistanceComputer.cpp +63 -0
  104. data/vendor/faiss/faiss/impl/DistanceComputer.h +3 -29
  105. data/vendor/faiss/faiss/impl/HNSW.cpp +48 -12
  106. data/vendor/faiss/faiss/impl/HNSW.h +74 -2
  107. data/vendor/faiss/faiss/impl/IDSelector.h +5 -4
  108. data/vendor/faiss/faiss/impl/LocalSearchQuantizer.cpp +6 -19
  109. data/vendor/faiss/faiss/impl/NNDescent.cpp +2 -1
  110. data/vendor/faiss/faiss/impl/NNDescent.h +4 -0
  111. data/vendor/faiss/faiss/impl/NSG.cpp +3 -2
  112. data/vendor/faiss/faiss/impl/Panorama.h +3 -2
  113. data/vendor/faiss/faiss/impl/PiPNN.cpp +824 -0
  114. data/vendor/faiss/faiss/impl/PiPNN.h +122 -0
  115. data/vendor/faiss/faiss/impl/PolysemousTraining.cpp +1 -1
  116. data/vendor/faiss/faiss/impl/ProductQuantizer.cpp +54 -11
  117. data/vendor/faiss/faiss/impl/RaBitQUtils.cpp +0 -2
  118. data/vendor/faiss/faiss/impl/RaBitQUtils.h +30 -1
  119. data/vendor/faiss/faiss/impl/RaBitQuantizer.cpp +91 -66
  120. data/vendor/faiss/faiss/impl/RaBitQuantizer.h +15 -0
  121. data/vendor/faiss/faiss/impl/ResultHandler.h +116 -0
  122. data/vendor/faiss/faiss/impl/ScalarQuantizer.cpp +29 -0
  123. data/vendor/faiss/faiss/impl/ScalarQuantizer.h +1 -6
  124. data/vendor/faiss/faiss/impl/approx_topk/avx2.cpp +0 -4
  125. data/vendor/faiss/faiss/impl/approx_topk/neon.cpp +0 -4
  126. data/vendor/faiss/faiss/impl/binary_hamming/IndexBinaryHash_impl.h +5 -2
  127. data/vendor/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h +1 -3
  128. data/vendor/faiss/faiss/impl/binary_hamming/avx2.cpp +0 -4
  129. data/vendor/faiss/faiss/impl/binary_hamming/avx512.cpp +0 -4
  130. data/vendor/faiss/faiss/impl/binary_hamming/neon.cpp +0 -4
  131. data/vendor/faiss/faiss/impl/binary_hamming/rvv.cpp +0 -4
  132. data/vendor/faiss/faiss/impl/expanded_scanners.h +93 -0
  133. data/vendor/faiss/faiss/impl/fast_scan/FastScanDistancePostProcessing.h +4 -0
  134. data/vendor/faiss/faiss/impl/fast_scan/accumulate_loops.h +61 -64
  135. data/vendor/faiss/faiss/impl/fast_scan/accumulate_loops_512.h +13 -14
  136. data/vendor/faiss/faiss/impl/fast_scan/decompose_qbs.h +17 -129
  137. data/vendor/faiss/faiss/impl/fast_scan/dispatching.h +25 -19
  138. data/vendor/faiss/faiss/impl/fast_scan/fast_scan.cpp +73 -6
  139. data/vendor/faiss/faiss/impl/fast_scan/fast_scan.h +43 -0
  140. data/vendor/faiss/faiss/impl/fast_scan/impl-avx2.cpp +15 -4
  141. data/vendor/faiss/faiss/impl/fast_scan/impl-avx512.cpp +115 -4
  142. data/vendor/faiss/faiss/impl/fast_scan/impl-neon.cpp +10 -85
  143. data/vendor/faiss/faiss/impl/fast_scan/impl-riscv.cpp +0 -4
  144. data/vendor/faiss/faiss/impl/fast_scan/kernels_neon.h +155 -0
  145. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd256.h +106 -1
  146. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd512.h +3 -6
  147. data/vendor/faiss/faiss/impl/fast_scan/rabitq_result_handler.h +0 -1
  148. data/vendor/faiss/faiss/impl/fast_scan/simd_result_handlers.h +105 -78
  149. data/vendor/faiss/faiss/impl/hnsw/LockVector.h +1 -2
  150. data/vendor/faiss/faiss/impl/hnsw/avx2.cpp +0 -4
  151. data/vendor/faiss/faiss/impl/hnsw/avx512.cpp +0 -4
  152. data/vendor/faiss/faiss/impl/index_read.cpp +318 -9
  153. data/vendor/faiss/faiss/impl/index_write.cpp +124 -5
  154. data/vendor/faiss/faiss/impl/io.cpp +1 -0
  155. data/vendor/faiss/faiss/impl/io_macros.h +2 -2
  156. data/vendor/faiss/faiss/impl/mapped_io.cpp +3 -1
  157. data/vendor/faiss/faiss/impl/maybe_owned_vector.h +78 -41
  158. data/vendor/faiss/faiss/impl/nndescent/gram-avx2.cpp +121 -0
  159. data/vendor/faiss/faiss/impl/nndescent/gram-avx512.cpp +124 -0
  160. data/vendor/faiss/faiss/impl/nndescent/gram-neon.cpp +114 -0
  161. data/vendor/faiss/faiss/impl/nndescent/gram.h +66 -0
  162. data/vendor/faiss/faiss/impl/optimal_kmeans/BlockCombiner-avx512.cpp +431 -0
  163. data/vendor/faiss/faiss/impl/optimal_kmeans/BlockCombiner-inl.h +1157 -0
  164. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeans.cpp +282 -0
  165. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeans.h +226 -0
  166. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeansCompressed.cpp +1567 -0
  167. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeansCompressed.h +281 -0
  168. data/vendor/faiss/faiss/impl/pipnn/HashPrune.cpp +159 -0
  169. data/vendor/faiss/faiss/impl/pipnn/HashPrune.h +69 -0
  170. data/vendor/faiss/faiss/impl/pipnn/Partition.cpp +587 -0
  171. data/vendor/faiss/faiss/impl/pipnn/Partition.h +93 -0
  172. data/vendor/faiss/faiss/impl/pipnn/kernels.cpp +326 -0
  173. data/vendor/faiss/faiss/impl/pipnn/kernels.h +92 -0
  174. data/vendor/faiss/faiss/impl/platform_macros.h +91 -27
  175. data/vendor/faiss/faiss/impl/polysemous_training/avx512.cpp +0 -4
  176. data/vendor/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h +84 -4
  177. data/vendor/faiss/faiss/impl/pq_code_distance/IVFPQ_QueryTables.cpp +17 -17
  178. data/vendor/faiss/faiss/impl/pq_code_distance/PQDistanceComputer_impl.h +6 -0
  179. data/vendor/faiss/faiss/impl/pq_code_distance/avx2.cpp +0 -4
  180. data/vendor/faiss/faiss/impl/pq_code_distance/avx512.cpp +0 -4
  181. data/vendor/faiss/faiss/impl/pq_code_distance/neon.cpp +0 -4
  182. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx2.h +4 -0
  183. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx512.h +4 -1
  184. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.cpp +19 -0
  185. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.h +6 -6
  186. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-inl.h +131 -6
  187. data/vendor/faiss/faiss/impl/pq_code_distance/pq_code_distance-sve.cpp +0 -4
  188. data/vendor/faiss/faiss/impl/pq_code_distance/pq_rvv_kernel.h +89 -0
  189. data/vendor/faiss/faiss/impl/pq_code_distance/pq_scan_impl.h +21 -10
  190. data/vendor/faiss/faiss/impl/pq_code_distance/rvv.cpp +45 -18
  191. data/vendor/faiss/faiss/impl/residual_quantizer_encode_steps.cpp +2 -1
  192. data/vendor/faiss/faiss/impl/result_handler/ResultHandler.cpp +68 -1
  193. data/vendor/faiss/faiss/impl/result_handler/avx2.cpp +70 -6
  194. data/vendor/faiss/faiss/impl/result_handler/avx512.cpp +2 -5
  195. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx2.cpp +0 -4
  196. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx512.cpp +0 -4
  197. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp +1 -1
  198. data/vendor/faiss/faiss/impl/scalar_quantizer/distance_computers.h +5 -1
  199. data/vendor/faiss/faiss/impl/scalar_quantizer/quantizers.h +28 -52
  200. data/vendor/faiss/faiss/impl/scalar_quantizer/scanners.h +85 -37
  201. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp +262 -110
  202. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h +503 -122
  203. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp +10 -155
  204. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp +7 -701
  205. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-dispatch.h +66 -57
  206. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp +133 -127
  207. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-rvv.cpp +3185 -144
  208. data/vendor/faiss/faiss/impl/scalar_quantizer/sq8_coefficients.h +48 -0
  209. data/vendor/faiss/faiss/impl/scalar_quantizer/sq8_rvv_kernel.h +546 -0
  210. data/vendor/faiss/faiss/impl/scalar_quantizer/training.cpp +2 -2
  211. data/vendor/faiss/faiss/impl/simd_dispatch.h +7 -0
  212. data/vendor/faiss/faiss/impl/simdlib/simdlib_avx2.h +14 -0
  213. data/vendor/faiss/faiss/impl/simdlib/simdlib_avx512.h +20 -20
  214. data/vendor/faiss/faiss/impl/simdlib/simdlib_dispatch.h +7 -8
  215. data/vendor/faiss/faiss/impl/simdlib/simdlib_neon.h +4 -4
  216. data/vendor/faiss/faiss/impl/sq_fastscan_utils.h +232 -0
  217. data/vendor/faiss/faiss/impl/zerocopy_io.cpp +2 -1
  218. data/vendor/faiss/faiss/index_factory.cpp +106 -6
  219. data/vendor/faiss/faiss/invlists/DirectMap.cpp +1 -1
  220. data/vendor/faiss/faiss/invlists/DiskIOBackend.cpp +121 -0
  221. data/vendor/faiss/faiss/invlists/DiskIOBackend.h +71 -0
  222. data/vendor/faiss/faiss/invlists/InvertedLists.cpp +15 -10
  223. data/vendor/faiss/faiss/invlists/InvertedListsIOHook.cpp +26 -0
  224. data/vendor/faiss/faiss/invlists/InvertedListsIOHook.h +5 -0
  225. data/vendor/faiss/faiss/invlists/OnDiskInvertedLists.cpp +9 -24
  226. data/vendor/faiss/faiss/invlists/RaBitQSSDInvertedLists.cpp +751 -0
  227. data/vendor/faiss/faiss/invlists/RaBitQSSDInvertedLists.h +224 -0
  228. data/vendor/faiss/faiss/svs/IndexSVSFaissUtils.h +2 -7
  229. data/vendor/faiss/faiss/svs/IndexSVSFlat.cpp +1 -1
  230. data/vendor/faiss/faiss/svs/IndexSVSIVF.cpp +2 -2
  231. data/vendor/faiss/faiss/svs/IndexSVSVamana.cpp +4 -4
  232. data/vendor/faiss/faiss/svs/IndexSVSVamana.h +3 -2
  233. data/vendor/faiss/faiss/utils/AlignedTable.h +6 -1
  234. data/vendor/faiss/faiss/utils/Heap.cpp +4 -3
  235. data/vendor/faiss/faiss/utils/WorkerThread.h +0 -1
  236. data/vendor/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h +16 -5
  237. data/vendor/faiss/faiss/utils/bf16.h +36 -0
  238. data/vendor/faiss/faiss/utils/distances.cpp +466 -43
  239. data/vendor/faiss/faiss/utils/distances.h +179 -2
  240. data/vendor/faiss/faiss/utils/distances_dispatch.h +6 -4
  241. data/vendor/faiss/faiss/utils/distances_fused/avx512.cpp +2 -5
  242. data/vendor/faiss/faiss/utils/distances_fused/distances_fused.cpp +0 -14
  243. data/vendor/faiss/faiss/utils/distances_fused/rvv.cpp +25 -0
  244. data/vendor/faiss/faiss/utils/distances_fused/simdlib_based.cpp +0 -4
  245. data/vendor/faiss/faiss/utils/distances_fused/simdlib_based_neon.cpp +0 -4
  246. data/vendor/faiss/faiss/utils/distances_fused/simdlib_kernel-inl.h +2 -1
  247. data/vendor/faiss/faiss/utils/distances_simd.cpp +9 -0
  248. data/vendor/faiss/faiss/utils/extra_distances.h +2 -1
  249. data/vendor/faiss/faiss/utils/fp16-fp16c.h +4 -0
  250. data/vendor/faiss/faiss/utils/fp16-inl.h +26 -52
  251. data/vendor/faiss/faiss/utils/hamming-inl.h +3 -0
  252. data/vendor/faiss/faiss/utils/hamming_distance/hamming_avx2.cpp +0 -4
  253. data/vendor/faiss/faiss/utils/hamming_distance/hamming_avx512.cpp +0 -4
  254. data/vendor/faiss/faiss/utils/hamming_distance/hamming_avx512_vpopcnt.cpp +0 -4
  255. data/vendor/faiss/faiss/utils/hamming_distance/hamming_computer-avx512.h +33 -5
  256. data/vendor/faiss/faiss/utils/hamming_distance/hamming_computer-avx512_vpopcnt.h +15 -30
  257. data/vendor/faiss/faiss/utils/hamming_distance/hamming_computer-neon.h +0 -4
  258. data/vendor/faiss/faiss/utils/hamming_distance/hamming_impl.h +2 -1
  259. data/vendor/faiss/faiss/utils/hamming_distance/hamming_neon.cpp +0 -4
  260. data/vendor/faiss/faiss/utils/hamming_distance/hamming_rvv.cpp +0 -4
  261. data/vendor/faiss/faiss/utils/partitioning.cpp +2 -2
  262. data/vendor/faiss/faiss/utils/pq_code_distance.h +8 -4
  263. data/vendor/faiss/faiss/utils/prefetch.h +1 -26
  264. data/vendor/faiss/faiss/utils/quantize_lut.cpp +26 -27
  265. data/vendor/faiss/faiss/utils/quantize_lut.h +11 -0
  266. data/vendor/faiss/faiss/utils/rabitq_simd.h +171 -22
  267. data/vendor/faiss/faiss/utils/simd_impl/distances_aarch64.cpp +9 -4
  268. data/vendor/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp +81 -9
  269. data/vendor/faiss/faiss/utils/simd_impl/distances_autovec-inl.h +7 -3
  270. data/vendor/faiss/faiss/utils/simd_impl/distances_avx2.cpp +108 -9
  271. data/vendor/faiss/faiss/utils/simd_impl/distances_avx512.cpp +111 -12
  272. data/vendor/faiss/faiss/utils/simd_impl/distances_rvv.cpp +353 -71
  273. data/vendor/faiss/faiss/utils/simd_impl/distances_rvv_kernel.h +68 -0
  274. data/vendor/faiss/faiss/utils/simd_impl/distances_simdlib256.h +3 -3
  275. data/vendor/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h +106 -0
  276. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels.h +76 -0
  277. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels_avx2.cpp +52 -0
  278. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels_avx512.cpp +52 -0
  279. data/vendor/faiss/faiss/utils/simd_impl/fp16_kernels_neon.cpp +48 -0
  280. data/vendor/faiss/faiss/utils/simd_impl/masked_sum-avx2.h +44 -0
  281. data/vendor/faiss/faiss/utils/simd_impl/masked_sum-avx512.h +43 -0
  282. data/vendor/faiss/faiss/utils/simd_impl/masked_sum.h +38 -0
  283. data/vendor/faiss/faiss/utils/simd_impl/partitioning_avx2.cpp +0 -4
  284. data/vendor/faiss/faiss/utils/simd_impl/partitioning_neon.cpp +0 -4
  285. data/vendor/faiss/faiss/utils/simd_impl/partitioning_simdlib256.h +16 -15
  286. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp +185 -51
  287. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp +194 -66
  288. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx512_vpopcnt.cpp +51 -14
  289. data/vendor/faiss/faiss/utils/simd_impl/rabitq_neon.cpp +297 -10
  290. data/vendor/faiss/faiss/utils/simd_impl/rabitq_rvv.cpp +0 -4
  291. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx2.cpp +0 -4
  292. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx512.cpp +0 -4
  293. data/vendor/faiss/faiss/utils/simd_impl/super_kmeans_kernels_sve.cpp +0 -4
  294. data/vendor/faiss/faiss/utils/simd_levels.cpp +22 -6
  295. data/vendor/faiss/faiss/utils/simd_levels.h +74 -1
  296. data/vendor/faiss/faiss/utils/sorting.cpp +6 -5
  297. data/vendor/faiss/faiss/utils/transpose/transpose-avx2-inl.h +0 -4
  298. data/vendor/faiss/faiss/utils/transpose/transpose-avx512-inl.h +0 -4
  299. data/vendor/faiss/faiss/utils/utils.cpp +84 -0
  300. data/vendor/faiss/faiss/utils/utils.h +24 -0
  301. metadata +52 -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
@@ -0,0 +1,63 @@
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ #include <faiss/impl/DistanceComputer.h>
9
+
10
+ #include <faiss/impl/FaissAssert.h>
11
+
12
+ namespace faiss {
13
+
14
+ void DistanceComputer::distances_batch_4(
15
+ const idx_t idx0,
16
+ const idx_t idx1,
17
+ const idx_t idx2,
18
+ const idx_t idx3,
19
+ float& dis0,
20
+ float& dis1,
21
+ float& dis2,
22
+ float& dis3) {
23
+ // compute first, assign next
24
+ const float d0 = this->operator()(idx0);
25
+ const float d1 = this->operator()(idx1);
26
+ const float d2 = this->operator()(idx2);
27
+ const float d3 = this->operator()(idx3);
28
+ dis0 = d0;
29
+ dis1 = d1;
30
+ dis2 = d2;
31
+ dis3 = d3;
32
+ }
33
+
34
+ float FlatCodesDistanceComputer::partial_dot_product(
35
+ const idx_t /* i */,
36
+ const uint32_t /* offset */,
37
+ const uint32_t /* num_components */) {
38
+ FAISS_THROW_MSG("partial_dot_product not implemented");
39
+ }
40
+
41
+ void FlatCodesDistanceComputer::partial_dot_product_batch_4(
42
+ const idx_t idx0,
43
+ const idx_t idx1,
44
+ const idx_t idx2,
45
+ const idx_t idx3,
46
+ float& dp0,
47
+ float& dp1,
48
+ float& dp2,
49
+ float& dp3,
50
+ const uint32_t offset,
51
+ const uint32_t num_components) {
52
+ // default implementation for correctness
53
+ const float d0 = this->partial_dot_product(idx0, offset, num_components);
54
+ const float d1 = this->partial_dot_product(idx1, offset, num_components);
55
+ const float d2 = this->partial_dot_product(idx2, offset, num_components);
56
+ const float d3 = this->partial_dot_product(idx3, offset, num_components);
57
+ dp0 = d0;
58
+ dp1 = d1;
59
+ dp2 = d2;
60
+ dp3 = d3;
61
+ }
62
+
63
+ } // namespace faiss
@@ -41,17 +41,7 @@ struct DistanceComputer {
41
41
  float& dis0,
42
42
  float& dis1,
43
43
  float& dis2,
44
- float& dis3) {
45
- // compute first, assign next
46
- const float d0 = this->operator()(idx0);
47
- const float d1 = this->operator()(idx1);
48
- const float d2 = this->operator()(idx2);
49
- const float d3 = this->operator()(idx3);
50
- dis0 = d0;
51
- dis1 = d1;
52
- dis2 = d2;
53
- dis3 = d3;
54
- }
44
+ float& dis3);
55
45
 
56
46
  /// compute distance between two stored vectors
57
47
  virtual float symmetric_dis(idx_t i, idx_t j) = 0;
@@ -181,9 +171,7 @@ struct FlatCodesDistanceComputer : DistanceComputer {
181
171
  virtual float partial_dot_product(
182
172
  const idx_t /* i */,
183
173
  const uint32_t /* offset */,
184
- const uint32_t /* num_components */) {
185
- FAISS_THROW_MSG("partial_dot_product not implemented");
186
- }
174
+ const uint32_t /* num_components */);
187
175
 
188
176
  /// compute distance of current query to an encoded vector
189
177
  virtual float distance_to_code(const uint8_t* code) = 0;
@@ -214,21 +202,7 @@ struct FlatCodesDistanceComputer : DistanceComputer {
214
202
  float& dp2,
215
203
  float& dp3,
216
204
  const uint32_t offset,
217
- const uint32_t num_components) {
218
- // default implementation for correctness
219
- const float d0 =
220
- this->partial_dot_product(idx0, offset, num_components);
221
- const float d1 =
222
- this->partial_dot_product(idx1, offset, num_components);
223
- const float d2 =
224
- this->partial_dot_product(idx2, offset, num_components);
225
- const float d3 =
226
- this->partial_dot_product(idx3, offset, num_components);
227
- dp0 = d0;
228
- dp1 = d1;
229
- dp2 = d2;
230
- dp3 = d3;
231
- }
205
+ const uint32_t num_components);
232
206
 
233
207
  virtual ~FlatCodesDistanceComputer() override {}
234
208
  };
@@ -1568,6 +1568,8 @@ void reservePriorityQueue(
1568
1568
  /// Templated body of `search_from_candidate_unbounded`. The choice of
1569
1569
  /// max-heap vs min-heap for both `top_candidates` and `candidates` is
1570
1570
  /// derived from C via `TopCandidatesQueue` / `CandidatesQueue`.
1571
+ /// `sel` filters the results only. The traversal still visits the rejected
1572
+ /// nodes.
1571
1573
  template <typename VTType, class C>
1572
1574
  TopCandidatesQueue<C> search_from_candidate_unbounded_fixVT(
1573
1575
  const HNSW& hnsw,
@@ -1575,16 +1577,48 @@ TopCandidatesQueue<C> search_from_candidate_unbounded_fixVT(
1575
1577
  DistanceComputer& qdis,
1576
1578
  int ef,
1577
1579
  VTType& vt,
1578
- HNSWStats& stats) {
1580
+ HNSWStats& stats,
1581
+ const IDSelector* sel) {
1582
+ const auto max_size = static_cast<size_t>(ef);
1583
+
1579
1584
  int ndis = 0;
1585
+ // `top_candidates` bounds the traversal and keeps the nodes that `sel`
1586
+ // rejects, because a rejected node is still a valid hop towards an
1587
+ // accepted one.
1580
1588
  TopCandidatesQueue<C> top_candidates;
1581
1589
  reservePriorityQueue(top_candidates, ef);
1582
1590
 
1591
+ // `selected_candidates` keeps only the accepted nodes, and
1592
+ // the function returns it instead when `sel` is set.
1593
+ TopCandidatesQueue<C> selected_candidates;
1594
+ if (sel) {
1595
+ reservePriorityQueue(selected_candidates, ef);
1596
+ }
1597
+
1583
1598
  CandidatesQueue<C> candidates;
1584
1599
  reservePriorityQueue(candidates, ef);
1585
1600
 
1601
+ // Adds a node to a queue of the best `max_size` nodes. The size test
1602
+ // comes first because `top()` needs a queue that is not empty.
1603
+ auto push_bounded = [max_size](
1604
+ TopCandidatesQueue<C>& queue,
1605
+ const float dis,
1606
+ const size_t idx) {
1607
+ if (queue.size() >= max_size && !C::cmp(queue.top().first, dis)) {
1608
+ return false;
1609
+ }
1610
+ queue.emplace(dis, idx);
1611
+ if (queue.size() > max_size) {
1612
+ queue.pop();
1613
+ }
1614
+ return true;
1615
+ };
1616
+
1586
1617
  top_candidates.push(node);
1587
1618
  candidates.push(node);
1619
+ if (sel && sel->is_member(node.second)) {
1620
+ selected_candidates.push(node);
1621
+ }
1588
1622
 
1589
1623
  vt.set(node.second);
1590
1624
 
@@ -1619,14 +1653,11 @@ TopCandidatesQueue<C> search_from_candidate_unbounded_fixVT(
1619
1653
  size_t saved_j[4];
1620
1654
 
1621
1655
  auto add_to_heap = [&](const size_t idx, const float dis) {
1622
- if (C::cmp(top_candidates.top().first, dis) ||
1623
- top_candidates.size() < static_cast<size_t>(ef)) {
1656
+ if (sel && sel->is_member(idx)) {
1657
+ push_bounded(selected_candidates, dis, idx);
1658
+ }
1659
+ if (push_bounded(top_candidates, dis, idx)) {
1624
1660
  candidates.emplace(dis, idx);
1625
- top_candidates.emplace(dis, idx);
1626
-
1627
- if (top_candidates.size() > static_cast<size_t>(ef)) {
1628
- top_candidates.pop();
1629
- }
1630
1661
  }
1631
1662
  };
1632
1663
 
@@ -1674,6 +1705,9 @@ TopCandidatesQueue<C> search_from_candidate_unbounded_fixVT(
1674
1705
  }
1675
1706
  stats.ndis += ndis;
1676
1707
 
1708
+ if (sel) {
1709
+ return selected_candidates;
1710
+ }
1677
1711
  return top_candidates;
1678
1712
  }
1679
1713
 
@@ -1693,7 +1727,7 @@ std::priority_queue<HNSW::Node> hnsw_detail::search_from_candidate_unbounded(
1693
1727
  using C = HNSW::C_distance;
1694
1728
  auto call = [&]<typename VTType>(VTType& vt_concrete) {
1695
1729
  return search_from_candidate_unbounded_fixVT<VTType, C>(
1696
- hnsw, node, qdis, ef, vt_concrete, stats);
1730
+ hnsw, node, qdis, ef, vt_concrete, stats, nullptr);
1697
1731
  };
1698
1732
  if (VisitedTableVector* vtv = dynamic_cast<VisitedTableVector*>(vt)) {
1699
1733
  return call(*vtv);
@@ -1792,6 +1826,7 @@ HNSWStats search_impl(
1792
1826
  hnsw.search_method == HNSW::SM_DEFAULT ||
1793
1827
  hnsw.search_method == HNSW::SM_PANORAMA,
1794
1828
  "invalid HNSW search method");
1829
+ const IDSelector* sel = params ? params->sel : nullptr;
1795
1830
  auto call = [&]<typename VTType>(VTType& vt_concrete) {
1796
1831
  return search_from_candidate_unbounded_fixVT<VTType, C>(
1797
1832
  hnsw,
@@ -1799,7 +1834,8 @@ HNSWStats search_impl(
1799
1834
  qdis,
1800
1835
  ef,
1801
1836
  vt_concrete,
1802
- stats);
1837
+ stats,
1838
+ sel);
1803
1839
  };
1804
1840
  TopCandidatesQueue<C> top_candidates;
1805
1841
  if (VisitedTableVector* vtv = dynamic_cast<VisitedTableVector*>(&vt)) {
@@ -2012,8 +2048,8 @@ void HNSW::permute_entries(const idx_t* map) {
2012
2048
  }
2013
2049
  assert(new_offsets[ntotal] == offsets[ntotal]);
2014
2050
  // swap everyone
2015
- std::swap(levels, new_levels);
2016
- std::swap(offsets, new_offsets);
2051
+ levels = std::move(new_levels);
2052
+ offsets = std::move(new_offsets);
2017
2053
  neighbors = std::move(new_neighbors);
2018
2054
  }
2019
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.
@@ -296,6 +296,76 @@ void hnsw_add_vertices_deterministic(
296
296
  const std::function<void(DistanceComputer&, HNSW::storage_idx_t)>&
297
297
  set_query);
298
298
 
299
+ /// Parameters of add_level_0_links_from_sample() of IndexHNSW and
300
+ /// IndexBinaryHNSW.
301
+ struct HNSWLevel0LinkParameters {
302
+ /// The search that the new links are for. nullptr: the search settings
303
+ /// of the index, which the IVF assignment with a coarse quantizer uses.
304
+ const SearchParametersHNSW* search_params = nullptr;
305
+ /// A sink receives at least this factor times the mean number of
306
+ /// vectors per node.
307
+ float min_mean_factor = 3.0f;
308
+ /// For at least this fraction of the vectors that the search sends to a
309
+ /// sink, an exact search finds a nearer node.
310
+ float min_closer_fraction = 0.5f;
311
+ /// Maximum number of level-0 links added to one sink in one round.
312
+ int max_links_per_sink = 32;
313
+ /// Maximum number of rounds that find sinks and add links.
314
+ int max_rounds = 3;
315
+ };
316
+
317
+ struct HNSWLevel0LinkStats {
318
+ /// Sinks found in the first round.
319
+ size_t n_sinks_found = 0;
320
+ /// Sinks found after the last round.
321
+ size_t n_sinks_remaining = 0;
322
+ /// Level-0 links written into free slots.
323
+ size_t n_links_added = 0;
324
+ /// Level-0 links that replaced a link.
325
+ size_t n_links_replaced = 0;
326
+ /// Rounds that changed links.
327
+ int n_rounds = 0;
328
+ /// Exact searches with the storage, in all rounds.
329
+ size_t n_exact_searches = 0;
330
+ };
331
+
332
+ /** The two searches of the sample vectors that
333
+ * hnsw_add_level_0_links_from_sample() compares. IndexHNSW and IndexBinaryHNSW
334
+ * implement them for their vector types. */
335
+ struct HNSWLinkSampleSearch {
336
+ /// number of sample vectors
337
+ idx_t n = 0;
338
+
339
+ virtual ~HNSWLinkSampleSearch() = default;
340
+
341
+ /// HNSW search (k = 1) of the m sample vectors `ids` (null: the first m).
342
+ virtual void search(
343
+ const SearchParametersHNSW* params,
344
+ size_t m,
345
+ const idx_t* ids,
346
+ idx_t* labels) const = 0;
347
+
348
+ /** Exact search (k = 1) of the m sample vectors `ids`. nearer[j] is 1 when
349
+ * exact[j] is nearer than found[j] by more than rounding differences. */
350
+ virtual void search_exact(
351
+ size_t m,
352
+ const idx_t* ids,
353
+ const idx_t* found,
354
+ idx_t* exact,
355
+ uint8_t* nearer) const = 0;
356
+ };
357
+
358
+ /** add_level_0_links_from_sample() of IndexHNSW and IndexBinaryHNSW.
359
+ * `dis` computes distances between nodes. `similarity` is true when a larger
360
+ * distance is nearer. */
361
+ HNSWLevel0LinkStats hnsw_add_level_0_links_from_sample(
362
+ HNSW& hnsw,
363
+ size_t ntotal,
364
+ DistanceComputer& dis,
365
+ bool similarity,
366
+ const HNSWLinkSampleSearch& sample,
367
+ const HNSWLevel0LinkParameters& params);
368
+
299
369
  struct HNSWStats {
300
370
  size_t n1 = 0; /// number of vectors searched
301
371
  size_t n2 =
@@ -315,6 +385,8 @@ struct HNSWStats {
315
385
  ndis += other.ndis;
316
386
  nhops += other.nhops;
317
387
  }
388
+
389
+ void combine_atomic(const HNSWStats& other);
318
390
  };
319
391
 
320
392
  // global var that collects them all
@@ -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 {