faiss 0.6.5 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +5 -0
  3. data/ext/faiss/extconf.rb +1 -0
  4. data/ext/faiss/index.cpp +42 -0
  5. data/lib/faiss/version.rb +1 -1
  6. data/vendor/faiss/faiss/IVFlib.cpp +48 -51
  7. data/vendor/faiss/faiss/IVFlib.h +6 -2
  8. data/vendor/faiss/faiss/Index.cpp +2 -2
  9. data/vendor/faiss/faiss/Index.h +3 -3
  10. data/vendor/faiss/faiss/IndexBinary.cpp +2 -2
  11. data/vendor/faiss/faiss/IndexBinary.h +2 -2
  12. data/vendor/faiss/faiss/IndexBinaryFlat.cpp +1 -0
  13. data/vendor/faiss/faiss/IndexBinaryHNSW.cpp +6 -3
  14. data/vendor/faiss/faiss/IndexBinaryIVF.cpp +6 -11
  15. data/vendor/faiss/faiss/IndexFastScan.cpp +1 -1
  16. data/vendor/faiss/faiss/IndexFlat.cpp +1 -1
  17. data/vendor/faiss/faiss/IndexHNSW.cpp +12 -10
  18. data/vendor/faiss/faiss/IndexHNSW.h +2 -5
  19. data/vendor/faiss/faiss/IndexIDMap.cpp +17 -4
  20. data/vendor/faiss/faiss/IndexIDMap.h +10 -5
  21. data/vendor/faiss/faiss/IndexIVF.cpp +68 -37
  22. data/vendor/faiss/faiss/IndexIVF.h +37 -1
  23. data/vendor/faiss/faiss/IndexIVFFastScan.cpp +5 -15
  24. data/vendor/faiss/faiss/IndexIVFFlat.h +6 -6
  25. data/vendor/faiss/faiss/IndexIVFPQFastScan.cpp +1 -1
  26. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.cpp +28 -44
  27. data/vendor/faiss/faiss/IndexIVFRaBitQFastScan.h +2 -11
  28. data/vendor/faiss/faiss/IndexIVFRaBitQSSD.cpp +1694 -0
  29. data/vendor/faiss/faiss/IndexIVFRaBitQSSD.h +288 -0
  30. data/vendor/faiss/faiss/IndexIVFSQFastScan.cpp +7 -2
  31. data/vendor/faiss/faiss/IndexNNDescent.cpp +21 -0
  32. data/vendor/faiss/faiss/IndexRaBitQ.cpp +189 -41
  33. data/vendor/faiss/faiss/IndexRaBitQ.h +5 -0
  34. data/vendor/faiss/faiss/IndexRaBitQFastScan.cpp +1 -1
  35. data/vendor/faiss/faiss/IndexRaBitQFastScan.h +2 -2
  36. data/vendor/faiss/faiss/SuperKMeans.cpp +2 -2
  37. data/vendor/faiss/faiss/VectorTransform.cpp +156 -9
  38. data/vendor/faiss/faiss/VectorTransform.h +24 -1
  39. data/vendor/faiss/faiss/factory_tools.cpp +19 -1
  40. data/vendor/faiss/faiss/gpu/Dataset.h +66 -14
  41. data/vendor/faiss/faiss/gpu/GpuIndexBinaryCagra.h +8 -2
  42. data/vendor/faiss/faiss/gpu/GpuIndexCagra.h +8 -2
  43. data/vendor/faiss/faiss/gpu/impl/optimal_kmeans/GpuOptimalKMeans.h +184 -0
  44. data/vendor/faiss/faiss/gpu/test/TestCodePacking.cpp +12 -4
  45. data/vendor/faiss/faiss/gpu/test/TestUtils.cpp +6 -5
  46. data/vendor/faiss/faiss/gpu_metal/GpuIndexFlat.h +1 -1
  47. data/vendor/faiss/faiss/gpu_metal/MetalCloner.h +1 -1
  48. data/vendor/faiss/faiss/gpu_metal/MetalDistance.h +1 -1
  49. data/vendor/faiss/faiss/gpu_metal/MetalFlatKernels.h +1 -1
  50. data/vendor/faiss/faiss/gpu_metal/MetalIndex.h +1 -1
  51. data/vendor/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.h +1 -1
  52. data/vendor/faiss/faiss/gpu_metal/MetalIndexFlat.h +1 -1
  53. data/vendor/faiss/faiss/gpu_metal/MetalIndexIVFFlat.h +1 -1
  54. data/vendor/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h +1 -1
  55. data/vendor/faiss/faiss/gpu_metal/MetalKernels.h +1 -1
  56. data/vendor/faiss/faiss/gpu_metal/MetalPythonBridge.h +1 -1
  57. data/vendor/faiss/faiss/gpu_metal/MetalResources.h +1 -1
  58. data/vendor/faiss/faiss/gpu_metal/StandardMetalResources.h +1 -1
  59. data/vendor/faiss/faiss/gpu_metal/impl/MetalIVFFlat.h +1 -1
  60. data/vendor/faiss/faiss/gpu_metal/impl/MetalIVFPQ.h +1 -1
  61. data/vendor/faiss/faiss/impl/AuxIndexStructures.cpp +1 -1
  62. data/vendor/faiss/faiss/impl/ClusteringInitialization.cpp +31 -50
  63. data/vendor/faiss/faiss/impl/ClusteringInitialization.h +0 -15
  64. data/vendor/faiss/faiss/impl/CodePacker.cpp +2 -2
  65. data/vendor/faiss/faiss/impl/CodePackerRaBitQ.cpp +2 -2
  66. data/vendor/faiss/faiss/impl/DeterministicNNDescent.cpp +2167 -0
  67. data/vendor/faiss/faiss/impl/DeterministicNNDescent.h +301 -0
  68. data/vendor/faiss/faiss/impl/HNSW.cpp +2 -2
  69. data/vendor/faiss/faiss/impl/HNSW.h +2 -2
  70. data/vendor/faiss/faiss/impl/IDSelector.h +5 -4
  71. data/vendor/faiss/faiss/impl/NNDescent.h +4 -0
  72. data/vendor/faiss/faiss/impl/PiPNN.cpp +4 -2
  73. data/vendor/faiss/faiss/impl/PiPNN.h +1 -1
  74. data/vendor/faiss/faiss/impl/PolysemousTraining.cpp +1 -1
  75. data/vendor/faiss/faiss/impl/RaBitQUtils.cpp +0 -2
  76. data/vendor/faiss/faiss/impl/RaBitQUtils.h +29 -0
  77. data/vendor/faiss/faiss/impl/RaBitQuantizer.cpp +14 -13
  78. data/vendor/faiss/faiss/impl/ResultHandler.h +116 -0
  79. data/vendor/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h +1 -3
  80. data/vendor/faiss/faiss/impl/expanded_scanners.h +29 -24
  81. data/vendor/faiss/faiss/impl/fast_scan/fast_scan.cpp +68 -6
  82. data/vendor/faiss/faiss/impl/fast_scan/fast_scan.h +43 -0
  83. data/vendor/faiss/faiss/impl/fast_scan/impl-avx2.cpp +15 -0
  84. data/vendor/faiss/faiss/impl/fast_scan/impl-avx512.cpp +115 -0
  85. data/vendor/faiss/faiss/impl/fast_scan/impl-neon.cpp +13 -0
  86. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd256.h +84 -0
  87. data/vendor/faiss/faiss/impl/fast_scan/kernels_simd512.h +0 -4
  88. data/vendor/faiss/faiss/impl/fast_scan/rabitq_result_handler.h +0 -1
  89. data/vendor/faiss/faiss/impl/fast_scan/simd_result_handlers.h +64 -55
  90. data/vendor/faiss/faiss/impl/hnsw/LockVector.h +1 -2
  91. data/vendor/faiss/faiss/impl/index_read.cpp +146 -9
  92. data/vendor/faiss/faiss/impl/index_write.cpp +29 -5
  93. data/vendor/faiss/faiss/impl/io.cpp +1 -0
  94. data/vendor/faiss/faiss/impl/io_macros.h +2 -2
  95. data/vendor/faiss/faiss/impl/mapped_io.cpp +3 -1
  96. data/vendor/faiss/faiss/impl/maybe_owned_vector.h +78 -41
  97. data/vendor/faiss/faiss/impl/nndescent/gram-avx2.cpp +121 -0
  98. data/vendor/faiss/faiss/impl/nndescent/gram-avx512.cpp +124 -0
  99. data/vendor/faiss/faiss/impl/nndescent/gram-neon.cpp +114 -0
  100. data/vendor/faiss/faiss/impl/nndescent/gram.h +66 -0
  101. data/vendor/faiss/faiss/impl/optimal_kmeans/BlockCombiner-avx512.cpp +431 -0
  102. data/vendor/faiss/faiss/impl/optimal_kmeans/BlockCombiner-inl.h +1157 -0
  103. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeans.cpp +282 -0
  104. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeans.h +226 -0
  105. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeansCompressed.cpp +1567 -0
  106. data/vendor/faiss/faiss/impl/optimal_kmeans/OptimalKMeansCompressed.h +281 -0
  107. data/vendor/faiss/faiss/impl/pipnn/HashPrune.cpp +1 -1
  108. data/vendor/faiss/faiss/impl/platform_macros.h +47 -28
  109. data/vendor/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h +6 -1
  110. data/vendor/faiss/faiss/impl/pq_code_distance/IVFPQ_QueryTables.cpp +17 -17
  111. data/vendor/faiss/faiss/impl/result_handler/ResultHandler.cpp +68 -1
  112. data/vendor/faiss/faiss/impl/result_handler/avx2.cpp +70 -2
  113. data/vendor/faiss/faiss/impl/result_handler/avx512.cpp +2 -1
  114. data/vendor/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp +1 -1
  115. data/vendor/faiss/faiss/impl/scalar_quantizer/scanners.h +26 -26
  116. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp +48 -45
  117. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h +34 -32
  118. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp +8 -6
  119. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp +4 -3
  120. data/vendor/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp +34 -33
  121. data/vendor/faiss/faiss/impl/simdlib/simdlib_avx512.h +20 -20
  122. data/vendor/faiss/faiss/impl/simdlib/simdlib_neon.h +4 -4
  123. data/vendor/faiss/faiss/impl/zerocopy_io.cpp +2 -1
  124. data/vendor/faiss/faiss/index_factory.cpp +30 -6
  125. data/vendor/faiss/faiss/invlists/DirectMap.cpp +1 -1
  126. data/vendor/faiss/faiss/invlists/DiskIOBackend.cpp +121 -0
  127. data/vendor/faiss/faiss/invlists/DiskIOBackend.h +71 -0
  128. data/vendor/faiss/faiss/invlists/InvertedLists.cpp +12 -9
  129. data/vendor/faiss/faiss/invlists/InvertedListsIOHook.cpp +26 -0
  130. data/vendor/faiss/faiss/invlists/InvertedListsIOHook.h +5 -0
  131. data/vendor/faiss/faiss/invlists/OnDiskInvertedLists.cpp +9 -24
  132. data/vendor/faiss/faiss/invlists/RaBitQSSDInvertedLists.cpp +751 -0
  133. data/vendor/faiss/faiss/invlists/RaBitQSSDInvertedLists.h +224 -0
  134. data/vendor/faiss/faiss/svs/IndexSVSFaissUtils.h +2 -7
  135. data/vendor/faiss/faiss/svs/IndexSVSFlat.cpp +1 -1
  136. data/vendor/faiss/faiss/svs/IndexSVSIVF.cpp +2 -2
  137. data/vendor/faiss/faiss/svs/IndexSVSVamana.cpp +4 -4
  138. data/vendor/faiss/faiss/utils/WorkerThread.h +0 -1
  139. data/vendor/faiss/faiss/utils/distances.cpp +246 -34
  140. data/vendor/faiss/faiss/utils/distances.h +145 -2
  141. data/vendor/faiss/faiss/utils/extra_distances.h +2 -1
  142. data/vendor/faiss/faiss/utils/hamming-inl.h +3 -0
  143. data/vendor/faiss/faiss/utils/partitioning.cpp +2 -2
  144. data/vendor/faiss/faiss/utils/rabitq_simd.h +120 -6
  145. data/vendor/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp +47 -7
  146. data/vendor/faiss/faiss/utils/simd_impl/distances_autovec-inl.h +7 -3
  147. data/vendor/faiss/faiss/utils/simd_impl/distances_avx2.cpp +47 -7
  148. data/vendor/faiss/faiss/utils/simd_impl/distances_avx512.cpp +50 -10
  149. data/vendor/faiss/faiss/utils/simd_impl/distances_simdlib256.h +3 -3
  150. data/vendor/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h +13 -0
  151. data/vendor/faiss/faiss/utils/simd_impl/partitioning_simdlib256.h +16 -15
  152. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp +131 -36
  153. data/vendor/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp +156 -45
  154. data/vendor/faiss/faiss/utils/simd_levels.cpp +3 -3
  155. data/vendor/faiss/faiss/utils/sorting.cpp +6 -5
  156. data/vendor/faiss/faiss/utils/utils.cpp +4 -0
  157. metadata +20 -1
