19 #include "FaissAssert.h"
22 #include "IndexFlat.h"
23 #include "VectorTransform.h"
27 #include "IndexIVFPQ.h"
28 #include "IndexIVFFlat.h"
29 #include "MetaIndexes.h"
30 #include "IndexScalarQuantizer.h"
31 #include "IndexHNSW.h"
32 #include "IndexBinaryFlat.h"
33 #include "IndexBinaryHNSW.h"
34 #include "IndexBinaryIVF.h"
39 AutoTuneCriterion::AutoTuneCriterion (idx_t nq, idx_t nnn):
40 nq (nq), nnn (nnn), gt_nnn (0)
45 int gt_nnn,
const float *gt_D_in,
const idx_t *gt_I_in)
49 gt_D.resize (nq * gt_nnn);
50 memcpy (
gt_D.data(), gt_D_in,
sizeof (
gt_D[0]) * nq * gt_nnn);
52 gt_I.resize (nq * gt_nnn);
53 memcpy (
gt_I.data(), gt_I_in,
sizeof (
gt_I[0]) * nq * gt_nnn);
58 OneRecallAtRCriterion::OneRecallAtRCriterion (idx_t nq, idx_t R):
64 FAISS_THROW_IF_NOT_MSG(
66 "ground truth not initialized");
68 for (idx_t q = 0; q <
nq; q++) {
70 const idx_t* I_line = I + q *
nnn;
71 for (
int i = 0; i < R; i++) {
72 if (I_line[i] == gt_nn) {
78 return n_ok / double(nq);
82 IntersectionCriterion::IntersectionCriterion (idx_t nq, idx_t R):
88 FAISS_THROW_IF_NOT_MSG(
90 "ground truth not initialized");
92 #pragma omp parallel for reduction(+: n_ok)
93 for (idx_t q = 0; q <
nq; q++) {
95 R, &
gt_I [q * gt_nnn],
98 return n_ok / double (nq * R);
105 OperatingPoints::OperatingPoints ()
129 if (perf > a.back().perf) {
132 }
else if (perf == a.back().perf) {
133 if (t < a.back ().t) {
141 for (i = 0; i < a.size(); i++) {
142 if (a[i].perf >= perf)
break;
144 assert (i < a.size());
146 if (a[i].perf == perf) {
149 a.insert (a.begin() + i, op);
156 int i = a.size() - 1;
158 if (a[i].t < a[i - 1].t)
159 a.erase (a.begin() + (i - 1));
168 const std::string & prefix)
171 for (
int i = 0; i < other.
all_pts.size(); i++) {
184 const std::vector<OperatingPoint> & a =
optimal_pts;
185 if (perf > a.back().perf)
return 1e50;
186 int i0 = -1, i1 = a.size() - 1;
187 while (i0 + 1 < i1) {
188 int imed = (i0 + i1 + 1) / 2;
189 if (a[imed].perf < perf) i0 = imed;
198 FILE *f = fopen(fname,
"w");
200 fprintf (stderr,
"cannot open %s", fname);
204 for (
int i = 0; i <
all_pts.size(); i++) {
206 fprintf (f,
"%g %g %s\n", op.
perf, op.
t, op.
key.c_str());
211 void OperatingPoints::optimal_to_gnuplot (
const char *fname)
const
213 FILE *f = fopen(fname,
"w");
215 fprintf (stderr,
"cannot open %s", fname);
219 double prev_perf = 0.0;
222 fprintf (f,
"%g %g\n", prev_perf, op.t);
223 fprintf (f,
"%g %g %s\n", op.perf, op.t, op.key.c_str());
231 const std::vector<OperatingPoint> &pts =
233 printf(
"Tested %ld operating points, %ld ones are optimal:\n",
236 for (
int i = 0; i < pts.size(); i++) {
238 const char *star =
"";
247 printf (
"cno=%ld key=%s perf=%.4f t=%.3f %s\n",
257 ParameterSpace::ParameterSpace ():
258 verbose (1), n_experiments (500),
259 batchsize (1<<30), thread_over_batches (false),
260 min_test_duration (0)
269 ParameterSpace::ParameterSpace (Index *index):
270 verbose (1), n_experiments (500),
271 batchsize (1<<30), thread_over_batches (false)
288 char buf[1000], *wp = buf;
292 size_t j = cno % pr.values.size();
293 cno /= pr.values.size();
295 wp, buf + 1000 - wp,
"%s%s=%g", i == 0 ?
"" :
",",
296 pr.name.c_str(), pr.values[j]);
298 return std::string (buf);
306 size_t j1 = c1 % nval;
307 size_t j2 = c2 % nval;
308 if (!(j1 >= j2))
return false;
317 #define DC(classname) \
318 const classname *ix = dynamic_cast<const classname *>(index)
326 for (
int i = 2; i <= pq.
code_size * 8 / 2; i+= 2)
327 pr.values.push_back(i);
335 if (pr.name == name) {
340 parameter_ranges.back ().name = name;
341 return parameter_ranges.back ();
353 for (
int i = 0; i <= 6; i++) {
354 pr.values.push_back (1 << i);
356 index = ix->base_index;
365 for (
int i = 0; i < 13; i++) {
366 size_t nprobe = 1 << i;
367 if (nprobe >= ix->nlist)
break;
368 pr.values.push_back (nprobe);
371 if (dynamic_cast<const IndexHNSW*>(ix->quantizer)) {
373 for (
int i = 2; i <= 9; i++) {
374 pr.values.push_back (1 << i);
380 init_pq_ParameterRange (ix->pq, pr);
384 init_pq_ParameterRange (ix->pq, pr);
392 for (
int i = 8; i < 20; i++) {
393 pr_max_codes.values.push_back (1 << i);
395 pr_max_codes.values.push_back (1.0 / 0.0);
400 for (
int i = 0; i <= 6; i++) {
401 pr.values.push_back (1 << i);
404 if (dynamic_cast<const IndexHNSW*>(index)) {
406 for (
int i = 2; i <= 9; i++) {
407 pr.values.push_back (1 << i);
415 #define DC(classname) classname *ix = dynamic_cast<classname *>(index)
424 size_t j = cno % pr.values.size();
425 cno /= pr.values.size();
426 double val = pr.values [j];
433 Index *index,
const char *description_in)
const
435 char description[strlen(description_in) + 1];
437 memcpy (description, description_in, strlen(description_in) + 1);
439 for (
char *tok = strtok_r (description,
" ,", &ptr);
441 tok = strtok_r (
nullptr,
" ,", &ptr)) {
444 int ret = sscanf (tok,
"%100[^=]=%lf", name, &val);
445 FAISS_THROW_IF_NOT_FMT (
446 ret == 2,
"could not interpret parameters %s", tok);
453 Index * index,
const std::string & name,
double val)
const
456 printf(
" set %s=%g\n", name.c_str(), val);
458 if (name ==
"verbose") {
468 for (
auto & shard_index : ix->shard_indexes) {
474 if (name ==
"k_factor_rf") {
475 ix->k_factor = int(val);
483 if (name ==
"verbose") {
488 if (name ==
"nprobe") {
490 ix->nprobe = int(val);
497 if (val >= ix->pq.code_size * 8) {
501 ix->polysemous_ht = int(val);
505 if (val >= ix->pq.code_size * 8) {
506 ix->polysemous_ht = 0;
508 ix->polysemous_ht = int(val);
514 if (name ==
"k_factor") {
520 if (name ==
"max_codes") {
522 ix->max_codes = std::isfinite(val) ? size_t(val) : 0;
527 if (name ==
"efSearch") {
529 ix->hnsw.efSearch = int(val);
534 dynamic_cast<IndexHNSW *>(ix->quantizer)) {
535 cq->hnsw.efSearch = int(val);
541 FAISS_THROW_FMT (
"ParameterSpace::set_index_parameter:"
542 "could not set parameter %s",
548 printf (
"ParameterSpace, %ld parameters, %ld combinations:\n",
552 printf (
" %s: ", pr.name.c_str ());
554 for (
int j = 0; j < pr.values.size(); j++) {
555 printf (
"%c %g", sep, pr.values [j]);
565 double *upper_bound_perf,
566 double *lower_bound_t)
const
569 if (op.
t > *lower_bound_t) *lower_bound_t = op.
t;
572 if (op.
perf < *upper_bound_perf) *upper_bound_perf = op.
perf;
579 size_t nq,
const float *xq,
583 FAISS_THROW_IF_NOT_MSG (nq == crit.
nq,
584 "criterion does not have the same nb of queries");
590 for (
size_t cno = 0; cno < n_comb; cno++) {
592 std::vector<Index::idx_t> I(nq * crit.
nnn);
593 std::vector<float> D(nq * crit.
nnn);
596 index->
search (nq, xq, crit.
nnn, D.data(), I.data());
599 double perf = crit.
evaluate (D.data(), I.data());
604 printf(
" %ld/%ld: %s perf=%.3f t=%.3f s %s\n", cno, n_comb,
613 if (n_exp > n_comb) n_exp = n_comb;
614 FAISS_THROW_IF_NOT (n_comb == 1 || n_exp > 2);
615 std::vector<int> perm (n_comb);
619 perm[1] = n_comb - 1;
620 rand_perm (&perm[2], n_comb - 2, 1234);
621 for (
int i = 2; i < perm.size(); i++) perm[i] ++;
624 for (
size_t xp = 0; xp < n_exp; xp++) {
625 size_t cno = perm[xp];
628 printf(
" %ld/%d: cno=%ld %s ", xp, n_exp, cno,
632 double lower_bound_t = 0.0;
633 double upper_bound_perf = 1.0;
634 for (
int i = 0; i < ops->
all_pts.size(); i++) {
636 &upper_bound_perf, &lower_bound_t);
638 double best_t = ops->
t_for_perf (upper_bound_perf);
640 printf (
"bounds [perf<=%.3f t>=%.3f] %s",
641 upper_bound_perf, lower_bound_t,
642 best_t <= lower_bound_t ?
"skip\n" :
"");
643 if (best_t <= lower_bound_t)
continue;
647 std::vector<Index::idx_t> I(nq * crit.
nnn);
648 std::vector<float> D(nq * crit.
nnn);
658 #pragma omp parallel for
659 for (
size_t q0 = 0; q0 < nq; q0 +=
batchsize) {
661 if (q1 > nq) q1 = nq;
662 index->
search (q1 - q0, xq + q0 * index->
d,
664 D.data() + q0 * crit.
nnn,
665 I.data() + q0 * crit.
nnn);
668 for (
size_t q0 = 0; q0 < nq; q0 +=
batchsize) {
670 if (q1 > nq) q1 = nq;
671 index->
search (q1 - q0, xq + q0 * index->
d,
673 D.data() + q0 * crit.
nnn,
674 I.data() + q0 * crit.
nnn);
684 double perf = crit.
evaluate (D.data(), I.data());
689 printf(
" perf %.3f t %.3f (%d runs) %s\n",
690 perf, t_search, nrun,
702 std::vector<VectorTransform *> chain;
704 for (
int i = 0; i < chain.size(); i++) {
712 char get_trains_alone(
const Index *coarse_quantizer) {
714 dynamic_cast<const MultiIndexQuantizer*
>(coarse_quantizer) ? 1 :
715 dynamic_cast<const IndexHNSWFlat*>(coarse_quantizer) ? 2 :
725 Index *coarse_quantizer =
nullptr;
726 Index *index =
nullptr;
727 bool add_idmap =
false;
728 bool make_IndexRefineFlat =
false;
732 char description[strlen(description_in) + 1];
734 memcpy (description, description_in, strlen(description_in) + 1);
738 for (
char *tok = strtok_r (description,
" ,", &ptr);
740 tok = strtok_r (
nullptr,
" ,", &ptr)) {
741 int d_out, opq_M, nbit, M, M2, pq_m, ncent;
742 std::string stok(tok);
748 Index *coarse_quantizer_1 =
nullptr;
749 Index *index_1 =
nullptr;
752 if (sscanf (tok,
"PCA%d", &d_out) == 1) {
755 }
else if (sscanf (tok,
"PCAR%d", &d_out) == 1) {
756 vt_1 =
new PCAMatrix (d, d_out, 0,
true);
758 }
else if (sscanf (tok,
"RR%d", &d_out) == 1) {
761 }
else if (sscanf (tok,
"PCAW%d", &d_out) == 1) {
762 vt_1 =
new PCAMatrix (d, d_out, -0.5,
false);
764 }
else if (sscanf (tok,
"PCAWR%d", &d_out) == 1) {
765 vt_1 =
new PCAMatrix (d, d_out, -0.5,
true);
767 }
else if (sscanf (tok,
"OPQ%d_%d", &opq_M, &d_out) == 2) {
770 }
else if (sscanf (tok,
"OPQ%d", &opq_M) == 1) {
772 }
else if (stok ==
"L2norm") {
776 }
else if (!coarse_quantizer &&
777 sscanf (tok,
"IVF%d_HNSW%d", &ncentroids, &M) == 2) {
778 FAISS_THROW_IF_NOT (metric == METRIC_L2);
781 }
else if (!coarse_quantizer &&
782 sscanf (tok,
"IVF%d", &ncentroids) == 1) {
783 if (metric == METRIC_L2) {
788 }
else if (!coarse_quantizer && sscanf (tok,
"IMI2x%d", &nbit) == 1) {
789 FAISS_THROW_IF_NOT_MSG (metric == METRIC_L2,
790 "MultiIndex not implemented for inner prod search");
792 ncentroids = 1 << (2 * nbit);
793 }
else if (stok ==
"IDMap") {
797 }
else if (!index && (stok ==
"Flat" || stok ==
"FlatDedup")) {
798 if (coarse_quantizer) {
800 IndexIVF *index_ivf = stok ==
"Flat" ?
802 coarse_quantizer, d, ncentroids, metric) :
804 coarse_quantizer, d, ncentroids, metric);
806 get_trains_alone (coarse_quantizer);
807 index_ivf->
cp.
spherical = metric == METRIC_INNER_PRODUCT;
808 del_coarse_quantizer.release ();
812 FAISS_THROW_IF_NOT_MSG (stok !=
"FlatDedup",
813 "dedup supported only for IVFFlat");
816 }
else if (!index && (stok ==
"SQ8" || stok ==
"SQ4" ||
821 stok ==
"SQfp16" ? ScalarQuantizer::QT_fp16 :
823 if (coarse_quantizer) {
826 coarse_quantizer, d, ncentroids, qt, metric);
828 get_trains_alone (coarse_quantizer);
829 del_coarse_quantizer.release ();
835 }
else if (!index && sscanf (tok,
"PQ%d+%d", &M, &M2) == 2) {
836 FAISS_THROW_IF_NOT_MSG(coarse_quantizer,
837 "PQ with + works only with an IVF");
838 FAISS_THROW_IF_NOT_MSG(metric == METRIC_L2,
839 "IVFPQR not implemented for inner product search");
841 coarse_quantizer, d, ncentroids, M, 8, M2, 8);
843 get_trains_alone (coarse_quantizer);
844 del_coarse_quantizer.release ();
847 }
else if (!index && (sscanf (tok,
"PQ%d", &M) == 1 ||
848 sscanf (tok,
"PQ%dnp", &M) == 1)) {
849 bool do_polysemous_training = stok.find(
"np") == std::string::npos;
850 if (coarse_quantizer) {
852 coarse_quantizer, d, ncentroids, M, 8);
854 get_trains_alone (coarse_quantizer);
856 index_ivf->
cp.
spherical = metric == METRIC_INNER_PRODUCT;
857 del_coarse_quantizer.release ();
867 sscanf (tok,
"HNSW%d_%d+PQ%d", &M, &ncent, &pq_m) == 3) {
874 sscanf (tok,
"HNSW%d_2x%d+PQ%d", &M, &nbit, &pq_m) == 3) {
883 sscanf (tok,
"HNSW%d_PQ%d", &M, &pq_m) == 2) {
886 sscanf (tok,
"HNSW%d", &M) == 1) {
889 sscanf (tok,
"HNSW%d_SQ%d", &M, &pq_m) == 2 &&
892 }
else if (stok ==
"RFlat") {
893 make_IndexRefineFlat =
true;
895 FAISS_THROW_FMT(
"could not parse token \"%s\" in %s\n",
896 tok, description_in);
899 if (index_1 && add_idmap) {
901 del_index.set (idmap);
908 vts.chain.push_back (vt_1);
911 if (coarse_quantizer_1) {
912 coarse_quantizer = coarse_quantizer_1;
913 del_coarse_quantizer.set (coarse_quantizer);
918 del_index.set (index);
922 FAISS_THROW_IF_NOT_FMT(index,
"descrption %s did not generate an index",
926 del_index.release ();
927 del_coarse_quantizer.release ();
930 fprintf(stderr,
"index_factory: WARNING: "
931 "IDMap option not used\n");
934 if (vts.chain.size() > 0) {
938 while (vts.chain.size() > 0) {
939 index_pt->prepend_transform (vts.chain.back ());
940 vts.chain.pop_back ();
945 if (make_IndexRefineFlat) {
954 IndexBinary *index_binary_factory(
int d,
const char *description)
956 IndexBinary *index =
nullptr;
961 if (sscanf(description,
"BIVF%d_HNSW%d", &ncentroids, &M) == 2) {
962 IndexBinaryIVF *index_ivf =
new IndexBinaryIVF(
963 new IndexBinaryHNSW(d, M), d, ncentroids
965 index_ivf->own_fields =
true;
968 }
else if (sscanf(description,
"BIVF%d", &ncentroids) == 1) {
969 IndexBinaryIVF *index_ivf =
new IndexBinaryIVF(
970 new IndexBinaryFlat(d), d, ncentroids
972 index_ivf->own_fields =
true;
975 }
else if (sscanf(description,
"BHNSW%d", &M) == 1) {
976 IndexBinaryHNSW *index_hnsw =
new IndexBinaryHNSW(d, M);
979 }
else if (std::string(description) ==
"BFlat") {
980 index =
new IndexBinaryFlat(d);
983 FAISS_THROW_IF_NOT_FMT(index,
"descrption %s did not generate an index",
void explore(Index *index, size_t nq, const float *xq, const AutoTuneCriterion &crit, OperatingPoints *ops) const
std::vector< ParameterRange > parameter_ranges
all tunable parameters
std::string key
key that identifies this op pt
Randomly rotate a set of vectors.
long cno
integer identifer
bool do_polysemous_training
false = standard PQ
double evaluate(const float *D, const idx_t *I) const override
void display(bool only_optimal=true) const
easy-to-read output
double perf
performance measure (output of a Criterion)
double t_for_perf(double perf) const
get time required to obtain a given performance measure
idx_t nnn
nb of NNs that the query should request
double evaluate(const float *D, const idx_t *I) const override
bool add(double perf, double t, const std::string &key, size_t cno=0)
add a performance measure. Return whether it is an optimal point
bool do_polysemous_training
reorder PQ centroids after training?
size_t batchsize
maximum number of queries to submit at a time.
Level1Quantizer q1
first level quantizer
virtual double evaluate(const float *D, const idx_t *I) const =0
idx_t nq
nb of queries this criterion is evaluated on
std::vector< OperatingPoint > optimal_pts
optimal operating points, sorted by perf
void set_groundtruth(int gt_nnn, const float *gt_D_in, const idx_t *gt_I_in)
ParameterRange & add_range(const char *name)
add a new parameter (or return it if it exists)
idx_t gt_nnn
nb of GT NNs required to evaluate crterion
void all_to_gnuplot(const char *fname) const
output to a format easy to digest by gnuplot
bool own_fields
should the base index be deallocated?
size_t code_size
byte per indexed vector
char quantizer_trains_alone
std::vector< OperatingPoint > all_pts
all operating points
size_t ranklist_intersection_size(size_t k1, const long *v1, size_t k2, const long *v2_in)
ClusteringParameters cp
to override default clustering params
bool verbose
verbosity level
double getmillisecs()
ms elapsed since some arbitrary epoch
std::vector< float > gt_D
Ground-truth distances (size nq * gt_nnn)
std::string combination_name(size_t cno) const
get string representation of the combination
virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const =0
void update_bounds(size_t cno, const OperatingPoint &op, double *upper_bound_perf, double *lower_bound_t) const
virtual void initialize(const Index *index)
initialize with reasonable parameters for the index
int verbose
verbosity during exploration
int merge_with(const OperatingPoints &other, const std::string &prefix="")
add operating points from other to this, with a prefix to the keys
virtual void set_index_parameter(Index *index, const std::string &name, double val) const
set one of the parameters
size_t n_combinations() const
nb of combinations, = product of values sizes
MetricType metric_type
type of metric this index uses for search
void set_index_parameters(Index *index, size_t cno) const
set a combination of parameters on an index
asymmetric product quantizer (default)
void display() const
print a description on stdout
HE filter (using ht) + PQ combination.
bool combination_ge(size_t c1, size_t c2) const
returns whether combinations c1 >= c2 in the tuple sense
bool spherical
do we want normalized centroids?
bool own_fields
whether object owns the quantizer
possible values of a parameter, sorted from least to most expensive/accurate
Index * index_factory(int d, const char *description_in, MetricType metric)
int n_experiments
nb of experiments during optimization (0 = try all combinations)
std::vector< idx_t > gt_I
Ground-truth indexes (size nq * gt_nnn)
double t
corresponding execution time (ms)
MetricType
Some algorithms support both an inner product version and a L2 search version.
bool own_fields
! the sub-index