15 #include "FaissAssert.h"
18 #include "IndexFlat.h"
19 #include "VectorTransform.h"
23 #include "IndexIVFPQ.h"
24 #include "IndexIVFFlat.h"
25 #include "MetaIndexes.h"
26 #include "IndexScalarQuantizer.h"
27 #include "IndexHNSW.h"
33 AutoTuneCriterion::AutoTuneCriterion (idx_t nq, idx_t nnn):
34 nq (nq), nnn (nnn), gt_nnn (0)
39 int gt_nnn,
const float *gt_D_in,
const idx_t *gt_I_in)
43 gt_D.resize (nq * gt_nnn);
44 memcpy (
gt_D.data(), gt_D_in,
sizeof (
gt_D[0]) * nq * gt_nnn);
46 gt_I.resize (nq * gt_nnn);
47 memcpy (
gt_I.data(), gt_I_in,
sizeof (
gt_I[0]) * nq * gt_nnn);
52 OneRecallAtRCriterion::OneRecallAtRCriterion (idx_t nq, idx_t R):
58 FAISS_THROW_IF_NOT_MSG(
60 "ground truth not initialized");
62 for (idx_t q = 0; q <
nq; q++) {
64 const idx_t* I_line = I + q *
nnn;
65 for (
int i = 0; i < R; i++) {
66 if (I_line[i] == gt_nn) {
72 return n_ok / double(nq);
76 IntersectionCriterion::IntersectionCriterion (idx_t nq, idx_t R):
82 FAISS_THROW_IF_NOT_MSG(
84 "ground truth not initialized");
86 #pragma omp parallel for reduction(+: n_ok)
87 for (idx_t q = 0; q <
nq; q++) {
89 R, &
gt_I [q * gt_nnn],
92 return n_ok / double (nq * R);
99 OperatingPoints::OperatingPoints ()
123 if (perf > a.back().perf) {
126 }
else if (perf == a.back().perf) {
127 if (t < a.back ().t) {
135 for (i = 0; i < a.size(); i++) {
136 if (a[i].perf >= perf)
break;
138 assert (i < a.size());
140 if (a[i].perf == perf) {
143 a.insert (a.begin() + i, op);
150 int i = a.size() - 1;
152 if (a[i].t < a[i - 1].t)
153 a.erase (a.begin() + (i - 1));
162 const std::string & prefix)
165 for (
int i = 0; i < other.
all_pts.size(); i++) {
178 const std::vector<OperatingPoint> & a =
optimal_pts;
179 if (perf > a.back().perf)
return 1e50;
180 int i0 = -1, i1 = a.size() - 1;
181 while (i0 + 1 < i1) {
182 int imed = (i0 + i1 + 1) / 2;
183 if (a[imed].perf < perf) i0 = imed;
192 FILE *f = fopen(fname,
"w");
194 fprintf (stderr,
"cannot open %s", fname);
198 for (
int i = 0; i <
all_pts.size(); i++) {
200 fprintf (f,
"%g %g %s\n", op.
perf, op.
t, op.
key.c_str());
205 void OperatingPoints::optimal_to_gnuplot (
const char *fname)
const
207 FILE *f = fopen(fname,
"w");
209 fprintf (stderr,
"cannot open %s", fname);
213 double prev_perf = 0.0;
216 fprintf (f,
"%g %g\n", prev_perf, op.t);
217 fprintf (f,
"%g %g %s\n", op.perf, op.t, op.key.c_str());
225 const std::vector<OperatingPoint> &pts =
227 printf(
"Tested %ld operating points, %ld ones are optimal:\n",
230 for (
int i = 0; i < pts.size(); i++) {
232 const char *star =
"";
241 printf (
"cno=%ld key=%s perf=%.4f t=%.3f %s\n",
251 ParameterSpace::ParameterSpace ():
252 verbose (1), n_experiments (500),
253 batchsize (1<<30), thread_over_batches (false)
262 ParameterSpace::ParameterSpace (Index *index):
263 verbose (1), n_experiments (500),
264 batchsize (1<<30), thread_over_batches (false)
280 char buf[1000], *wp = buf;
284 size_t j = cno % pr.values.size();
285 cno /= pr.values.size();
287 wp, buf + 1000 - wp,
"%s%s=%g", i == 0 ?
"" :
",",
288 pr.name.c_str(), pr.values[j]);
290 return std::string (buf);
298 size_t j1 = c1 % nval;
299 size_t j2 = c2 % nval;
300 if (!(j1 >= j2))
return false;
309 #define DC(classname) \
310 const classname *ix = dynamic_cast<const classname *>(index)
318 for (
int i = 2; i <= pq.
code_size * 8 / 2; i+= 2)
319 pr.values.push_back(i);
327 if (pr.name == name) {
332 parameter_ranges.back ().name = name;
333 return parameter_ranges.back ();
345 for (
int i = 0; i <= 6; i++) {
346 pr.values.push_back (1 << i);
348 index = ix->base_index;
357 for (
int i = 0; i < 13; i++) {
358 size_t nprobe = 1 << i;
359 if (nprobe >= ix->nlist)
break;
360 pr.values.push_back (nprobe);
363 if (dynamic_cast<const IndexHNSW*>(ix->quantizer)) {
365 for (
int i = 2; i <= 9; i++) {
366 pr.values.push_back (1 << i);
372 init_pq_ParameterRange (ix->pq, pr);
376 init_pq_ParameterRange (ix->pq, pr);
384 for (
int i = 8; i < 20; i++) {
385 pr_max_codes.values.push_back (1 << i);
387 pr_max_codes.values.push_back (1.0 / 0.0);
392 for (
int i = 0; i <= 6; i++) {
393 pr.values.push_back (1 << i);
396 if (dynamic_cast<const IndexHNSW*>(index)) {
398 for (
int i = 2; i <= 9; i++) {
399 pr.values.push_back (1 << i);
407 #define DC(classname) classname *ix = dynamic_cast<classname *>(index)
416 size_t j = cno % pr.values.size();
417 cno /= pr.values.size();
418 double val = pr.values [j];
425 Index *index,
const char *description_in)
const
427 char description[strlen(description_in) + 1];
429 memcpy (description, description_in, strlen(description_in) + 1);
431 for (
char *tok = strtok_r (description,
" ,", &ptr);
433 tok = strtok_r (
nullptr,
" ,", &ptr)) {
436 int ret = sscanf (tok,
"%100[^=]=%lf", name, &val);
437 FAISS_THROW_IF_NOT_FMT (
438 ret == 2,
"could not interpret parameters %s", tok);
445 Index * index,
const std::string & name,
double val)
const
448 printf(
" set %s=%g\n", name.c_str(), val);
450 if (name ==
"verbose") {
460 for (
auto & shard_index : ix->shard_indexes) {
466 if (name ==
"k_factor_rf") {
467 ix->k_factor = int(val);
475 if (name ==
"verbose") {
480 if (name ==
"nprobe") {
482 ix->nprobe = int(val);
489 if (val >= ix->pq.code_size * 8) {
493 ix->polysemous_ht = int(val);
497 if (val >= ix->pq.code_size * 8) {
498 ix->polysemous_ht = 0;
500 ix->polysemous_ht = int(val);
506 if (name ==
"k_factor") {
512 if (name ==
"max_codes") {
514 ix->max_codes = finite(val) ? size_t(val) : 0;
518 FAISS_THROW_FMT (
"ParameterSpace::set_index_parameter:"
519 "could not set parameter %s",
525 printf (
"ParameterSpace, %ld parameters, %ld combinations:\n",
529 printf (
" %s: ", pr.name.c_str ());
531 for (
int j = 0; j < pr.values.size(); j++) {
532 printf (
"%c %g", sep, pr.values [j]);
542 double *upper_bound_perf,
543 double *lower_bound_t)
const
546 if (op.
t > *lower_bound_t) *lower_bound_t = op.
t;
549 if (op.
perf < *upper_bound_perf) *upper_bound_perf = op.
perf;
556 size_t nq,
const float *xq,
560 FAISS_THROW_IF_NOT_MSG (nq == crit.
nq,
561 "criterion does not have the same nb of queries");
567 for (
size_t cno = 0; cno < n_comb; cno++) {
569 std::vector<Index::idx_t> I(nq * crit.
nnn);
570 std::vector<float> D(nq * crit.
nnn);
573 index->
search (nq, xq, crit.
nnn, D.data(), I.data());
576 double perf = crit.
evaluate (D.data(), I.data());
581 printf(
" %ld/%ld: %s perf=%.3f t=%.3f s %s\n", cno, n_comb,
590 if (n_exp > n_comb) n_exp = n_comb;
591 FAISS_THROW_IF_NOT (n_comb == 1 || n_exp > 2);
592 std::vector<int> perm (n_comb);
596 perm[1] = n_comb - 1;
597 rand_perm (&perm[2], n_comb - 2, 1234);
598 for (
int i = 2; i < perm.size(); i++) perm[i] ++;
601 for (
size_t xp = 0; xp < n_exp; xp++) {
602 size_t cno = perm[xp];
605 printf(
" %ld/%d: cno=%ld %s ", xp, n_exp, cno,
609 double lower_bound_t = 0.0;
610 double upper_bound_perf = 1.0;
611 for (
int i = 0; i < ops->
all_pts.size(); i++) {
613 &upper_bound_perf, &lower_bound_t);
615 double best_t = ops->
t_for_perf (upper_bound_perf);
617 printf (
"bounds [perf<=%.3f t>=%.3f] %s",
618 upper_bound_perf, lower_bound_t,
619 best_t <= lower_bound_t ?
"skip\n" :
"");
620 if (best_t <= lower_bound_t)
continue;
624 std::vector<Index::idx_t> I(nq * crit.
nnn);
625 std::vector<float> D(nq * crit.
nnn);
630 #pragma omp parallel for
631 for (
size_t q0 = 0; q0 < nq; q0 +=
batchsize) {
633 if (q1 > nq) q1 = nq;
634 index->
search (q1 - q0, xq + q0 * index->
d,
636 D.data() + q0 * crit.
nnn,
637 I.data() + q0 * crit.
nnn);
640 for (
size_t q0 = 0; q0 < nq; q0 +=
batchsize) {
642 if (q1 > nq) q1 = nq;
643 index->
search (q1 - q0, xq + q0 * index->
d,
645 D.data() + q0 * crit.
nnn,
646 I.data() + q0 * crit.
nnn);
652 double perf = crit.
evaluate (D.data(), I.data());
657 printf(
" perf %.3f t %.3f %s\n", perf, t_search,
669 std::vector<VectorTransform *> chain;
671 for (
int i = 0; i < chain.size(); i++) {
679 char get_trains_alone(
const Index *coarse_quantizer) {
681 dynamic_cast<const MultiIndexQuantizer*
>(coarse_quantizer) ? 1 :
691 Index *coarse_quantizer =
nullptr;
692 Index *index =
nullptr;
693 bool add_idmap =
false;
694 bool make_IndexRefineFlat =
false;
698 char description[strlen(description_in) + 1];
700 memcpy (description, description_in, strlen(description_in) + 1);
704 for (
char *tok = strtok_r (description,
" ,", &ptr);
706 tok = strtok_r (
nullptr,
" ,", &ptr)) {
707 int d_out, opq_M, nbit, M, M2, pq_m, ncent;
708 std::string stok(tok);
714 Index *coarse_quantizer_1 =
nullptr;
715 Index *index_1 =
nullptr;
718 if (sscanf (tok,
"PCA%d", &d_out) == 1) {
721 }
else if (sscanf (tok,
"PCAR%d", &d_out) == 1) {
722 vt_1 =
new PCAMatrix (d, d_out, 0,
true);
724 }
else if (sscanf (tok,
"PCAW%d", &d_out) == 1) {
725 vt_1 =
new PCAMatrix (d, d_out, -0.5,
false);
727 }
else if (sscanf (tok,
"PCAWR%d", &d_out) == 1) {
728 vt_1 =
new PCAMatrix (d, d_out, -0.5,
true);
730 }
else if (sscanf (tok,
"OPQ%d_%d", &opq_M, &d_out) == 2) {
733 }
else if (sscanf (tok,
"OPQ%d", &opq_M) == 1) {
735 }
else if (stok ==
"L2norm") {
738 }
else if (!coarse_quantizer &&
739 sscanf (tok,
"IVF%d_HNSW%d", &ncentroids, &M) == 2) {
740 FAISS_THROW_IF_NOT (metric == METRIC_L2);
742 }
else if (!coarse_quantizer &&
743 sscanf (tok,
"IVF%d", &ncentroids) == 1) {
744 if (metric == METRIC_L2) {
749 }
else if (!coarse_quantizer && sscanf (tok,
"IMI2x%d", &nbit) == 1) {
750 FAISS_THROW_IF_NOT_MSG (metric == METRIC_L2,
751 "MultiIndex not implemented for inner prod search");
753 ncentroids = 1 << (2 * nbit);
754 }
else if (stok ==
"IDMap") {
758 }
else if (!index && stok ==
"Flat") {
759 if (coarse_quantizer) {
762 coarse_quantizer, d, ncentroids, metric);
764 get_trains_alone (coarse_quantizer);
765 index_ivf->
cp.
spherical = metric == METRIC_INNER_PRODUCT;
766 del_coarse_quantizer.release ();
772 }
else if (!index && (stok ==
"SQ8" || stok ==
"SQ4")) {
777 if (coarse_quantizer) {
780 coarse_quantizer, d, ncentroids, qt, metric);
782 get_trains_alone (coarse_quantizer);
783 del_coarse_quantizer.release ();
789 }
else if (!index && sscanf (tok,
"PQ%d+%d", &M, &M2) == 2) {
790 FAISS_THROW_IF_NOT_MSG(coarse_quantizer,
791 "PQ with + works only with an IVF");
792 FAISS_THROW_IF_NOT_MSG(metric == METRIC_L2,
793 "IVFPQR not implemented for inner product search");
795 coarse_quantizer, d, ncentroids, M, 8, M2, 8);
797 get_trains_alone (coarse_quantizer);
798 del_coarse_quantizer.release ();
801 }
else if (!index && (sscanf (tok,
"PQ%d", &M) == 1 ||
802 sscanf (tok,
"PQ%dnp", &M) == 1)) {
803 bool do_polysemous_training = stok.find(
"np") == std::string::npos;
804 if (coarse_quantizer) {
806 coarse_quantizer, d, ncentroids, M, 8);
808 get_trains_alone (coarse_quantizer);
810 index_ivf->
cp.
spherical = metric == METRIC_INNER_PRODUCT;
811 del_coarse_quantizer.release ();
821 sscanf (tok,
"HNSW%d_%d+PQ%d", &M, &ncent, &pq_m) == 3) {
828 sscanf (tok,
"HNSW%d_2x%d+PQ%d", &M, &nbit, &pq_m) == 3) {
837 sscanf (tok,
"HNSW%d_PQ%d", &M, &pq_m) == 2) {
840 sscanf (tok,
"HNSW%d", &M) == 1) {
843 sscanf (tok,
"HNSW%d_SQ%d", &M, &pq_m) == 2 &&
846 }
else if (stok ==
"RFlat") {
847 make_IndexRefineFlat =
true;
849 FAISS_THROW_FMT(
"could not parse token \"%s\" in %s\n",
850 tok, description_in);
853 if (index_1 && add_idmap) {
855 del_index.set (idmap);
862 vts.chain.push_back (vt_1);
865 if (coarse_quantizer_1) {
866 coarse_quantizer = coarse_quantizer_1;
867 del_coarse_quantizer.set (coarse_quantizer);
872 del_index.set (index);
876 FAISS_THROW_IF_NOT_FMT(index,
"descrption %s did not generate an index",
880 del_index.release ();
881 del_coarse_quantizer.release ();
884 fprintf(stderr,
"index_factory: WARNING: "
885 "IDMap option not used\n");
888 if (vts.chain.size() > 0) {
892 while (vts.chain.size() > 0) {
893 index_pt->prepend_transform (vts.chain.back ());
894 vts.chain.pop_back ();
899 if (make_IndexRefineFlat) {
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
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