@@ -1,5 +1,13 @@
1
1
  /*
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ * Portions 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
+ /*
9
+ * Portions Copyright 2026 Arm Limited and/or its affiliates
10
+ * <open-source-office@arm.com>
3
11
  *
4
12
  * This source code is licensed under the MIT license found in the
5
13
  * LICENSE file in the root directory of this source tree.
@@ -13,6 +21,7 @@
13
21
  #include <cstddef>
14
22
  #include <cstdio>
15
23
  #include <cstring>
24
+ #include <type_traits>
16
25
  #include <vector>
17
26
 
18
27
  #include <omp.h>
@@ -380,7 +389,8 @@ void exhaustive_inner_product_blas_tiles(
380
389
  /* block sizes */
381
390
  const size_t bs_x = distance_compute_blas_query_bs;
382
391
  const size_t bs_y = distance_compute_blas_database_bs;
383
- std::unique_ptr<float[]> ip_block(new float[bs_x * bs_y]);
392
+ std::unique_ptr<float[]> ip_block(
393
+ new float[std::min(bs_x, nx) * std::min(bs_y, ny)]);
384
394
 
385
395
  for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
386
396
  size_t i1 = i0 + bs_x;
@@ -433,17 +443,20 @@ void exhaustive_L2sqr_blas_tiles(
433
443
  size_t nx,
434
444
  size_t ny,
435
445
  BlockResultHandler& res,
436
- const float* y_norms = nullptr) {
446
+ const float* y_norms = nullptr,
447
+ size_t bs_x = distance_compute_blas_query_bs,
448
+ size_t bs_y = distance_compute_blas_database_bs) {
437
449
  // BLAS does not like empty matrices
438
450
  if (nx == 0 || ny == 0) {
439
451
  return;
440
452
  }
441
453
 
442
- /* block sizes */
443
- const size_t bs_x = distance_compute_blas_query_bs;
444
- const size_t bs_y = distance_compute_blas_database_bs;
454
+ [[maybe_unused]] constexpr bool parallel_distances = std::is_same_v<
455
+ BlockResultHandler,
456
+ Top2BlockResultHandler<CMax<float, int64_t>>>;
445
457
  // const size_t bs_x = 16, bs_y = 16;
446
- std::unique_ptr<float[]> ip_block(new float[bs_x * bs_y]);
458
+ std::unique_ptr<float[]> ip_block(
459
+ new float[std::min(bs_x, nx) * std::min(bs_y, ny)]);
447
460
  std::unique_ptr<float[]> x_norms(new float[nx]);
448
461
  std::unique_ptr<float[]> del2;
449
462
 
@@ -489,7 +502,9 @@ void exhaustive_L2sqr_blas_tiles(
489
502
  ip_block.get(),
490
503
  &nyi);
491
504
  }
