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
@@ -424,13 +424,85 @@ static int next_power_of_2(int n) {
424
424
  return p;
425
425
  }
426
426
 
427
- // Generate three sign-flip vectors from the given seed.
427
+ // Smallest multiple of 64 >= n.
428
+ static int next_multiple_of_64(int n) {
429
+ return (n + 63) / 64 * 64;
430
+ }
431
+
432
+ static bool is_power_of_2(size_t n) {
433
+ return n > 0 && (n & (n - 1)) == 0;
434
+ }
435
+
436
+ // Largest power of 2 <= n, for n > 0.
437
+ static size_t prev_power_of_2(size_t n) {
438
+ size_t p = 1;
439
+ while (p * 2 <= n) {
440
+ p *= 2;
441
+ }
442
+ return p;
443
+ }
444
+
445
+ // Butterfly between the two halves of x (p even):
446
+ // (x_j, x_{j + p/2}) -> (x_j + x_{j + p/2}, x_j - x_{j + p/2}).
447
+ // Scales norms by sqrt(2).
448
+ static void kac_butterfly(float* x, size_t p) {
449
+ const size_t half = p / 2;
450
+ for (size_t j = 0; j < half; j++) {
451
+ float a = x[j];
452
+ float b = x[j + half];
453
+ x[j] = a + b;
454
+ x[j + half] = a - b;
455
+ }
456
+ }
457
+
458
+ // One round of the FHT-Kac rotation of a vector of p components: sign flips,
459
+ // normalized FWHT of the t components starting at offset, then the butterfly.
460
+ static void fht_kac_round(
461
+ float* x,
462
+ size_t p,
463
+ size_t t,
464
+ size_t offset,
465
+ const float* signs,
466
+ float fwht_scale) {
467
+ for (size_t j = 0; j < p; j++) {
468
+ x[j] *= signs[j];
469
+ }
470
+ fwht_inplace(x + offset, t);
471
+ for (size_t j = offset; j < offset + t; j++) {
472
+ x[j] *= fwht_scale;
473
+ }
474
+ kac_butterfly(x, p);
475
+ }
476
+
477
+ // Inverse of fht_kac_round, up to the sqrt(2) scaling of the butterfly: the
478
+ // butterfly, the normalized FWHT and the sign flips are each their own
479
+ // inverse, so they are applied in reverse order.
480
+ static void fht_kac_inverse_round(
481
+ float* x,
482
+ size_t p,
483
+ size_t t,
484
+ size_t offset,
485
+ const float* signs,
486
+ float fwht_scale) {
487
+ kac_butterfly(x, p);
488
+ fwht_inplace(x + offset, t);
489
+ for (size_t j = offset; j < offset + t; j++) {
490
+ x[j] *= fwht_scale;
491
+ }
492
+ for (size_t j = 0; j < p; j++) {
493
+ x[j] *= signs[j];
494
+ }
495
+ }
496
+
497
+ // Generate three sign-flip vectors from the given seed, and a fourth one
498
+ // after them if s4 is not null.
428
499
  static void generate_signs(
429
500
  uint32_t seed,
430
501
  size_t p,
431
502
  std::vector<float>& s1,
432
503
  std::vector<float>& s2,
433
- std::vector<float>& s3) {
504
+ std::vector<float>& s3,
505
+ std::vector<float>* s4) {
434
506
  FAISS_THROW_IF_NOT_MSG(
435
507
  p > 0, "number of Hadamard factors p must be positive");
436
508
  SplitMix64RandomGenerator rng(seed);
@@ -446,17 +518,36 @@ static void generate_signs(
446
518
  for (size_t j = 0; j < p; j++) {
447
519
  s3[j] = (rng.rand_int(2) == 0) ? -1.0f : 1.0f;
448
520
  }
521
+ if (s4) {
522
+ s4->resize(p);
523
+ for (size_t j = 0; j < p; j++) {
524
+ (*s4)[j] = (rng.rand_int(2) == 0) ? -1.0f : 1.0f;
525
+ }
526
+ }
449
527
  }
450
528
 
451
- HadamardRotation::HadamardRotation(int d, uint32_t seed_in)
452
- : VectorTransform(d, next_power_of_2(d)), seed(seed_in) {
529
+ HadamardRotation::HadamardRotation(
530
+ int d,
531
+ uint32_t seed_in,
532
+ bool pad_to_power_of_2_in)
533
+ : VectorTransform(
534
+ d,
535
+ pad_to_power_of_2_in ? next_power_of_2(d)
536
+ : next_multiple_of_64(d)),
537
+ seed(seed_in),
538
+ pad_to_power_of_2(pad_to_power_of_2_in) {
453
539
  init(seed_in);
454
540
  }
455
541
 
456
542
  void HadamardRotation::init(uint32_t seed_in) {
457
543
  seed = seed_in;
458
544
  is_trained = true;
459
- generate_signs(seed, d_out, signs1, signs2, signs3);
545
+ if (is_power_of_2(d_out)) {
546
+ generate_signs(seed, d_out, signs1, signs2, signs3, nullptr);
547
+ signs4.clear();
548
+ } else {
549
+ generate_signs(seed, d_out, signs1, signs2, signs3, &signs4);
550
+ }
460
551
  }
461
552
 
462
553
  void HadamardRotation::train(idx_t, const float*) {
@@ -478,6 +569,35 @@ void HadamardRotation::apply_noalloc(idx_t n, const float* x, float* xt) const {
478
569
  signs3.size() == p,
479
570
  "sign-flip vector 3 size must match output dimension");
480
571
 
572
+ if (!is_power_of_2(p)) {
573
+ // FHT-Kac rotation (pad_to_power_of_2 == false), see the header.
574
+ FAISS_THROW_IF_NOT_MSG(
575
+ signs4.size() == p,
576
+ "sign-flip vector 4 size must match output dimension");
577
+ const size_t t = prev_power_of_2(p);
578
+ const float fwht_scale = 1.0f / std::sqrt(static_cast<float>(t));
579
+
580
+ #pragma omp parallel for schedule(FAISS_OMP_DYNAMIC)
581
+ for (idx_t i = 0; i < n; i++) {
582
+ const float* xi = x + i * d;
583
+ float* xo = xt + i * p;
584
+
585
+ std::memcpy(xo, xi, d * sizeof(float));
586
+ for (size_t j = d; j < p; j++) {
587
+ xo[j] = 0.0f;
588
+ }
589
+ fht_kac_round(xo, p, t, 0, signs1.data(), fwht_scale);
590
+ fht_kac_round(xo, p, t, p - t, signs2.data(), fwht_scale);
591
+ fht_kac_round(xo, p, t, 0, signs3.data(), fwht_scale);
592
+ fht_kac_round(xo, p, t, p - t, signs4.data(), fwht_scale);
593
+ // The four butterflies scaled norms by sqrt(2)^4 = 4.
594
+ for (size_t j = 0; j < p; j++) {
595
+ xo[j] *= 0.25f;
596
+ }
597
+ }
598
+ return;
599
+ }
600
+
481
601
  // Each unnormalized FWHT scales norms by sqrt(p).
482
602
  // Three rounds scale by p^(3/2). Normalize once at the end.
483
603
  float total_scale = 1.0f / (p * std::sqrt(static_cast<float>(p)));
@@ -522,6 +642,30 @@ void HadamardRotation::reverse_transform(idx_t n, const float* xt, float* x)
522
642
  "HadamardRotation inverse requires equal input/output dimensions");
523
643
 
524
644
  const size_t p = d_out;
645
+
646
+ if (!is_power_of_2(p)) {
647
+ // Reverse of the FHT-Kac rotation: the rounds in reverse order.
648
+ FAISS_THROW_IF_NOT_MSG(
649
+ signs4.size() == p,
650
+ "sign-flip vector 4 size must match output dimension");
651
+ const size_t t = prev_power_of_2(p);
652
+ const float fwht_scale = 1.0f / std::sqrt(static_cast<float>(t));
653
+
654
+ #pragma omp parallel for schedule(FAISS_OMP_DYNAMIC)
655
+ for (idx_t i = 0; i < n; i++) {
656
+ float* xo = x + i * p;
657
+ std::memcpy(xo, xt + i * p, p * sizeof(float));
658
+ fht_kac_inverse_round(xo, p, t, p - t, signs4.data(), fwht_scale);
659
+ fht_kac_inverse_round(xo, p, t, 0, signs3.data(), fwht_scale);
660
+ fht_kac_inverse_round(xo, p, t, p - t, signs2.data(), fwht_scale);
661
+ fht_kac_inverse_round(xo, p, t, 0, signs1.data(), fwht_scale);
662
+ for (size_t j = 0; j < p; j++) {
663
+ xo[j] *= 0.25f;
664
+ }
665
+ }
666
+ return;
667
+ }
668
+
525
669
  // Reverse of apply_noalloc: three unnormalized FWHT rounds scale norms
526
670
  // by (sqrt(p))^3 = p*sqrt(p); the forward pass cancels this with
527
671
  // total_scale = 1/(p*sqrt(p)), so the inverse applies the same factor.
@@ -562,6 +706,9 @@ void HadamardRotation::check_identical(const VectorTransform& other) const {
562
706
  "HadamardRotation output dimensions must match");
563
707
  FAISS_THROW_IF_NOT_MSG(
564
708
  seed == hr->seed, "HadamardRotation seeds must match");
709
+ FAISS_THROW_IF_NOT_MSG(
710
+ pad_to_power_of_2 == hr->pad_to_power_of_2,
711
+ "HadamardRotation padding modes must match");
565
712
  }
566
713
 
567
714
  /*********************************************
@@ -719,7 +866,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) {
719
866
  }
720
867
 
721
868
  std::vector<double> covd(d_in * d_in);
722
- for (size_t i = 0; i < d_in * d_in; i++) {
869
+ for (size_t i = 0; i < static_cast<size_t>(d_in) * d_in; i++) {
723
870
  covd[i] = cov[i];
724
871
  }
725
872
 
@@ -727,7 +874,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) {
727
874
 
728
875
  eig(d_in, covd.data(), eigenvaluesd.data(), verbose);
729
876
 
730
- for (size_t i = 0; i < d_in * d_in; i++) {
877
+ for (size_t i = 0; i < static_cast<size_t>(d_in) * d_in; i++) {
731
878
  PCAMat[i] = covd[i];
732
879
  }
733
880
  eigenvalues.resize(d_in);
@@ -774,7 +921,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) {
774
921
  }
775
922
 
776
923
  std::vector<double> gramd(n * n);
777
- for (size_t i = 0; i < n * n; i++) {
924
+ for (idx_t i = 0; i < n * n; i++) {
778
925
  gramd[i] = gram[i];
779
926
  }
780
927
 
@@ -786,7 +933,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) {
786
933
 
787
934
  PCAMat.resize(d_in * n);
788
935
 
789
- for (size_t i = 0; i < n * n; i++) {
936
+ for (idx_t i = 0; i < n * n; i++) {
790
937
  gram[i] = gramd[i];
791
938
  }
792
939
 
@@ -129,14 +129,37 @@ struct RandomRotationMatrix : LinearTransform {
129
129
  /** Three rounds of random sign-flip + Fast Walsh-Hadamard Transform.
130
130
  * Produces a pseudo-random rotation in O(d log d) time.
131
131
  * d_out is the smallest power of 2 >= d_in (zero-padded as needed).
132
+ *
133
+ * With pad_to_power_of_2 = false, d_out is the smallest multiple of 64 >= d_in
134
+ * instead, which avoids e.g. padding d = 1536 to 2048. When that d_out is not
135
+ * a power of 2, the transform runs four rounds. Each round flips the signs of
136
+ * all d_out components, applies a normalized FWHT to the first (rounds 1 and
137
+ * 3) or the last (rounds 2 and 4) t of them, t being the largest power of 2
138
+ * <= d_out, and then mixes the two halves of the vector with the butterfly
139
+ * (x_j, x_{j + d_out/2}) -> (x_j + x_{j + d_out/2}, x_j - x_{j + d_out/2})
140
+ * / sqrt(2). This is the FHT-Kac rotation of the RaBitQ library.
141
+ *
142
+ * In index_factory: "HR" (power of 2) or "HRk" (multiple of 64), optionally
143
+ * followed by the seed, e.g. "HRk7".
132
144
  */
133
145
  struct HadamardRotation : VectorTransform {
134
146
  uint32_t seed{};
135
147
 
148
+ /// d_out is the smallest power of 2 >= d_in if true (the default), the
149
+ /// smallest multiple of 64 >= d_in if false
150
+ bool pad_to_power_of_2 = true;
151
+
136
152
  /// Sign-flip vectors, each of size d_out, generated from seed.
137
153
  std::vector<float> signs1, signs2, signs3;
138
154
 
139
- explicit HadamardRotation(int d, uint32_t seed = 12345);
155
+ /// Sign-flip vector of the fourth round. Only used, and only non-empty,
156
+ /// when d_out is not a power of 2.
157
+ std::vector<float> signs4;
158
+
159
+ explicit HadamardRotation(
160
+ int d,
161
+ uint32_t seed = 12345,
162
+ bool pad_to_power_of_2 = true);
140
163
 
141
164
  void init(uint32_t seed_in);
142
165
 
@@ -20,10 +20,12 @@
20
20
  #include <faiss/IndexIVFEDEN.h>
21
21
  #include <faiss/IndexIVFFlat.h>
22
22
  #include <faiss/IndexIVFPQFastScan.h>
23
+ #include <faiss/IndexIVFPQR.h>
23
24
  #include <faiss/IndexIVFRaBitQ.h>
24
25
  #include <faiss/IndexLSH.h>
25
26
  #include <faiss/IndexNSG.h>
26
27
  #include <faiss/IndexPQFastScan.h>
28
+ #include <faiss/IndexPiPNN.h>
27
29
  #include <faiss/IndexPreTransform.h>
28
30
  #include <faiss/IndexRaBitQ.h>
29
31
  #include <faiss/IndexRefine.h>
@@ -124,6 +126,11 @@ std::string reverse_index_factory(const faiss::Index* index) {
124
126
  dynamic_cast<const faiss::IndexIVFScalarQuantizer*>(
125
127
  ivf_index)) {
126
128
  return prefix + "," + sq_types.at(sq_index->sq.qtype);
129
+ } else if (
130
+ const faiss::IndexIVFPQR* ivfpqr_index =
131
+ dynamic_cast<const faiss::IndexIVFPQR*>(ivf_index)) {
132
+ return prefix + ",PQ" + std::to_string(ivfpqr_index->pq.M) + "+" +
133
+ std::to_string(ivfpqr_index->refine_pq.M);
127
134
  } else if (
128
135
  const faiss::IndexIVFPQ* ivfpq_index =
129
136
  dynamic_cast<const faiss::IndexIVFPQ*>(ivf_index)) {
@@ -178,12 +185,23 @@ std::string reverse_index_factory(const faiss::Index* index) {
178
185
  } else if (
179
186
  const faiss::IndexHNSW* hnsw_index =
180
187
  dynamic_cast<const faiss::IndexHNSW*>(index)) {
181
- return "HNSW" + std::to_string(get_hnsw_M(hnsw_index));
188
+ std::string hnsw_prefix =
189
+ "HNSW" + std::to_string(get_hnsw_M(hnsw_index));
190
+ const faiss::Index* storage = hnsw_index->storage;
191
+ if (!storage || dynamic_cast<const faiss::IndexFlat*>(storage)) {
192
+ return hnsw_prefix;
193
+ }
194
+ return hnsw_prefix + "," + reverse_index_factory(storage);
182
195
  } else if (
183
196
  const faiss::IndexNSG* nsg_index =
184
197
  dynamic_cast<const faiss::IndexNSG*>(index)) {
185
198
  return "NSG" + std::to_string(nsg_index->nsg.R) + "," +
186
199
  reverse_index_factory(nsg_index->storage);
200
+ } else if (
201
+ const faiss::IndexPiPNN* pipnn_index =
202
+ dynamic_cast<const faiss::IndexPiPNN*>(index)) {
203
+ return "PiPNN" + std::to_string(pipnn_index->pipnn.R) + "," +
204
+ reverse_index_factory(pipnn_index->storage);
187
205
  } else if (
188
206
  const faiss::IndexRefine* refine_index =
189
207
  dynamic_cast<const faiss::IndexRefine*>(index)) {
@@ -9,25 +9,57 @@
9
9
 
10
10
  #include <faiss/Index.h>
11
11
 
12
+ #include <cstdint>
12
13
  #include <memory>
13
14
 
14
15
  namespace faiss {
15
16
  namespace gpu {
16
17
  class GpuResourcesProvider;
17
18
 
18
- /** Caller-controlled dense vector storage for cuVS CAGRA.
19
+ enum class BBQCodeLayout {
20
+ Packed1Bit,
21
+ Transposed2Bit,
22
+ Transposed4Bit,
23
+ Packed4Bit,
24
+ Packed7Bit,
25
+ Packed8Bit
26
+ };
27
+
28
+ /** Precomputed BBQ codes and corrections in caller-owned device buffers.
29
+ *
30
+ * Codes are packed rows in codeLayout with a 4-byte aligned base pointer. Each
31
+ * correction array has one entry per row; centroid has dim entries of the
32
+ * Dataset numeric type. Corrections must have been generated for metric. All
33
+ * buffers must outlive uses of the Dataset.
34
+ */
35
+ struct BBQQuantizer {
36
+ const uint8_t* codes = nullptr;
37
+ const float* lowerIntervals = nullptr;
38
+ const float* upperIntervals = nullptr;
39
+ const float* additionalCorrections = nullptr;
40
+ const int32_t* quantizedComponentSums = nullptr;
41
+ const void* centroid = nullptr;
42
+ const float* dequantDelta = nullptr;
43
+ const float* dequantSumDelta = nullptr;
44
+ const float* rowNorm = nullptr;
45
+ BBQCodeLayout codeLayout = BBQCodeLayout::Packed1Bit;
46
+ MetricType metric = METRIC_L2;
47
+ float centroidNormSquared = 0;
48
+ };
49
+
50
+ /** Caller-controlled vector storage for cuVS CAGRA.
19
51
  *
20
- * Dimensions and row strides are in elements, with contiguous columns. Binary
21
- * vectors use UInt8, and their dimension is the number of bytes, not bits.
22
- * Views never own or copy their allocation. An owning Dataset controls the
23
- * allocation's lifetime; CAGRA always borrows it. Keep the backing allocation
24
- * alive and unchanged until all indexes using it and queued GPU work finish.
25
- * Moving an owning Dataset preserves its allocation and existing borrowed
26
- * views.
52
+ * Dense dimensions and row strides are in elements, with contiguous columns.
53
+ * Binary vectors use UInt8, and their dimension is the number of bytes, not
54
+ * bits. Views never own or copy their allocation. An owning Dataset controls
55
+ * the allocation's lifetime; CAGRA always borrows it. Keep the backing
56
+ * allocation alive and unchanged until all indexes using it and queued GPU work
57
+ * finish. Moving an owning Dataset preserves its allocation and existing
58
+ * borrowed views.
27
59
  */
28
60
  class Dataset {
29
61
  public:
30
- enum class Layout { Standard, Padded };
62
+ enum class Layout { Standard, Padded, BBQ };
31
63
 
32
64
  ~Dataset();
33
65
  Dataset(Dataset&&) noexcept;
@@ -66,6 +98,18 @@ class Dataset {
66
98
  idx_t rowStride,
67
99
  int device);
68
100
 
101
+ /// Borrow one symmetric or two asymmetric BBQ quantizers without copying
102
+ /// their buffers. Both quantizers describe the same vectors, numeric type,
103
+ /// and metric. BBQ supports NN-descent graph construction; attach dense
104
+ /// padded storage with CAGRA updateDataset before searching.
105
+ static Dataset viewDeviceBBQ(
106
+ const BBQQuantizer& source,
107
+ idx_t numRows,
108
+ int dim,
109
+ NumericType numericType,
110
+ int device,
111
+ const BBQQuantizer* secondary = nullptr);
112
+
69
113
  /// Create padded device storage using cuVS make_device_padded_dataset.
70
114
  /// Device/managed input whose stride already matches the required padding
71
115
  /// is rejected; use a view for that storage. Copies logical columns and
@@ -78,9 +122,11 @@ class Dataset {
78
122
  const Dataset& source,
79
123
  int device);
80
124
 
125
+ /// Dense storage only; BBQ has separate code and correction buffers.
81
126
  const void* getData() const;
82
127
  idx_t getNumRows() const;
83
128
  int getDim() const;
129
+ /// Dense storage only, in elements.
84
130
  idx_t getRowStride() const;
85
131
  NumericType getNumericType() const;
86
132
  int getDevice() const; // -1 for host storage
@@ -88,23 +134,29 @@ class Dataset {
88
134
  bool isDevice() const;
89
135
  bool ownsData() const;
90
136
 
91
- /// Reports device residency, base alignment, and exact required row stride.
92
- /// Does not inspect padding values; zero padding is a caller contract.
137
+ /// Reports dense device residency, alignment, and exact required row
138
+ /// stride. Returns false for BBQ. Does not inspect padding values; zero
139
+ /// padding is a caller contract.
93
140
  bool isCagraCompatible() const;
94
141
 
95
142
  /// Create a non-owning view of the same storage by copying its metadata.
96
143
  /// Does not retain ownership of the backing allocation.
97
144
  Dataset view() const;
98
145
 
99
- /// Copy logical columns into packed host storage. destination must have
100
- /// numRows * dim * sizeof(element) bytes. Completes all device work using
101
- /// the source device before copying and returns with the host data ready.
146
+ /// Copy dense logical columns into packed host storage. destination must
147
+ /// have numRows * dim * sizeof(element) bytes. Completes all device work
148
+ /// using the source device before copying and returns with the host data
149
+ /// ready.
102
150
  void copyToHost(void* destination) const;
103
151
 
104
152
  private:
153
+ template <typename>
154
+ friend class CuvsCagra;
155
+
105
156
  struct Impl;
106
157
  explicit Dataset(std::unique_ptr<Impl> impl);
107
158
  const Impl& getImpl() const;
159
+ const BBQQuantizer* getBBQQuantizer(bool secondary) const;
108
160
  std::unique_ptr<Impl> impl_;
109
161
  };
110
162
 
@@ -58,8 +58,14 @@ struct GpuIndexBinaryCagra : public IndexBinary {
58
58
  /// The backing storage must remain alive and unchanged until all index
59
59
  /// operations have completed. Does nothing if already trained; call reset()
60
60
  /// before building again.
61
- void train(const Dataset& dataset) override;
62
- void add(const Dataset& dataset) override;
61
+ void train(const Dataset& dataset);
62
+ void add(const Dataset& dataset);
63
+ void train_dataset(const Dataset& dataset) override {
64
+ train(dataset);
65
+ }
66
+ void add_dataset(const Dataset& dataset) override {
67
+ add(dataset);
68
+ }
63
69
 
64
70
  /// Rebind search storage without changing the graph. The vectors and their
65
71
  /// ordering must match the training data. Requires compatible device data;
@@ -319,10 +319,16 @@ struct GpuIndexCagra : public GpuIndex {
319
319
  /// allocation must remain alive and unchanged through index use and all
320
320
  /// outstanding GPU work. Does nothing if already trained; call reset()
321
321
  /// before building again.
322
- void train(const Dataset& dataset) override;
322
+ void train(const Dataset& dataset);
323
+ void train_dataset(const Dataset& dataset) override {
324
+ train(dataset);
325
+ }
323
326
 
324
327
  /// Equivalent to train(dataset); incremental insertion is unsupported.
325
- void add(const Dataset& dataset) override;
328
+ void add(const Dataset& dataset);
329
+ void add_dataset(const Dataset& dataset) override {
330
+ add(dataset);
331
+ }
326
332
 
327
333
  /// Attach search-compatible device storage without changing the graph.
328
334
  /// Shape, dtype and vector ordering must match the trained dataset. The
@@ -0,0 +1,184 @@
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ #pragma once
9
+
10
+ #include <faiss/impl/optimal_kmeans/OptimalKMeans.h>
11
+ #include <faiss/impl/optimal_kmeans/OptimalKMeansCompressed.h>
12
+
13
+ #include <cstdint>
14
+ #include <memory>
15
+
16
+ /** GPU version of the block combination of the optimal k-means
17
+ * (contrib/optimal_kmeans/06_gpu.md). All the tables are in the memory of
18
+ * one GPU; the pointers passed to the functions below are device pointers.
19
+ * Splits are uint64 (n <= 40). */
20
+
21
+ namespace faiss {
22
+ namespace gpu {
23
+
24
+ class GpuResourcesProvider;
25
+ struct GpuOptimalKMeansState;
26
+
27
+ /** Parameters of the GPU engine (all of them change only the speed). */
28
+ struct GpuOptimalKMeansParams {
29
+ /// 0: automatic, 1: every pair dense (no pruning), 2: pruned engine for
30
+ /// every pair that is not skipped
31
+ int mode = 0;
32
+ /// a pair is dense if the sampled fraction of its level-3 nodes that
33
+ /// survive the bound test exceeds dense_rate
34
+ float dense_rate = 0.06f;
35
+ /// blocks with fewer than 2^dense_work_log2 candidates are evaluated
36
+ /// densely (the pruning setup costs more)
37
+ int dense_work_log2 = 34;
38
+ /// guess pass over the block points (leave one point out)
39
+ bool guess_low = true;
40
+ /// guess pass over the context points: at most this many points per
41
+ /// group (needs the context split table)
42
+ int guess_bits_ctx = 64;
43
+ /// scale of the global offsets
44
+ float offset_scale = 1.0f;
45
+ /// test the 9 level-9 descendants of a root before loading its tiles
46
+ bool root9 = true;
47
+ /// split bits held by the 64-bit keys; n > group_bits processes the
48
+ /// pairs by groups of equal high split bits (tests use small values)
49
+ int group_bits = 32;
50
+
51
+ GpuOptimalKMeansParams() {}
52
+ };
53
+
54
+ /// shared memory per block needed by the combination kernels
55
+ size_t gpu_optimal_kmeans_shared_bytes();
56
+
57
+ /** Whether the GPU can run the combination kernels: they need
58
+ * gpu_optimal_kmeans_shared_bytes() of shared memory per block (85 KB:
59
+ * compute capability 8.0 or later). The other functions of this file run on
60
+ * any GPU. */
61
+ bool gpu_optimal_kmeans_supported(int device);
62
+
63
+ /** Block combinations on one GPU (same semantics as
64
+ * optimal_kmeans_combine_block). The work is enqueued on the default
65
+ * stream of the device in the resources; the object can be reused for many
66
+ * blocks, but by one thread at a time. */
67
+ struct GpuOptimalKMeansCombiner {
68
+ GpuOptimalKMeansCombiner(
69
+ GpuResourcesProvider* prov,
70
+ int device,
71
+ int L_max,
72
+ int n_max,
73
+ const GpuOptimalKMeansParams& params = GpuOptimalKMeansParams());
74
+ ~GpuOptimalKMeansCombiner();
75
+
76
+ /** Combine the block s_hi of A and B into (acc_cost, acc_split).
77
+ *
78
+ * @param A, B device tables of 2^n entries
79
+ * @param ctx_split optional device split table of the whole output
80
+ * (2^n entries): the blocks s_hi ^ (1 << j), j bit of
81
+ * s_hi, must be final; used for the context guesses
82
+ * @param acc_cost device, 2^L entries, in/out
83
+ * @param acc_split device, 2^L entries, in/out
84
+ */
85
+ void combine_block(
86
+ int n,
87
+ int L,
88
+ uint64_t s_hi,
89
+ const float* A,
90
+ const float* B,
91
+ bool sym,
92
+ const uint64_t* ctx_split,
93
+ float* acc_cost,
94
+ uint64_t* acc_split);
95
+
96
+ /** Streaming combination of one block (07_compressed.md): the input
97
+ * blocks are given per pair, in device memory, instead of whole tables:
98
+ *
99
+ * block_begin(n, L, s_hi, sym, acc_cost, acc_split);
100
+ * block_pairs(...); // one or several batches
101
+ * block_end();
102
+ *
103
+ * Every pair (l_hi, r_hi) of s_hi must be given once (sym: l_hi < r_hi,
104
+ * plus (0, 0) for s_hi = 0). The guess pass only uses the candidates of
105
+ * the first batch. Same result as combine_block. */
106
+ void block_begin(
107
+ int n,
108
+ int L,
109
+ uint64_t s_hi,
110
+ bool sym,
111
+ float* acc_cost,
112
+ uint64_t* acc_split);
113
+
114
+ /** A batch of pairs.
115
+ *
116
+ * @param l_hi, r_hi host arrays of npairs upper divisions of s_hi
117
+ * @param slots device array of blocks of 2^L floats
118
+ * @param a_slot, b_slot host arrays: the A block of pair i is
119
+ * slots + a_slot[i] * 2^L, its B block
120
+ * slots + b_slot[i] * 2^L
121
+ * The blocks must stay unchanged until the work is done (stream order).
122
+ */
123
+ void block_pairs(
124
+ size_t npairs,
125
+ const uint64_t* l_hi,
126
+ const uint64_t* r_hi,
127
+ const float* slots,
128
+ const int32_t* a_slot,
129
+ const int32_t* b_slot);
130
+
131
+ void block_end();
132
+
133
+ /// add the counters of the blocks combined so far (synchronizes)
134
+ void get_stats(OptimalKMeansStats* stats, bool reset = true);
135
+
136
+ /// synchronize with the work enqueued so far
137
+ void synchronize();
138
+
139
+ GpuOptimalKMeansParams params;
140
+ int device;
141
+ std::shared_ptr<GpuOptimalKMeansState> state;
142
+ };
143
+
144
+ /** T1 of the 2^L groups (blk << L) | z, written to out (device), computed
145
+ * on the GPU with the double operations of OptimalKMeansCost1, so the
146
+ * result is the same as on the CPU. */
147
+ void gpu_optimal_kmeans_cost1(
148
+ GpuResourcesProvider* prov,
149
+ int device,
150
+ const OptimalKMeansCost1& gen,
151
+ int L,
152
+ uint64_t blk,
153
+ float* out);
154
+
155
+ struct GpuOptimalKMeansBlockLoaderState;
156
+
157
+ /** Input blocks of 2^L entries generated on the GPU (07_compressed.md):
158
+ * T1, or a block of a compressed level decoded with the same operations as
159
+ * optimal_kmeans_decode_block. The work is enqueued
160
+ * on the default stream of the device in the resources. */
161
+ struct GpuOptimalKMeansBlockLoader {
162
+ GpuOptimalKMeansBlockLoader(
163
+ GpuResourcesProvider* prov,
164
+ int device,
165
+ const OptimalKMeansCost1& t1,
166
+ int L);
167
+ ~GpuOptimalKMeansBlockLoader();
168
+
169
+ /// T1 of the 2^L groups (blk << L) | z into out (device)
170
+ void cost1_block(uint64_t blk, float* out);
171
+
172
+ /// decoded block s of the level into out (device, 2^L floats)
173
+ void decode_block(
174
+ const OptimalKMeansCompressedLevel& level,
175
+ uint64_t s,
176
+ float* out);
177
+
178
+ int device;
179
+ int L;
180
+ std::shared_ptr<GpuOptimalKMeansBlockLoaderState> state;
181
+ };
182
+
183
+ } // namespace gpu
184
+ } // namespace faiss