20 #include "FaissAssert.h"
21 #include "IndexFlat.h"
22 #include "AuxIndexStructures.h"
31 IndexIVF::IndexIVF (
Index * quantizer,
size_t d,
size_t nlist,
36 quantizer (quantizer),
37 quantizer_trains_alone (false),
40 maintain_direct_map (false)
42 FAISS_THROW_IF_NOT (d == quantizer->
d);
56 IndexIVF::IndexIVF ():
57 nlist (0), nprobe (1), quantizer (nullptr),
58 quantizer_trains_alone (false), own_fields (false),
59 maintain_direct_map (false)
72 direct_map.resize (
ntotal, -1);
73 for (
size_t key = 0; key <
nlist; key++) {
74 const std::vector<long> & idlist =
ids[key];
76 for (
long ofs = 0; ofs < idlist.size(); ofs++) {
77 direct_map [idlist [ofs]] =
90 for (
size_t i = 0; i <
ids.size(); i++)
99 printf (
"IVF quantizer does not need training.\n");
102 printf (
"IVF quantizer trains alone...\n");
105 "nlist not consistent with quantizer size");
108 printf (
"Training IVF quantizer on %ld vectors in %dD\n",
118 printf (
"Training IVF residual\n");
127 printf (
"IndexIVF: no residual training\n");
135 std::vector<int> hist (
nlist);
136 for (
int i = 0; i <
nlist; i++) {
137 hist[i] =
ids[i].size();
144 std::vector<int> sizes(40);
145 for (
int i = 0; i <
nlist; i++) {
146 for (
int j = 0; j < sizes.size(); j++) {
147 if ((
ids[i].size() >> j) == 0) {
153 for (
int i = 0; i < sizes.size(); i++) {
155 printf (
"list size in < %d: %d instances\n",
165 FAISS_THROW_IF_NOT (other.
d ==
d);
169 "direct map copy not implemented");
170 FAISS_THROW_IF_NOT_MSG (
typeid (*
this) ==
typeid (other),
171 "can only merge indexes of the same type");
172 for (
long i = 0; i <
nlist; i++) {
173 std::vector<idx_t> & src = other.
ids[i];
174 std::vector<idx_t> & dest =
ids[i];
175 for (
long j = 0; j < src.size(); j++)
176 dest.push_back (src[j] + add_id);
187 IndexIVF::~IndexIVF()
198 IndexIVFFlat::IndexIVFFlat (Index * quantizer,
200 IndexIVF (quantizer, d, nlist, metric)
216 const long *precomputed_idx)
223 if (precomputed_idx) {
224 idx = precomputed_idx;
226 long * idx0 =
new long [n];
227 quantizer->assign (n, x, idx0);
232 for (
size_t i = 0; i < n; i++) {
233 long id = xids ? xids[i] :
ntotal + i;
234 long list_no = idx [i];
237 assert (list_no < nlist);
239 ids[list_no].push_back (
id);
240 const float *xi = x + i *
d;
242 for (
size_t j = 0 ; j <
d ; j++)
243 vecs[list_no].push_back (xi [j]);
246 direct_map.push_back (list_no << 32 | (
ids[list_no].size() - 1));
250 printf(
"IndexIVFFlat::add_core: added %ld / %ld vectors\n",
256 void IndexIVFFlatStats::reset()
258 memset ((
void*)
this, 0,
sizeof (*
this));
262 IndexIVFFlatStats indexIVFFlat_stats;
267 const long * __restrict keys,
271 const size_t k = res->
k;
272 size_t nlistv = 0, ndis = 0;
274 #pragma omp parallel for reduction(+: nlistv, ndis)
275 for (
size_t i = 0; i < nx; i++) {
276 const float * xi = x + i *
d;
277 const long * keysi = keys + i *
nprobe;
278 float * __restrict simi = res->
get_val (i);
279 long * __restrict idxi = res->
get_ids (i);
280 minheap_heapify (k, simi, idxi);
282 for (
size_t ik = 0; ik <
nprobe; ik++) {
283 long key = keysi[ik];
288 if (key >= (
long) nlist) {
289 fprintf (stderr,
"Invalid key=%ld at ik=%ld nlist=%ld\n",
294 const size_t list_size =
ids[key].size();
295 const float * list_vecs =
vecs[key].data();
297 for (
size_t j = 0; j < list_size; j++) {
298 const float * yj = list_vecs + d * j;
299 float ip = fvec_inner_product (xi, yj, d);
301 minheap_pop (k, simi, idxi);
302 minheap_push (k, simi, idxi, ip,
ids[key][j]);
307 minheap_reorder (k, simi, idxi);
309 indexIVFFlat_stats.nq += nx;
310 indexIVFFlat_stats.nlist += nlistv;
311 indexIVFFlat_stats.ndis += ndis;
318 const long * __restrict keys,
321 const size_t k = res->
k;
322 size_t nlistv = 0, ndis = 0;
324 #pragma omp parallel for reduction(+: nlistv, ndis)
325 for (
size_t i = 0; i < nx; i++) {
326 const float * xi = x + i *
d;
327 const long * keysi = keys + i *
nprobe;
328 float * __restrict disi = res->
get_val (i);
329 long * __restrict idxi = res->
get_ids (i);
330 maxheap_heapify (k, disi, idxi);
332 for (
size_t ik = 0; ik <
nprobe; ik++) {
333 long key = keysi[ik];
338 if (key >= (
long) nlist) {
339 fprintf (stderr,
"Invalid key=%ld at ik=%ld nlist=%ld\n",
344 const size_t list_size =
ids[key].size();
345 const float * list_vecs =
vecs[key].data();
347 for (
size_t j = 0; j < list_size; j++) {
348 const float * yj = list_vecs + d * j;
350 if (disij < disi[0]) {
351 maxheap_pop (k, disi, idxi);
352 maxheap_push (k, disi, idxi, disij,
ids[key][j]);
357 maxheap_reorder (k, disi, idxi);
359 indexIVFFlat_stats.nq += nx;
360 indexIVFFlat_stats.nlist += nlistv;
361 indexIVFFlat_stats.ndis += ndis;
366 float *distances,
idx_t *labels)
const
370 quantizer->assign (n, x, idx,
nprobe);
377 float *distances,
idx_t *labels)
const
381 size_t(n), size_t(k), labels, distances};
386 size_t(n), size_t(k), labels, distances};
398 quantizer->assign (nx, x, keys,
nprobe);
404 for (
size_t i = 0; i < nx; i++) {
405 const float * xi = x + i *
d;
406 const long * keysi = keys + i *
nprobe;
411 for (
size_t ik = 0; ik <
nprobe; ik++) {
412 long key = keysi[ik];
413 if (key < 0 || key >= (
long) nlist) {
414 fprintf (stderr,
"Invalid key=%ld at ik=%ld nlist=%ld\n",
419 const size_t list_size =
ids[key].size();
420 const float * list_vecs =
vecs[key].data();
422 for (
size_t j = 0; j < list_size; j++) {
423 const float * yj = list_vecs + d * j;
426 if (disij < radius) {
427 qres.add (disij,
ids[key][j]);
430 float disij = fvec_inner_product(xi, yj, d);
431 if (disij > radius) {
432 qres.add (disij,
ids[key][j]);
446 for (
int i = 0; i <
nlist; i++) {
447 std::vector<float> & src = other.
vecs[i];
448 std::vector<float> & dest =
vecs[i];
449 for (
int j = 0; j < src.size(); j++)
450 dest.push_back (src[j]);
456 long a1,
long a2)
const
458 FAISS_THROW_IF_NOT (nlist == other.
nlist);
461 for (
long list_no = 0; list_no <
nlist; list_no++) {
462 const std::vector<idx_t> & ids_in =
ids[list_no];
463 std::vector<idx_t> & ids_out = other.
ids[list_no];
464 const std::vector<float> & vecs_in =
vecs[list_no];
465 std::vector<float> & vecs_out = other.
vecs[list_no];
467 for (
long i = 0; i < ids_in.size(); i++) {
468 idx_t id = ids_in[i];
469 if (subset_type == 0 && a1 <=
id &&
id < a2) {
470 ids_out.push_back (
id);
471 vecs_out.insert (vecs_out.end(),
472 vecs_in.begin() + i *
d,
473 vecs_in.begin() + (i + 1) * d);
485 for (
size_t key = 0; key <
nlist; key++) {
493 "direct map remove not implemented");
495 #pragma omp parallel for reduction(+: nremove)
496 for (
long i = 0; i <
nlist; i++) {
497 std::vector<idx_t> & idsi =
ids[i];
498 float *vecsi =
vecs[i].data();
500 long l = idsi.size(), j = 0;
502 if (sel.is_member (idsi[j])) {
505 memmove (vecsi + j * d,
506 vecsi + l * d, d *
sizeof (
float));
511 if (l < idsi.size()) {
512 nremove += idsi.size() - l;
514 vecs[i].resize (l * d);
524 FAISS_THROW_IF_NOT_MSG (direct_map.size() ==
ntotal,
525 "direct map is not initialized");
526 int list_no = direct_map[key] >> 32;
527 int ofs = direct_map[key] & 0xffffffff;
528 memcpy (recons, &
vecs[list_no][ofs * d], d *
sizeof(recons[0]));
538 IndexIVFFlatIPBounds::IndexIVFFlatIPBounds (
539 Index * quantizer,
size_t d,
size_t nlist,
541 IndexIVFFlat(quantizer, d, nlist, METRIC_INNER_PRODUCT), fsize(fsize)
543 part_norms.resize(nlist);
549 const long *precomputed_idx) {
555 if (precomputed_idx) {
556 idx = precomputed_idx;
558 long * idx0 =
new long [n];
559 quantizer->
assign (n, x, idx0);
566 const float * xi = x +
fsize;
567 for (
size_t i = 0; i < n; i++) {
578 void search_bounds_knn_inner_product (
586 size_t k = res->
k, nx = res->
nh, nprobe = ivf.
nprobe;
588 int fsize = ivf.
fsize;
590 size_t nlistv = 0, ndis = 0, npartial = 0;
592 #pragma omp parallel for reduction(+: nlistv, ndis, npartial)
593 for (
size_t i = 0; i < nx; i++) {
594 const float * xi = x + i * d;
595 const long * keysi = keys + i * nprobe;
596 float qnorm = qnorms[i];
597 float * __restrict simi = res->
get_val (i);
598 long * __restrict idxi = res->
get_ids (i);
599 minheap_heapify (k, simi, idxi);
601 for (
size_t ik = 0; ik < nprobe; ik++) {
602 long key = keysi[ik];
607 assert (key < (
long) ivf.
nlist);
610 const size_t list_size = ivf.
ids[key].size();
611 const float * yj = ivf.
vecs[key].data();
612 const float * bnorms = ivf.
part_norms[key].data();
614 for (
size_t j = 0; j < list_size; j++) {
615 float ip_part = fvec_inner_product (xi, yj, fsize);
616 float bound = ip_part + bnorms[j] * qnorm;
618 if (bound > simi[0]) {
619 float ip = ip_part + fvec_inner_product (
620 xi + fsize, yj + fsize, d - fsize);
622 minheap_pop (k, simi, idxi);
623 minheap_push (k, simi, idxi, ip, ivf.
ids[key][j]);
629 npartial += list_size;
631 minheap_reorder (k, simi, idxi);
633 indexIVFFlat_stats.nq += nx;
634 indexIVFFlat_stats.nlist += nlistv;
635 indexIVFFlat_stats.ndis += ndis;
636 indexIVFFlat_stats.npartial += npartial;
645 float *distances,
idx_t *labels)
const
650 quantizer->
assign (n, x, idx, nprobe);
652 float * qnorms =
new float [n];
655 #pragma omp parallel for
656 for (
size_t i = 0; i < n; i++) {
658 x + i * d + fsize, d - fsize));
662 size_t(n), size_t(k), labels, distances};
664 search_bounds_knn_inner_product (*
this, x, idx, &res, qnorms);
void search_preassigned(idx_t n, const float *x, idx_t k, const idx_t *assign, float *distances, idx_t *labels) const
perform search, without computing the assignment to the quantizer
int niter
clustering iterations
result structure for a single query
float fvec_L2sqr(const float *x, const float *y, size_t d)
Squared L2 distance between two vectors.
void search_knn_L2sqr(size_t nx, const float *x, const long *keys, float_maxheap_array_t *res) const
Implementation of the search for the L2 metric.
T * get_val(size_t key)
Return the list of values for a heap.
double imbalance_factor() const
1= perfectly balanced, >1: imbalanced
virtual void reset()=0
removes all elements from the database.
size_t nprobe
number of probes at query time
void reconstruct(idx_t key, float *recons) const override
void assign(idx_t n, const float *x, idx_t *labels, idx_t k=1)
bool quantizer_trains_alone
just pass over the trainset to quantizer
void range_search(idx_t n, const float *x, float radius, RangeSearchResult *result) const override
void copy_subset_to(IndexIVFFlat &other, int subset_type, long a1, long a2) const
void merge_from_residuals(IndexIVF &other) override
virtual void add_with_ids(idx_t n, const float *x, const long *xids)
virtual void train_residual(idx_t n, const float *x)
size_t k
allocated size per heap
double imbalance_factor(int n, int k, const long *assign)
a balanced assignment has a IF of 1
long remove_ids(const IDSelector &sel) override
std::vector< std::vector< long > > ids
Inverted lists for indexes.
Index * quantizer
quantizer that maps vectors to inverted lists
void train(idx_t n, const float *x) override
Trains the quantizer and calls train_residual to train sub-quantizers.
ClusteringParameters cp
to override default clustering params
void add_with_ids(idx_t n, const float *x, const long *xids) override
implemented for all IndexIVF* classes
bool own_fields
whether object owns the quantizer
long idx_t
all indices are this type
void reset() override
removes all elements from the database.
void make_direct_map()
intialize a direct map
idx_t ntotal
total nb of indexed vectors
bool verbose
verbosity level
void reset() override
removes all elements from the database.
QueryResult & new_result(idx_t qno)
begin a new result
void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const override
std::vector< std::vector< float > > part_norms
norm of remainder (dimensions fsize:d)
float fvec_norm_L2sqr(const float *x, size_t d)
size_t fsize
nb of dimensions of pre-filter
the entries in the buffers are split per query
virtual void merge_from_residuals(IndexIVF &other)=0
TI * get_ids(size_t key)
Correspponding identifiers.
MetricType metric_type
type of metric this index uses for search
void print_stats() const
display some stats about the inverted lists
void add_core(idx_t n, const float *x, const long *xids, const long *precomputed_idx) override
same as add_with_ids, with precomputed coarse quantizer
size_t nlist
number of possible key values
void add(idx_t n, const float *x) override
Quantizes x and calls add_with_key.
virtual void train(idx_t n, const float *x, faiss::Index &index)
Index is used during the assignment stage.
bool is_trained
set if the Index does not require training, or if training is done already
void search_knn_inner_product(size_t nx, const float *x, const long *keys, float_minheap_array_t *res) const
Implementation of the search for the inner product metric.
virtual void train(idx_t n, const float *x)
bool maintain_direct_map
map for direct access to the elements. Enables reconstruct().
bool spherical
do we want normalized centroids?
virtual void merge_from(IndexIVF &other, idx_t add_id)
MetricType
Some algorithms support both an inner product vetsion and a L2 search version.
std::vector< std::vector< float > > vecs
virtual void add_core(idx_t n, const float *x, const long *xids, const long *precomputed_idx)
same as add_with_ids, with precomputed coarse quantizer
void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const override