492
- for (size_t i = i0; i < i1; i++) {
505
+ // The top-2 handler is too cheap to hide this pass: share it.
506
+ #pragma omp parallel for if (parallel_distances && i1 - i0 >= 16)
507
+ for (int64_t i = i0; i < static_cast<int64_t>(i1); i++) {
493
508
  float* ip_line = ip_block.get() + (i - i0) * (j1 - j0);
494
509
 
495
510
  for (size_t j = j0; j < j1; j++) {
@@ -536,9 +551,12 @@ void exhaustive_L2sqr_blas_default_impl(
536
551
  size_t nx,
537
552
  size_t ny,
538
553
  BlockResultHandler& res,
539
- const float* y_norms = nullptr) {
554
+ const float* y_norms = nullptr,
555
+ size_t bs_x = distance_compute_blas_query_bs,
556
+ size_t bs_y = distance_compute_blas_database_bs) {
540
557
  Fp32QueryTiles queries{x, d};
541
- exhaustive_L2sqr_blas_tiles(queries, y, d, nx, ny, res, y_norms);
558
+ exhaustive_L2sqr_blas_tiles(
559
+ queries, y, d, nx, ny, res, y_norms, bs_x, bs_y);
542
560
  }
543
561
 
544
562
  template <class BlockResultHandler>
@@ -549,8 +567,11 @@ void exhaustive_L2sqr_blas(
549
567
  size_t nx,
550
568
  size_t ny,
551
569
  BlockResultHandler& res,
552
- const float* y_norms = nullptr) {
553
- exhaustive_L2sqr_blas_default_impl(x, y, d, nx, ny, res, y_norms);
570
+ const float* y_norms = nullptr,
571
+ size_t bs_x = distance_compute_blas_query_bs,
572
+ size_t bs_y = distance_compute_blas_database_bs) {
573
+ exhaustive_L2sqr_blas_default_impl(
574
+ x, y, d, nx, ny, res, y_norms, bs_x, bs_y);
554
575
  }
555
576
 
556
577
  } // anonymous namespace
@@ -566,7 +587,9 @@ void exhaustive_L2sqr_blas<Top1BlockResultHandler<CMax<float, int64_t>>>(
566
587
  size_t nx,
567
588
  size_t ny,
568
589
  Top1BlockResultHandler<CMax<float, int64_t>>& res,
569
- const float* y_norms) {
590
+ const float* y_norms,
591
+ size_t bs_x,
592
+ size_t bs_y) {
570
593
  // use a faster fused kernel if available
571
594
  if (exhaustive_L2sqr_fused_cmax(x, y, d, nx, ny, res, y_norms)) {
572
595
  return;
@@ -578,11 +601,11 @@ void exhaustive_L2sqr_blas<Top1BlockResultHandler<CMax<float, int64_t>>>(
578
601
  SL == SIMDLevel::AVX2 || SL == SIMDLevel::AVX512 ||
579
602
  SL == SIMDLevel::ARM_SVE) {
580
603
  exhaustive_L2sqr_blas_cmax<SL>(
581
- x, y, d, nx, ny, res, y_norms);
604
+ x, y, d, nx, ny, res, y_norms, bs_x, bs_y);
582
605
  } else {
583
606
  exhaustive_L2sqr_blas_default_impl<
584
607
  Top1BlockResultHandler<CMax<float, int64_t>>>(
585
- x, y, d, nx, ny, res, y_norms);
608
+ x, y, d, nx, ny, res, y_norms, bs_x, bs_y);
586
609
  }
587
610
  });
