21 #include "FaissAssert.h"
22 #include "IndexFlat.h"
23 #include "AuxIndexStructures.h"
32 IndexIVF::IndexIVF (
Index * quantizer,
size_t d,
size_t nlist,
37 quantizer (quantizer),
38 quantizer_trains_alone (false),
41 maintain_direct_map (false)
43 FAISS_ASSERT (d == quantizer->
d);
57 IndexIVF::IndexIVF ():
58 nlist (0), nprobe (1), quantizer (nullptr),
59 quantizer_trains_alone (false), own_fields (false),
60 maintain_direct_map (false)
73 direct_map.resize (
ntotal, -1);
74 for (
size_t key = 0; key <
nlist; key++) {
75 const std::vector<long> & idlist =
ids[key];
77 for (
long ofs = 0; ofs < idlist.size(); ofs++) {
78 direct_map [idlist [ofs]] =
91 for (
size_t i = 0; i <
ids.size(); i++)
100 printf (
"IVF quantizer does not need training.\n");
103 printf (
"IVF quantizer trains alone...\n");
106 !
"nlist not consistent with quantizer size");
109 printf (
"Training IVF quantizer on %ld vectors in %dD\n",
119 printf (
"Training IVF residual\n");
128 printf (
"IndexIVF: no residual training\n");
136 std::vector<int> hist (
nlist);
137 for (
int i = 0; i <
nlist; i++) {
138 hist[i] =
ids[i].size();
145 std::vector<int> sizes(40);
146 for (
int i = 0; i <
nlist; i++) {
147 for (
int j = 0; j < sizes.size(); j++) {
148 if ((
ids[i].size() >> j) == 0) {
154 for (
int i = 0; i < sizes.size(); i++) {
156 printf (
"list size in < %d: %d instances\n",
166 FAISS_ASSERT (other.
d ==
d);
169 !
"direct map copy not implemented");
170 FAISS_ASSERT (
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)
215 s <<
"[" << nlist <<
":" << quantizer->index_typename <<
"]";
216 index_typename = s.str();
230 const long *precomputed_idx)
236 if (precomputed_idx) {
237 idx = precomputed_idx;
239 long * idx0 =
new long [n];
240 quantizer->assign (n, x, idx0);
244 for (
size_t i = 0; i < n; i++) {
245 long id = xids ? xids[i] :
ntotal + i;
246 long list_no = idx [i];
249 FAISS_ASSERT (list_no < nlist);
251 ids[list_no].push_back (
id);
252 const float *xi = x + i *
d;
254 for (
size_t j = 0 ; j <
d ; j++)
255 vecs[list_no].push_back (xi [j]);
258 direct_map.push_back (list_no << 32 | (
ids[list_no].size() - 1));
262 printf(
"IndexIVFFlat::add_core: added %ld / %ld vectors\n",
265 if (!precomputed_idx)
270 void IndexIVFFlatStats::reset()
272 memset ((
void*)
this, 0,
sizeof (*
this));
276 IndexIVFFlatStats indexIVFFlat_stats;
281 const long * __restrict keys,
285 const size_t k = res->
k;
286 size_t nlistv = 0, ndis = 0;
288 #pragma omp parallel for reduction(+: nlistv, ndis)
289 for (
size_t i = 0; i < nx; i++) {
290 const float * xi = x + i *
d;
291 const long * keysi = keys + i *
nprobe;
292 float * __restrict simi = res->
get_val (i);
293 long * __restrict idxi = res->
get_ids (i);
294 minheap_heapify (k, simi, idxi);
296 for (
size_t ik = 0; ik <
nprobe; ik++) {
297 long key = keysi[ik];
302 if (key >= (
long) nlist) {
303 fprintf (stderr,
"Invalid key=%ld at ik=%ld nlist=%ld\n",
308 const size_t list_size =
ids[key].size();
309 const float * list_vecs =
vecs[key].data();
311 for (
size_t j = 0; j < list_size; j++) {
312 const float * yj = list_vecs + d * j;
313 float ip = fvec_inner_product (xi, yj, d);
315 minheap_pop (k, simi, idxi);
316 minheap_push (k, simi, idxi, ip,
ids[key][j]);
321 minheap_reorder (k, simi, idxi);
323 indexIVFFlat_stats.nq += nx;
324 indexIVFFlat_stats.nlist += nlistv;
325 indexIVFFlat_stats.ndis += ndis;
332 const long * __restrict keys,
335 const size_t k = res->
k;
336 size_t nlistv = 0, ndis = 0;
338 #pragma omp parallel for reduction(+: nlistv, ndis)
339 for (
size_t i = 0; i < nx; i++) {
340 const float * xi = x + i *
d;
341 const long * keysi = keys + i *
nprobe;
342 float * __restrict disi = res->
get_val (i);
343 long * __restrict idxi = res->
get_ids (i);
344 maxheap_heapify (k, disi, idxi);
346 for (
size_t ik = 0; ik <
nprobe; ik++) {
347 long key = keysi[ik];
352 if (key >= (
long) nlist) {
353 fprintf (stderr,
"Invalid key=%ld at ik=%ld nlist=%ld\n",
358 const size_t list_size =
ids[key].size();
359 const float * list_vecs =
vecs[key].data();
361 for (
size_t j = 0; j < list_size; j++) {
362 const float * yj = list_vecs + d * j;
364 if (disij < disi[0]) {
365 maxheap_pop (k, disi, idxi);
366 maxheap_push (k, disi, idxi, disij,
ids[key][j]);
371 maxheap_reorder (k, disi, idxi);
373 indexIVFFlat_stats.nq += nx;
374 indexIVFFlat_stats.nlist += nlistv;
375 indexIVFFlat_stats.ndis += ndis;
380 float *distances,
idx_t *labels)
const
383 quantizer->assign (n, x, idx,
nprobe);
387 size_t(n), size_t(k), labels, distances};
392 size_t(n), size_t(k), labels, distances};
404 quantizer->assign (nx, x, keys,
nprobe);
406 assert (
metric_type == METRIC_L2 || !
"Only L2 implemented");
411 for (
size_t i = 0; i < nx; i++) {
412 const float * xi = x + i *
d;
413 const long * keysi = keys + i *
nprobe;
418 for (
size_t ik = 0; ik <
nprobe; ik++) {
419 long key = keysi[ik];
420 if (key < 0 || key >= (
long) nlist) {
421 fprintf (stderr,
"Invalid key=%ld at ik=%ld nlist=%ld\n",
426 const size_t list_size =
ids[key].size();
427 const float * list_vecs =
vecs[key].data();
429 for (
size_t j = 0; j < list_size; j++) {
430 const float * yj = list_vecs + d * j;
432 if (disij < radius) {
433 qres.add (disij,
ids[key][j]);
447 for (
int i = 0; i <
nlist; i++) {
448 std::vector<float> & src = other.
vecs[i];
449 std::vector<float> & dest =
vecs[i];
450 for (
int j = 0; j < src.size(); j++)
451 dest.push_back (src[j]);
457 long a1,
long a2)
const
459 FAISS_ASSERT (nlist == other.
nlist);
462 for (
long list_no = 0; list_no <
nlist; list_no++) {
463 const std::vector<idx_t> & ids_in =
ids[list_no];
464 std::vector<idx_t> & ids_out = other.
ids[list_no];
465 const std::vector<float> & vecs_in =
vecs[list_no];
466 std::vector<float> & vecs_out = other.
vecs[list_no];
468 for (
long i = 0; i < ids_in.size(); i++) {
469 idx_t id = ids_in[i];
470 if (subset_type == 0 && a1 <=
id &&
id < a2) {
471 ids_out.push_back (
id);
472 vecs_out.insert (vecs_out.end(),
473 vecs_in.begin() + i *
d,
474 vecs_in.begin() + (i + 1) * d);
486 for (
size_t key = 0; key <
nlist; key++) {
494 !
"direct map remove not implemented");
496 #pragma omp parallel for reduction(+: nremove)
497 for (
long i = 0; i <
nlist; i++) {
498 std::vector<idx_t> & idsi =
ids[i];
499 float *vecsi =
vecs[i].data();
501 long l = idsi.size(), j = 0;
503 if (sel.is_member (idsi[j])) {
506 memmove (vecsi + j * d,
507 vecsi + l * d, d *
sizeof (
float));
512 if (l < idsi.size()) {
513 nremove += idsi.size() - l;
515 vecs[i].resize (l * d);
525 assert (direct_map.size() ==
ntotal);
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) {
554 if (precomputed_idx) {
555 idx = precomputed_idx;
557 long * idx0 =
new long [n];
558 quantizer->
assign (n, x, idx0);
564 const float * xi = x +
fsize;
565 for (
size_t i = 0; i < n; i++) {
571 if (idx != precomputed_idx) {
579 void search_bounds_knn_inner_product (
587 size_t k = res->
k, nx = res->
nh, nprobe = ivf.
nprobe;
589 int fsize = ivf.
fsize;
591 size_t nlistv = 0, ndis = 0, npartial = 0;
593 #pragma omp parallel for reduction(+: nlistv, ndis, npartial)
594 for (
size_t i = 0; i < nx; i++) {
595 const float * xi = x + i * d;
596 const long * keysi = keys + i * nprobe;
597 float qnorm = qnorms[i];
598 float * __restrict simi = res->
get_val (i);
599 long * __restrict idxi = res->
get_ids (i);
600 minheap_heapify (k, simi, idxi);
602 for (
size_t ik = 0; ik < nprobe; ik++) {
603 long key = keysi[ik];
608 assert (key < (
long) ivf.
nlist);
611 const size_t list_size = ivf.
ids[key].size();
612 const float * yj = ivf.
vecs[key].data();
613 const float * bnorms = ivf.
part_norms[key].data();
615 for (
size_t j = 0; j < list_size; j++) {
616 float ip_part = fvec_inner_product (xi, yj, fsize);
617 float bound = ip_part + bnorms[j] * qnorm;
619 if (bound > simi[0]) {
620 float ip = ip_part + fvec_inner_product (
621 xi + fsize, yj + fsize, d - fsize);
623 minheap_pop (k, simi, idxi);
624 minheap_push (k, simi, idxi, ip, ivf.
ids[key][j]);
630 npartial += list_size;
632 minheap_reorder (k, simi, idxi);
634 indexIVFFlat_stats.nq += nx;
635 indexIVFFlat_stats.nlist += nlistv;
636 indexIVFFlat_stats.ndis += ndis;
637 indexIVFFlat_stats.npartial += npartial;
646 float *distances,
idx_t *labels)
const
650 quantizer->
assign (n, x, idx, nprobe);
652 float * qnorms =
new float [n];
654 #pragma omp parallel for
655 for (
size_t i = 0; i < n; i++) {
657 x + i * d + fsize, d - fsize));
661 size_t(n), size_t(k), labels, distances};
663 search_bounds_knn_inner_product (*
this, x, idx, &res, qnorms);
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
virtual 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
virtual void set_typename() override
virtual 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
virtual 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
virtual 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
virtual 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
virtual 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
virtual 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
virtual void reset() override
removes all elements from the database.
QueryResult & new_result(idx_t qno)
begin a new result
virtual 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
virtual 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
virtual 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
virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const override