16 #include "FaissAssert.h"
19 #include "IndexFlat.h"
20 #include "VectorTransform.h"
24 #include "IndexIVFPQ.h"
25 #include "MetaIndexes.h"
32 AutoTuneCriterion::AutoTuneCriterion (idx_t nq, idx_t nnn):
33 nq (nq), nnn (nnn), gt_nnn (0)
38 int gt_nnn,
const float *gt_D_in,
const idx_t *gt_I_in)
42 gt_D.resize (nq * gt_nnn);
43 memcpy (
gt_D.data(), gt_D_in,
sizeof (
gt_D[0]) * nq * gt_nnn);
45 gt_I.resize (nq * gt_nnn);
46 memcpy (
gt_I.data(), gt_I_in,
sizeof (
gt_I[0]) * nq * gt_nnn);
51 OneRecallAtRCriterion::OneRecallAtRCriterion (idx_t nq, idx_t R):
55 double OneRecallAtRCriterion::evaluate (
const float *D,
const idx_t *I)
const
58 !
"gound truth not initialized");
60 for (idx_t q = 0; q <
nq; q++) {
62 const idx_t *I_line = I + q *
nnn;
63 for (
int i = 0; i < R; i++) {
64 if (I_line[i] == gt_nn) {
70 return n_ok / double (nq);
74 IntersectionCriterion::IntersectionCriterion (idx_t nq, idx_t R):
75 AutoTuneCriterion(nq, R), R(R)
81 !
"gound truth not initialized");
83 #pragma omp parallel for reduction(+: n_ok)
84 for (idx_t q = 0; q <
nq; q++) {
86 R, &
gt_I [q * gt_nnn],
89 return n_ok / double (nq * R);
96 OperatingPoints::OperatingPoints ()
120 if (perf > a.back().perf) {
123 }
else if (perf == a.back().perf) {
124 if (t < a.back ().t) {
132 for (i = 0; i < a.size(); i++) {
133 if (a[i].perf >= perf)
break;
135 assert (i < a.size());
137 if (a[i].perf == perf) {
140 a.insert (a.begin() + i, op);
147 int i = a.size() - 1;
149 if (a[i].t < a[i - 1].t)
150 a.erase (a.begin() + (i - 1));
159 const std::string & prefix)
162 for (
int i = 0; i < other.
all_pts.size(); i++) {
175 const std::vector<OperatingPoint> & a =
optimal_pts;
176 if (perf > a.back().perf)
return 1e50;
177 int i0 = -1, i1 = a.size() - 1;
178 while (i0 + 1 < i1) {
179 int imed = (i0 + i1 + 1) / 2;
180 if (a[imed].perf < perf) i0 = imed;
189 FILE *f = fopen(fname,
"w");
191 fprintf (stderr,
"cannot open %s", fname);
195 for (
int i = 0; i <
all_pts.size(); i++) {
197 fprintf (f,
"%g %g %s\n", op.
perf, op.
t, op.
key.c_str());
202 void OperatingPoints::optimal_to_gnuplot (
const char *fname)
const
204 FILE *f = fopen(fname,
"w");
206 fprintf (stderr,
"cannot open %s", fname);
210 double prev_perf = 0.0;
213 fprintf (f,
"%g %g\n", prev_perf, op.t);
214 fprintf (f,
"%g %g %s\n", op.perf, op.t, op.key.c_str());
222 const std::vector<OperatingPoint> &pts =
224 printf(
"Tested %ld operating points, %ld ones are optimal:\n",
227 for (
int i = 0; i < pts.size(); i++) {
229 const char *star =
"";
238 printf (
"cno=%ld key=%s perf=%.4f t=%.3f %s\n",
248 ParameterSpace::ParameterSpace ():
249 verbose (1), n_experiments (500),
250 batchsize (1<<30), thread_over_batches (false)
259 ParameterSpace::ParameterSpace (Index *index):
260 verbose (1), n_experiments (500),
261 batchsize (1<<30), thread_over_batches (false)
277 char buf[1000], *wp = buf;
281 size_t j = cno % pr.values.size();
282 cno /= pr.values.size();
284 wp, buf + 1000 - wp,
"%s%s=%g", i == 0 ?
"" :
",",
285 pr.name.c_str(), pr.values[j]);
287 return std::string (buf);
295 size_t j1 = c1 % nval;
296 size_t j2 = c2 % nval;
297 if (!(j1 >= j2))
return false;
306 #define DC(classname) \
307 const classname *ix = dynamic_cast<const classname *>(index)
315 for (
int i = 2; i <= pq.
code_size * 8 / 2; i+= 2)
316 pr.values.push_back(i);
337 for (
int i = 0; i <= 6; i++) {
338 pr.values.push_back (1 << i);
340 index = ix->base_index;
348 for (
int i = 0; i < 13; i++) {
349 size_t nprobe = 1 << i;
350 if (nprobe >= ix->nlist)
break;
351 pr.values.push_back (nprobe);
356 init_pq_ParameterRange (ix->pq, pr);
360 init_pq_ParameterRange (ix->pq, pr);
366 for (
int i = 8; i < 20; i++) {
367 pr_max_codes.values.push_back (1 << i);
369 pr_max_codes.values.push_back (1.0 / 0.0);
375 for (
int i = 0; i <= 6; i++) {
376 pr.values.push_back (1 << i);
384 #define DC(classname) classname *ix = dynamic_cast<classname *>(index)
393 size_t j = cno % pr.values.size();
394 cno /= pr.values.size();
395 double val = pr.values [j];
402 Index *index,
const char *description_in)
const
404 char description[strlen(description_in) + 1];
406 memcpy (description, description_in, strlen(description_in) + 1);
408 for (
char *tok = strtok_r (description,
" ,", &ptr);
410 tok = strtok_r (
nullptr,
" ,", &ptr)) {
413 FAISS_ASSERT (sscanf (tok,
"%100[^=]=%lf", name, &val) == 2);
420 Index * index,
const std::string & name,
double val)
const
423 printf(
" set %s=%g\n", name.c_str(), val);
425 if (name ==
"verbose") {
431 if (name ==
"verbose") {
435 if (name ==
"k_factor_rf") {
436 ix->k_factor = int(val);
439 index = ix->base_index;
444 if (name ==
"verbose") {
448 if (name ==
"nprobe") {
450 ix->nprobe = int(val);
451 }
else if (name ==
"ht") {
453 if (val >= ix->pq.code_size * 8) {
457 ix->polysemous_ht = int(val);
460 if (val >= ix->pq.code_size * 8) {
461 ix->polysemous_ht = 0;
463 ix->polysemous_ht = int(val);
466 }
else if (name ==
"k_factor") {
469 }
else if (name ==
"max_codes") {
471 ix->max_codes = finite(val) ? size_t(val) : 0;
474 "ParameterSpace::set_index_parameter:"
475 "could not set parameter %s\n",
482 printf (
"ParameterSpace, %ld parameters, %ld combinations:\n",
486 printf (
" %s: ", pr.name.c_str ());
488 for (
int j = 0; j < pr.values.size(); j++) {
489 printf (
"%c %g", sep, pr.values [j]);
499 double *upper_bound_perf,
500 double *lower_bound_t)
const
503 if (op.
t > *lower_bound_t) *lower_bound_t = op.
t;
506 if (op.
perf < *upper_bound_perf) *upper_bound_perf = op.
perf;
513 size_t nq,
const float *xq,
517 FAISS_ASSERT (nq == crit.
nq ||
518 !
"criterion does not have the same nb of queries");
524 for (
size_t cno = 0; cno < n_comb; cno++) {
526 std::vector<Index::idx_t> I(nq * crit.
nnn);
527 std::vector<float> D(nq * crit.
nnn);
530 index->
search (nq, xq, crit.
nnn, D.data(), I.data());
533 double perf = crit.
evaluate (D.data(), I.data());
538 printf(
" %ld/%ld: %s perf=%.3f t=%.3f s %s\n", cno, n_comb,
547 if (n_exp > n_comb) n_exp = n_comb;
548 FAISS_ASSERT (n_comb == 1 || n_exp > 2);
549 std::vector<int> perm (n_comb);
553 perm[1] = n_comb - 1;
554 rand_perm (&perm[2], n_comb - 2, 1234);
555 for (
int i = 2; i < perm.size(); i++) perm[i] ++;
558 for (
size_t xp = 0; xp < n_exp; xp++) {
559 size_t cno = perm[xp];
562 printf(
" %ld/%d: cno=%ld %s ", xp, n_exp, cno,
566 double lower_bound_t = 0.0;
567 double upper_bound_perf = 1.0;
568 for (
int i = 0; i < ops->
all_pts.size(); i++) {
570 &upper_bound_perf, &lower_bound_t);
572 double best_t = ops->
t_for_perf (upper_bound_perf);
574 printf (
"bounds [perf<=%.3f t>=%.3f] %s",
575 upper_bound_perf, lower_bound_t,
576 best_t <= lower_bound_t ?
"skip\n" :
"");
577 if (best_t <= lower_bound_t)
continue;
581 std::vector<Index::idx_t> I(nq * crit.
nnn);
582 std::vector<float> D(nq * crit.
nnn);
587 #pragma omp parallel for
588 for (
size_t q0 = 0; q0 < nq; q0 +=
batchsize) {
590 if (q1 > nq) q1 = nq;
591 index->
search (q1 - q0, xq + q0 * index->
d,
593 D.data() + q0 * crit.
nnn,
594 I.data() + q0 * crit.
nnn);
597 for (
size_t q0 = 0; q0 < nq; q0 +=
batchsize) {
599 if (q1 > nq) q1 = nq;
600 index->
search (q1 - q0, xq + q0 * index->
d,
602 D.data() + q0 * crit.
nnn,
603 I.data() + q0 * crit.
nnn);
609 double perf = crit.
evaluate (D.data(), I.data());
614 printf(
" perf %.3f t %.3f %s\n", perf, t_search,
626 Index *coarse_quantizer =
nullptr;
627 Index *index =
nullptr;
628 bool add_idmap =
false;
629 bool make_IndexRefineFlat =
false;
631 char description[strlen(description_in) + 1];
633 memcpy (description, description_in, strlen(description_in) + 1);
637 for (
char *tok = strtok_r (description,
" ,", &ptr);
639 tok = strtok_r (
nullptr,
" ,", &ptr)) {
640 int d_out, opq_M, nbit, M, M2;
642 Index *coarse_quantizer_1 =
nullptr;
643 Index *index_1 =
nullptr;
646 if (sscanf (tok,
"PCA%d", &d_out) == 1) {
649 }
else if (sscanf (tok,
"PCAR%d", &d_out) == 1) {
650 vt_1 =
new PCAMatrix (d, d_out, 0,
true);
652 }
else if (sscanf (tok,
"OPQ%d_%d", &opq_M, &d_out) == 2) {
655 }
else if (sscanf (tok,
"OPQ%d", &opq_M) == 1) {
658 }
else if (sscanf (tok,
"IVF%d", &ncentroids) == 1) {
659 if (metric == METRIC_L2) {
664 }
else if (sscanf (tok,
"IMI2x%d", &nbit) == 1) {
665 FAISS_ASSERT(metric == METRIC_L2 ||
666 !
"MultiIndex not implemented for inner prod search");
668 ncentroids = 1 << (2 * nbit);
669 }
else if (strcmp(tok,
"IDMap") == 0) {
673 }
else if (strcmp (tok,
"Flat") == 0) {
674 if (coarse_quantizer) {
677 coarse_quantizer, d, ncentroids, metric);
681 index_ivf->
cp.
spherical = metric == METRIC_INNER_PRODUCT;
693 }
else if (sscanf (tok,
"PQ%d+%d", &M, &M2) == 2) {
694 FAISS_ASSERT(coarse_quantizer ||
695 !
"PQ with + works only with an IVF");
696 FAISS_ASSERT(metric == METRIC_L2 ||
697 !
"IVFPQR not implemented for inner product search");
699 coarse_quantizer, d, ncentroids, M, 8, M2, 8);
705 }
else if (sscanf (tok,
"PQ%d", &M) == 1) {
706 if (coarse_quantizer) {
708 coarse_quantizer, d, ncentroids, M, 8);
713 index_ivf->
cp.
spherical = metric == METRIC_INNER_PRODUCT;
728 }
else if (strcmp (tok,
"RFlat") == 0) {
729 make_IndexRefineFlat =
true;
731 fprintf (stderr,
"could not parse token \"%s\" in %s\n",
732 tok, description_in);
733 FAISS_ASSERT (!
"parse error");
737 FAISS_ASSERT (!vt || !
"cannot apply two VectorTransforms");
741 if (coarse_quantizer_1) {
742 FAISS_ASSERT (!coarse_quantizer ||
743 !
"cannot have 2 coarse quantizers");
744 coarse_quantizer = coarse_quantizer_1;
748 FAISS_ASSERT (!index || !
"cannot have 2 indexes");
754 fprintf(stderr,
"index_factory: WARNING: "
755 "IDMap option not used\n");
764 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
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
bool quantizer_trains_alone
just pass over the trainset to quantizer
virtual 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.
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
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
ClusteringParameters cp
to override default clustering params
bool thread_over_batches
use multithreading over batches (useful to benchmark independent single-searches) ...
bool own_fields
whether object owns the quantizer
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)
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?
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 vetsion and a L2 search version.
bool own_fields
! the sub-index