588
611
  }
@@ -625,6 +648,21 @@ void exhaustive_L2sqr_blas_fp16<Top1BlockResultHandler<CMax<float, int64_t>>>(
625
648
  });
626
649
  }
627
650
 
651
+ // BLAS is faster for the small query slices that each OpenMP worker of
652
+ // IndexIVF::search passes to the quantizer, when the total work is large.
653
+ // Measured on Neoverse-V2 with ArmPL and on Neoverse-V3 with OpenBLAS,
654
+ // both on Linux. The rule applies to all GCC and Clang aarch64 builds.
655
+ bool should_use_blas(size_t nx, [[maybe_unused]] size_t ny, size_t d) {
656
+ #ifdef __aarch64__
657
+ if (omp_in_parallel() && d >= 64 && nx >= 4 &&
658
+ nx * d * ny >=
659
+ static_cast<size_t>(distance_compute_blas_threshold) * 32) {
660
+ return true;
661
+ }
662
+ #endif
663
+ return nx * d >= static_cast<size_t>(distance_compute_blas_threshold);
664
+ }
665
+
628
666
  struct Run_search_inner_product {
629
667
  using T = void;
630
668
  template <class BlockResultHandler>
@@ -638,8 +676,7 @@ struct Run_search_inner_product {
638
676
  // per-query begin()/end() still runs and each handler writes its own
639
677
  // neutral distance and -1 label. The BLAS path instead returns early
640
678
  // on ny == 0, before the handler is initialized.
641
- if (res.sel || ny == 0 ||
642
- nx * d < static_cast<size_t>(distance_compute_blas_threshold)) {
679
+ if (res.sel || ny == 0 || !should_use_blas(nx, ny, d)) {
643
680
  exhaustive_inner_product_seq(x, y, d, nx, ny, res);
644
681
  } else {
645
682
  exhaustive_inner_product_blas(x, y, d, nx, ny, res);
@@ -658,8 +695,7 @@ struct Run_search_L2sqr {
658
695
  size_t ny,
659
696
  const float* y_norm2) {
660
697
  // See the note on ny == 0 in Run_search_inner_product.
661
- if (res.sel || ny == 0 ||
662
- nx * d < static_cast<size_t>(distance_compute_blas_threshold)) {
698
+ if (res.sel || ny == 0 || !should_use_blas(nx, ny, d)) {
663
699
  exhaustive_L2sqr_seq(x, y, d, nx, ny, res);
664
700
  } else {
665
701
  exhaustive_L2sqr_blas(x, y, d, nx, ny, res, y_norm2);
@@ -667,6 +703,29 @@ struct Run_search_L2sqr {
667
703
  }
668
704
  };
669
705
 
706
+ // Supplied score norms are authoritative: use norm expansion even for a
707
+ // small query. Keep the same BLAS/fused/SIMD result handlers as knn_L2sqr.
708
+ struct Run_search_L2sqr_with_norms {
709
+ using T = void;
710
+ template <class BlockResultHandler>
711
+ void f(BlockResultHandler& res,
712
+ const float* x,
713
+ const float* y,
714
+ size_t d,
715
+ size_t nx,
716
+ size_t ny,
717
+ const float* y_norm2,
718
+ size_t bs_x,
719
+ size_t bs_y) {
720
+ // Initialize each handler's neutral distance/-1 outputs for ny == 0.
721
+ if (ny == 0) {
722
+ exhaustive_L2sqr_seq(x, y, d, nx, ny, res);
723
+ } else {
724
+ exhaustive_L2sqr_blas(x, y, d, nx, ny, res, y_norm2, bs_x, bs_y);
725
+ }
726
+ }
727
+ };
728
+
670
729
  // fp16 consumers only run the BLAS kernels, see use_fp16_blas_kernels
671
730
  struct Run_search_inner_product_fp16 {
672
731
  using T = void;
@@ -708,8 +767,23 @@ int distance_compute_blas_database_bs = 1024;
708
767
  int distance_compute_min_k_reservoir = 100;
709
768
 
710
769
  // Database-parallel KNN: parallelizes over database segments instead of
711
- // queries, for the case where nx < nthreads and the database is large.
770
+ // queries, for a large database and as many queries as its buffers allow.
712
771
  static constexpr size_t kDbParallelMinVectors = 10000;
772
+ // Bound on its per-thread result heaps and inner-product blocks when
773
+ // nx >= nthreads.
774
+ static constexpr size_t kDbParallelMaxBytes = size_t(256) << 20;
775
+ // Inner-product block of one thread, in floats.
776
+ static constexpr size_t kDbParallelBlockFloats = size_t(1) << 16;
777
+
778
+ // Database vectors per inner-product block: fewer for more queries, so that
779
+ // the block stays near kDbParallelBlockFloats.
780
+ static size_t db_parallel_block(
781
+ size_t nx,
782
+ size_t database_block_size = distance_compute_blas_database_bs) {
783
+ return std::min<size_t>(
784
+ database_block_size,
785
+ std::max<size_t>(32, kDbParallelBlockFloats / nx));
786
+ }
713
787
 
714
788
  template <class C>
715
789
  static void knn_db_parallel_impl(
@@ -721,12 +795,13 @@ static void knn_db_parallel_impl(
721
795
  size_t k,
722
796
  float* vals,
723
797
  int64_t* ids,
724
- const float* y_norms) {
798
+ const float* y_norms,
799
+ size_t database_block_size = distance_compute_blas_database_bs) {
725
800
  using T = typename C::T;
726
801
  using TI = typename C::TI;
727
802
 
728
803
  int nt = omp_get_max_threads();
729
- const size_t bs_y = distance_compute_blas_database_bs;
804
+ const size_t bs_y = db_parallel_block(nx, database_block_size);
730
805
 
731
806
  // Result heaps: nt segments x nx queries x k results
732
807
  std::vector<T> all_dis(static_cast<size_t>(nt) * nx * k);
@@ -857,16 +932,28 @@ static void knn_db_parallel_impl(
857
932
  static bool should_use_db_parallel(
858
933
  size_t nx,
859
934
  size_t ny,
860
- const IDSelector* sel) {
935
+ size_t k,
936
+ const IDSelector* sel,
937
+ size_t database_block_size = distance_compute_blas_database_bs) {
861
938
  if (sel) {
862
939
  return false;
863
940
  }
864
- int nt = omp_get_max_threads();
865
- size_t min_ny = std::max(
866
- kDbParallelMinVectors,
867
- static_cast<size_t>(nt) *
868
- static_cast<size_t>(distance_compute_blas_database_bs));
869
- return nt > 1 && nx < static_cast<size_t>(nt) && ny >= min_ny;
941
+ const size_t nt = omp_get_max_threads();
942
+ const size_t min_ny =
943
+ std::max(kDbParallelMinVectors, nt * database_block_size);
944
+ if (nt <= 1 || ny < min_ny) {
945
+ return false;
946
+ }
947
+ if (nx < nt) {
948
+ return true;
949
+ }
950
+ // Otherwise the sequential scan or BLAS runs. The sequential scan reads
951
+ // the whole database once per query per thread, and BLAS synchronizes
952
+ // all threads twice per database block.
953
+ const size_t bytes = nt *
954
+ (nx * k * (sizeof(float) + sizeof(int64_t)) +
955
+ nx * db_parallel_block(nx, database_block_size) * sizeof(float));
956
+ return bytes <= kDbParallelMaxBytes;
870
957
  }
871
958
 
872
959
  void knn_inner_product(
@@ -893,7 +980,7 @@ void knn_inner_product(
893
980
  return;
894
981
  }
895
982
 
896
- if (should_use_db_parallel(nx, ny, sel)) {
983
+ if (should_use_db_parallel(nx, ny, k, sel)) {
897
984
  knn_db_parallel_impl<CMin<float, int64_t>>(
898
985
  x, y, d, nx, ny, k, vals, ids, nullptr);
899
986
  } else {
@@ -959,7 +1046,7 @@ void knn_L2sqr(
959
1046
  return;
960
1047
  }
961
1048
 
962
- if (should_use_db_parallel(nx, ny, sel)) {
1049
+ if (should_use_db_parallel(nx, ny, k, sel)) {
963
1050
  knn_db_parallel_impl<CMax<float, int64_t>>(
964
1051
  x, y, d, nx, ny, k, vals, ids, y_norm2);
965
1052
  } else {
@@ -991,6 +1078,130 @@ void knn_L2sqr(
991
1078
  knn_L2sqr(x, y, d, nx, ny, res->k, res->val, res->ids, y_norm2, sel);
992
1079
  }
993
1080
 
1081
+ void knn_L2sqr_with_norms(
1082
+ const float* x,
1083
+ const float* y,
1084
+ size_t d,
1085
+ size_t nx,
1086
+ size_t ny,
1087
+ size_t k,
1088
+ float* vals,
1089
+ int64_t* ids,
1090
+ const float* y_norm2,
1091
+ size_t query_block_size,
1092
+ size_t database_block_size) {
1093
+ FAISS_THROW_IF_NOT(query_block_size > 0 && database_block_size > 0);
1094
+ FAISS_THROW_IF_NOT(ny == 0 || y_norm2 != nullptr);
1095
+ if (nx == 0) {
1096
+ return;
1097
+ }
1098
+ if (should_use_db_parallel(nx, ny, k, nullptr, database_block_size)) {
1099
+ knn_db_parallel_impl<CMax<float, int64_t>>(
1100
+ x, y, d, nx, ny, k, vals, ids, y_norm2, database_block_size);
1101
+ } else {
1102
+ Run_search_L2sqr_with_norms r;
1103
+ dispatch_knn_ResultHandler(
1104
+ nx,
1105
+ vals,
1106
+ ids,
1107
+ k,
1108
+ METRIC_L2,
1109
+ nullptr,
1110
+ r,
1111
+ x,
1112
+ y,
1113
+ d,
1114
+ nx,
1115
+ ny,
1116
+ y_norm2,
1117
+ query_block_size,
1118
+ database_block_size);
1119
+ }
1120
+ }
1121
+
1122
+ void accumulate_cluster_sums(
1123
+ size_t d,
1124
+ size_t n,
1125
+ size_t k,
1126
+ const float* x,
1127
+ const int64_t* labels,
1128
+ float* sums) {
1129
+ // Each thread owns a range of labels, so no two threads write one row.
1130
+ #pragma omp parallel if (n * d > 65536)
1131
+ {
1132
+ const int64_t nt = omp_get_num_threads(), rank = omp_get_thread_num();
1133
+ const int64_t a0 = k * rank / nt, a1 = k * (rank + 1) / nt;
1134
+ for (size_t i = 0; i < n; i++) {
1135
+ const int64_t a = labels[i];
1136
+ if (a >= a0 && a < a1) {
1137
+ float* row = sums + a * (d + 1);
1138
+ fvec_add(d, row, x + i * d, row);
1139
+ row[d] += 1;
1140
+ }
1141
+ }
1142
+ }
1143
+ }
1144
+
1145
+ void accumulate_removal_stats(
1146
+ size_t d,
1147
+ size_t n,
1148
+ size_t k,
1149
+ const float* x,
1150
+ const int64_t* labels,
1151
+ const float* d1,
1152
+ const float* d2,
1153
+ const float* centroids,
1154
+ const float* axes,
1155
+ float* stats) {
1156
+ // Each thread owns a range of labels, so no two threads write one row.
1157
+ #pragma omp parallel if (n * d > 65536)
1158
+ {
1159
+ const int64_t nt = omp_get_num_threads(), rank = omp_get_thread_num();
1160
+ const int64_t a0 = k * rank / nt, a1 = k * (rank + 1) / nt;
1161
+ std::vector<float> y(d);
1162
+ for (size_t i = 0; i < n; i++) {
1163
+ const int64_t a = labels[i];
1164
+ if (a < a0 || a >= a1) {
1165
+ continue;
1166
+ }
1167
+ fvec_sub(d, x + i * d, centroids + a * d, y.data());
1168
+ const float p = fvec_inner_product(y.data(), axes + a * d, d);
1169
+ float* row = stats + a * (d + 1);
1170
+ fvec_madd(d, row, p, y.data(), row);
1171
+ const float margin = d2[i] - d1[i];
1172
+ row[d] += std::isfinite(margin) ? margin : 0;
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ void update_removal_axes(
1178
+ size_t d,
1179
+ size_t n,
1180
+ const int64_t* ids,
1181
+ float weight,
1182
+ float* batch,
1183
+ float* axis,
1184
+ float* axes) {
1185
+ #pragma omp parallel for if (n * d > 65536)
1186
+ for (int64_t i = 0; i < static_cast<int64_t>(n); i++) {
1187
+ const int64_t a = ids[i];
1188
+ float* b = batch + a * (d + 1);
1189
+ float* u = axis + a * (d + 1);
1190
+ fvec_madd(d, u, weight, b, u);
1191
+ double norm2 = 0;
1192
+ for (size_t j = 0; j < d; j++) {
1193
+ norm2 += double(u[j]) * u[j];
1194
+ }
1195
+ const double norm = std::sqrt(norm2);
1196
+ if (norm > 0) {
1197
+ for (size_t j = 0; j < d; j++) {
1198
+ axes[a * d + j] = u[j] / norm;
1199
+ }
1200
+ }
1201
+ std::fill(b, b + d + 1, 0.0f);
1202
+ }
1203
+ }
1204
+
994
1205
  namespace {
995
1206
 
996
1207
  /** Whether fp16 queries go to the BLAS kernels directly.
@@ -1003,10 +1214,11 @@ bool use_fp16_blas_kernels(
1003
1214
  size_t d,
1004
1215
  size_t nx,
1005
1216
  size_t ny,
1217
+ size_t k,
1006
1218
  const IDSelector* sel) {
1007
1219
  return !sel && ny > 0 && d > 32 &&
1008
1220
  nx * d >= static_cast<size_t>(distance_compute_blas_threshold) &&
1009
- !should_use_db_parallel(nx, ny, sel);
1221
+ !should_use_db_parallel(nx, ny, k, sel);
1010
1222
  }
1011
1223
 
1012
1224
  /// widens chunks of queries and calls search(x_chunk, n_chunk, i0) on them
@@ -1040,7 +1252,7 @@ void knn_inner_product_fp16(
1040
1252
  float* vals,
1041
1253
  int64_t* ids,
1042
1254
  const IDSelector* sel) {
1043
- if (!use_fp16_blas_kernels(d, nx, ny, sel)) {
1255
+ if (!use_fp16_blas_kernels(d, nx, ny, k, sel)) {
1044
1256
  search_fp16_by_chunks(
1045
1257
  x, d, nx, [&](const float* xc, size_t nc, size_t i0) {
1046
1258
  knn_inner_product(
@@ -1083,7 +1295,7 @@ void knn_L2sqr_fp16(
1083
1295
  int64_t* ids,
1084
1296
  const float* y_norm2,
1085
1297
  const IDSelector* sel) {
1086
- if (!use_fp16_blas_kernels(d, nx, ny, sel)) {
1298
+ if (!use_fp16_blas_kernels(d, nx, ny, k, sel)) {
1087
1299
  search_fp16_by_chunks(
1088
1300
  x, d, nx, [&](const float* xc, size_t nc, size_t i0) {
1089
1301
  knn_L2sqr(
@@ -1,5 +1,13 @@
1
1
  /*
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ * Portions 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
+ /*
9
+ * Portions Copyright 2026 Arm Limited and/or its affiliates
10
+ * <open-source-office@arm.com>
3
11
  *
4
12
  * This source code is licensed under the MIT license found in the
5
13
  * LICENSE file in the root directory of this source tree.
@@ -369,7 +377,9 @@ void pairwise_indexed_inner_product(
369
377
  * KNN functions
370
378
  ***************************************************************************/
371
379
 
372
- // threshold on nx * d above which we switch to BLAS to compute distances
380
+ // threshold on nx * d above which we switch to BLAS to compute distances.
381
+ // On Arm, inside an OpenMP parallel region, BLAS also wins when d >= 64,
382
+ // nx >= 4, and nx * d * ny >= 32 * distance_compute_blas_threshold.
373
383
  FAISS_API extern int distance_compute_blas_threshold;
374
384
 
375
385
  // block sizes for BLAS distance computations
@@ -455,6 +465,37 @@ void knn_L2sqr(
455
465
  const float* y_norm2 = nullptr,
456
466
  const IDSelector* sel = nullptr);
457
467
 
468
+ /** Search using authoritative FP32 database score norms and per-call blocks.
469
+ *
470
+ * Scores use the existing norm-expansion kernels: ||x||^2 + y_norm2[j]
471
+ * - 2 * x.y[j], with the existing nonnegative clamp. y_norm2 may include a
472
+ * bias/offset or +infinity mask; returned scores need not be plain L2
473
+ * distances. The caller is responsible for their interpretation.
474
+ *
475
+ * Uses the same top-k handlers, fused/SIMD BLAS and database-parallel paths
476
+ * as knn_L2sqr with forced norm expansion, without reading/writing the BLAS
477
+ * threshold or block globals. Result-handler selection (including
478
+ * distance_compute_min_k_reservoir) and the OpenMP thread count follow the
479
+ * normal knn_L2sqr policies. Blocks must be positive; y_norm2 must contain
480
+ * ny entries for a nonempty database. No selector is supported.
481
+ *
482
+ * Outputs have nx * k entries, sorted by score. With ny == 0, each entry
483
+ * has the existing neutral distance and -1 ID; nx == 0 writes no outputs.
484
+ * Other input/output storage requirements are the same as knn_L2sqr.
485
+ */
486
+ void knn_L2sqr_with_norms(
487
+ const float* x,
488
+ const float* y,
489
+ size_t d,
490
+ size_t nx,
491
+ size_t ny,
492
+ size_t k,
493
+ float* distances,
494
+ int64_t* indexes,
495
+ const float* y_norm2,
496
+ size_t query_block_size,
497
+ size_t database_block_size);
498
+
458
499
  /** knn_inner_product for packed IEEE binary16 queries (x: nx * d uint16_t).
459
500
  *
460
501
  * The BLAS kernels widen each query tile once and reuse it for all database
@@ -599,6 +640,108 @@ void compute_PQ_dis_tables_dsub2(
599
640
  * Misc matrix and vector manipulation functions
600
641
  ***************************************************************************/
601
642
 
643
+ /** Per-cluster sums and counts of labeled vectors.
644
+ *
645
+ * For each i < n, adds x[i] to sums[labels[i], 0:d] and 1 to
646
+ * sums[labels[i], d]. The result equals numpy.add.at(sums[:, :d], labels, x)
647
+ * and numpy.add.at(sums[:, d], labels, 1) bit for bit: the rows of each
648
+ * cluster are added in increasing i, whatever the number of threads.
649
+ * Unlike numpy.add.at, which is single-threaded, it runs with OpenMP when
650
+ * n * d > 65536: each thread owns a contiguous range of labels and scans all
651
+ * rows, so no two threads write the same row of sums and no reduction is
652
+ * needed.
653
+ *
654
+ * All arrays are contiguous and row-major; x and sums are float32, labels
655
+ * int64; sums must not overlap x or labels.
656
+ *
657
+ * @param d dimension of the vectors
658
+ * @param n number of vectors
659
+ * @param k number of clusters
660
+ * @param x input vectors, size n * d
661
+ * @param labels input cluster of each vector, size n, in [0, k)
662
+ * @param sums in/out sums and counts, size k * (d + 1): row a holds the
663
+ * d components of the sum and then the count; results are
664
+ * added to its contents
665
+ */
666
+ void accumulate_cluster_sums(
667
+ size_t d,
668
+ size_t n,
669
+ size_t k,
670
+ const float* x,
671
+ const int64_t* labels,
672
+ float* sums);
673
+
674
+ /** Per-cluster removal costs and Oja long-axis terms of an assignment.
675
+ *
676
+ * Used by e-means' cost-based revival. For each i < n, with a = labels[i],
677
+ * y = x[i] - centroids[a] and p = <y, axes[a]>, adds p * y to
678
+ * stats[a, 0:d] and the removal cost d2[i] - d1[i] to stats[a, d] (zero is
679
+ * added when the computed difference is not finite). The rows of each
680
+ * cluster are added in increasing i, so the result does not depend on the
681
+ * number of threads. OpenMP as in accumulate_cluster_sums: each thread owns
682
+ * a range of labels.
683
+ *
684
+ * All arrays are contiguous and row-major, float32 except the int64
685
+ * labels; stats must not overlap any input.
686
+ *
687
+ * @param d dimension of the vectors
688
+ * @param n number of vectors
689
+ * @param k number of clusters
690
+ * @param x input vectors, size n * d
691
+ * @param labels input nearest centroid of each vector, size n, in [0, k)
692
+ * @param d1 input squared distance to the nearest centroid, size n
693
+ * @param d2 input squared distance to the second-nearest centroid,
694
+ * size n
695
+ * @param centroids input centroids used for the assignment, size k * d
696
+ * @param axes input unit long axis of each cluster, size k * d
697
+ * @param stats in/out per-cluster sums, size k * (d + 1): row a holds
698
+ * the sum of p * y and then the sum of d2 - d1; results
699
+ * are added to its contents
700
+ */
701
+ void accumulate_removal_stats(
702
+ size_t d,
703
+ size_t n,
704
+ size_t k,
705
+ const float* x,
706
+ const int64_t* labels,
707
+ const float* d1,
708
+ const float* d2,
709
+ const float* centroids,
710
+ const float* axes,
711
+ float* stats);
712
+
713
+ /** Oja update of the cluster axes from accumulate_removal_stats sums.
714
+ *
715
+ * For each cluster a = ids[i], i < n: u = axis[a, 0:d] += weight *
716
+ * batch[a, 0:d]; if |u| > 0 (computed in double), axes[a] = u / |u|;
717
+ * batch[a] is then zeroed. Clusters are independent; OpenMP over ids when
718
+ * n * d > 65536. Rows not in ids keep their contents, and so does axes[a]
719
+ * when |u| = 0.
720
+ *
721
+ * All arrays are contiguous and row-major, float32 except the int64 ids;
722
+ * batch, axis and axes have k rows (k is the number of clusters they were
723
+ * allocated for) and must not overlap each other or ids.
724
+ *
725
+ * @param d dimension of the vectors
726
+ * @param n number of clusters to update
727
+ * @param ids input clusters to update, size n, distinct, each in [0, k)
728
+ * @param weight input weight of the batch sums
729
+ * @param batch in/out batch sums, k rows of size d + 1 (as stats in
730
+ * accumulate_removal_stats); rows ids are zeroed
731
+ * @param axis in/out running sums u, k rows of size d + 1 (component d
732
+ * is not used)
733
+ * @param axes out unit axes, k rows of size d; rows ids with |u| > 0 are
734
+ * overwritten
735
+ */
736
+ void update_removal_axes(
737
+ size_t d,
738
+ size_t n,
739
+ const int64_t* ids,
740
+ float weight,
741
+ float* batch,
742
+ float* axis,
743
+ float* axes);
744
+
602
745
  /** compute c := a + bf * b for a, b and c tables
603
746
  *
604
747
  * @param n size of the tables
@@ -112,7 +112,8 @@ struct VectorDistance {
112
112
  size_t d;
113
113
  float metric_arg;
114
114
 
115
- VectorDistance(size_t d, float metric_arg) : d(d), metric_arg(metric_arg) {}
115
+ VectorDistance(size_t d_in, float metric_arg_in)
116
+ : d(d_in), metric_arg(metric_arg_in) {}
116
117
 
117
118
  static constexpr MetricType metric = mt;
118
119
  static constexpr bool is_similarity = is_similarity_metric(mt);
@@ -42,6 +42,9 @@ inline BitstringReader::BitstringReader(
42
42
  : code(code_in), code_size(code_size_in), i(0) {}
43
43
 
44
44
  inline uint64_t BitstringReader::read(int nbit) {
45
+ if (nbit <= 0) {
46
+ return 0;
47
+ }
45
48
  assert(code_size * 8 >= nbit + i);
46
49
  // nb of available bits in i / 8
47
50
  int na = 8 - (i & 7);
@@ -204,13 +204,13 @@ typename C::T partition_fuzzy_median3(
204
204
  thresh = C::Crev::nextafter(thresh);
205
205
  n_eq_1 = q;
206
206
  } else {
207
- assert(n_eq_1 <= n_eq);
207
+ assert(static_cast<size_t>(n_eq_1) <= n_eq);
208
208
  }
209
209
 
210
210
  [[maybe_unused]] const int wp =
211
211
  compress_array<C>(vals, ids, n, thresh, n_eq_1);
212
212
 
213
- assert(wp == q);
213
+ assert(static_cast<size_t>(wp) == q);
214
214
  if (q_out) {
215
215
  *q_out = q;
216
216
  }