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 (0),
39 clustering_index (nullptr),
41 maintain_direct_map (false)
43 FAISS_THROW_IF_NOT (d == quantizer->
d);
58 IndexIVF::IndexIVF ():
59 nlist (0), nprobe (1), quantizer (nullptr),
60 quantizer_trains_alone (0), own_fields (false),
61 clustering_index (nullptr),
62 maintain_direct_map (false)
77 if (new_maintain_direct_map) {
78 direct_map.resize (
ntotal, -1);
79 for (
size_t key = 0; key <
nlist; key++) {
80 const std::vector<long> & idlist =
ids[key];
82 for (
long ofs = 0; ofs < idlist.size(); ofs++) {
83 FAISS_THROW_IF_NOT_MSG (
84 0 <= idlist [ofs] && idlist[ofs] <
ntotal,
85 "direct map supported only for seuquential ids");
86 direct_map [idlist [ofs]] = key << 32 | ofs;
97 float *distances,
idx_t *labels)
const
99 long * idx =
new long [n *
nprobe];
101 float * coarse_dis =
new float [n *
nprobe];
107 distances, labels,
false);
116 for (
size_t i = 0; i <
ids.size(); i++) {
126 "direct map remove not implemented");
128 #pragma omp parallel for reduction(+: nremove)
129 for (
long i = 0; i <
nlist; i++) {
130 std::vector<idx_t> & idsi =
ids[i];
131 uint8_t * codesi = codes[i].data();
133 long l = idsi.size(), j = 0;
135 if (sel.is_member (idsi[j])) {
139 codesi + l * code_size, code_size);
144 if (l < idsi.size()) {
145 nremove += idsi.size() - l;
161 printf (
"IVF quantizer does not need training.\n");
164 printf (
"IVF quantizer trains alone...\n");
168 "nlist not consistent with quantizer size");
171 printf (
"Training IVF quantizer on %ld vectors in %dD\n",
186 "Training L2 quantizer on %ld vectors in %dD%s\n",
193 clus.
train(n, x, assigner);
198 printf (
"Adding centroids to quantizer\n");
202 printf (
"Training IVF residual\n");
210 printf(
"IndexIVF: no residual training\n");
218 std::vector<int> hist (
nlist);
219 for (
int i = 0; i <
nlist; i++) {
220 hist[i] =
ids[i].size();
227 std::vector<int> sizes(40);
228 for (
int i = 0; i <
nlist; i++) {
229 for (
int j = 0; j < sizes.size(); j++) {
230 if ((
ids[i].size() >> j) == 0) {
236 for (
int i = 0; i < sizes.size(); i++) {
238 printf (
"list size in < %d: %d instances\n",
248 FAISS_THROW_IF_NOT (other.
d ==
d);
252 "direct map copy not implemented");
253 FAISS_THROW_IF_NOT_MSG (
typeid (*
this) ==
typeid (other),
254 "can only merge indexes of the same type");
255 for (
long i = 0; i <
nlist; i++) {
256 std::vector<idx_t> & src = other.
ids[i];
257 std::vector<idx_t> & dest =
ids[i];
258 for (
long j = 0; j < src.size(); j++)
259 dest.push_back (src[j] + add_id);
261 codes[i].insert (codes[i].end(),
262 other.codes[i].begin(),
263 other.codes[i].end());
264 other.codes[i].clear();
273 long a1,
long a2)
const
277 FAISS_THROW_IF_NOT_FMT (
278 subset_type == 0 || subset_type == 1 || subset_type == 2,
279 "subset type %d not implemented", subset_type);
285 for (
long list_no = 0; list_no <
nlist; list_no++) {
286 const std::vector<idx_t> & ids_in =
ids[list_no];
287 std::vector<idx_t> & ids_out = other.
ids[list_no];
288 const std::vector<uint8_t> & codes_in = codes[list_no];
289 std::vector<uint8_t> & codes_out = other.codes[list_no];
290 size_t n = ids_in.size();
292 if (subset_type == 0) {
293 for (
long i = 0; i < n; i++) {
294 idx_t id = ids_in[i];
295 if (a1 <=
id &&
id < a2) {
296 ids_out.push_back (
id);
297 codes_out.insert (codes_out.end(),
299 codes_in.begin() + (i + 1) * code_size);
303 }
else if (subset_type == 1) {
304 for (
long i = 0; i < n; i++) {
305 idx_t id = ids_in[i];
307 ids_out.push_back (
id);
308 codes_out.insert (codes_out.end(),
310 codes_in.begin() + (i + 1) * code_size);
314 }
else if (subset_type == 2) {
316 size_t next_accu_n = accu_n + n;
317 size_t next_accu_a1 = next_accu_n * a1 /
ntotal;
318 size_t i1 = next_accu_a1 - accu_a1;
319 size_t next_accu_a2 = next_accu_n * a2 /
ntotal;
320 size_t i2 = next_accu_a2 - accu_a2;
321 ids_out.insert(ids_out.end(),
323 ids_in.begin() + i2);
324 codes_out.insert (codes_out.end(),
328 accu_a1 = next_accu_a1;
329 accu_a2 = next_accu_a2;
333 FAISS_ASSERT(accu_n ==
ntotal);
338 IndexIVF::~IndexIVF()
349 IndexIVFFlat::IndexIVFFlat (Index * quantizer,
351 IndexIVF (quantizer, d, nlist, metric)
367 const long *precomputed_idx)
372 "cannot have direct map and add with ids");
376 if (precomputed_idx) {
377 idx = precomputed_idx;
379 long * idx0 =
new long [n];
385 for (
size_t i = 0; i < n; i++) {
386 long id = xids ? xids[i] :
ntotal + i;
387 long list_no = idx [i];
390 assert (list_no <
nlist);
392 ids[list_no].push_back (
id);
393 const float *xi = x + i *
d;
395 size_t ofs = codes[list_no].size();
397 memcpy(codes[list_no].data() + ofs,
401 direct_map.push_back (list_no << 32 | (
ids[list_no].size() - 1));
405 printf(
"IndexIVFFlat::add_core: added %ld / %ld vectors\n",
411 void IndexIVFFlatStats::reset()
413 memset ((
void*)
this, 0,
sizeof (*
this));
417 IndexIVFFlatStats indexIVFFlat_stats;
421 void search_knn_inner_product (
const IndexIVFFlat & ivf,
425 float_minheap_array_t * res,
429 const size_t k = res->k;
430 size_t nlistv = 0, ndis = 0;
433 #pragma omp parallel for reduction(+: nlistv, ndis)
434 for (
size_t i = 0; i < nx; i++) {
435 const float * xi = x + i * d;
436 const long * keysi = keys + i * ivf.nprobe;
437 float * __restrict simi = res->get_val (i);
438 long * __restrict idxi = res->get_ids (i);
439 minheap_heapify (k, simi, idxi);
441 for (
size_t ik = 0; ik < ivf.nprobe; ik++) {
442 long key = keysi[ik];
447 FAISS_THROW_IF_NOT_FMT (
448 key < (
long) ivf.nlist,
449 "Invalid key=%ld at ik=%ld nlist=%ld\n",
453 const size_t list_size = ivf.ids[key].size();
454 const float * list_vecs = (
const float*)(ivf.codes[key].data());
456 for (
size_t j = 0; j < list_size; j++) {
457 const float * yj = list_vecs + d * j;
458 float ip = fvec_inner_product (xi, yj, d);
460 minheap_pop (k, simi, idxi);
461 long id = store_pairs ? (key << 32 | j) : ivf.ids[key][j];
462 minheap_push (k, simi, idxi, ip,
id);
467 minheap_reorder (k, simi, idxi);
469 indexIVFFlat_stats.nq += nx;
470 indexIVFFlat_stats.nlist += nlistv;
471 indexIVFFlat_stats.ndis += ndis;
475 void search_knn_L2sqr (
const IndexIVFFlat &ivf,
479 float_maxheap_array_t * res,
482 const size_t k = res->k;
483 size_t nlistv = 0, ndis = 0;
485 #pragma omp parallel for reduction(+: nlistv, ndis)
486 for (
size_t i = 0; i < nx; i++) {
487 const float * xi = x + i * d;
488 const long * keysi = keys + i * ivf.nprobe;
489 float * __restrict disi = res->get_val (i);
490 long * __restrict idxi = res->get_ids (i);
491 maxheap_heapify (k, disi, idxi);
493 for (
size_t ik = 0; ik < ivf.nprobe; ik++) {
494 long key = keysi[ik];
499 FAISS_THROW_IF_NOT_FMT (
500 key < (
long) ivf.nlist,
501 "Invalid key=%ld at ik=%ld nlist=%ld\n",
505 const size_t list_size = ivf.ids[key].size();
506 const float * list_vecs = (
const float*)(ivf.codes[key].data());
508 for (
size_t j = 0; j < list_size; j++) {
509 const float * yj = list_vecs + d * j;
511 if (disij < disi[0]) {
512 maxheap_pop (k, disi, idxi);
513 long id = store_pairs ? (key << 32 | j) : ivf.ids[key][j];
514 maxheap_push (k, disi, idxi, disij,
id);
519 maxheap_reorder (k, disi, idxi);
521 indexIVFFlat_stats.nq += nx;
522 indexIVFFlat_stats.nlist += nlistv;
523 indexIVFFlat_stats.ndis += ndis;
532 float *distances,
idx_t *labels,
533 bool store_pairs)
const
537 size_t(n), size_t(k), labels, distances};
538 search_knn_inner_product (*
this, n, x, idx, &res, store_pairs);
542 size_t(n), size_t(k), labels, distances};
543 search_knn_L2sqr (*
this, n, x, idx, &res, store_pairs);
559 for (
size_t i = 0; i < nx; i++) {
560 const float * xi = x + i *
d;
561 const long * keysi = keys + i *
nprobe;
566 for (
size_t ik = 0; ik <
nprobe; ik++) {
567 long key = keysi[ik];
568 if (key < 0 || key >= (
long)
nlist) {
569 fprintf (stderr,
"Invalid key=%ld at ik=%ld nlist=%ld\n",
574 const size_t list_size =
ids[key].size();
575 const float * list_vecs = (
const float *)(codes[key].data());
577 for (
size_t j = 0; j < list_size; j++) {
578 const float * yj = list_vecs + d * j;
581 if (disij < radius) {
582 qres.add (disij,
ids[key][j]);
585 float disij = fvec_inner_product(xi, yj, d);
586 if (disij > radius) {
587 qres.add (disij,
ids[key][j]);
602 std::vector<idx_t>
assign (n);
605 for (
int i = 0; i < n; i++) {
606 idx_t id = new_ids[i];
607 FAISS_THROW_IF_NOT_MSG (0 <=
id &&
id <
ntotal,
608 "id to update out of range");
610 long dm = direct_map[id];
611 long ofs = dm & 0xffffffff;
613 size_t l =
ids[il].size();
615 long id2 =
ids[il].back();
617 direct_map[id2] = (il << 32) | ofs;
618 float * vecs = (
float*)codes[il].data();
619 memcpy (vecs + ofs * d,
628 size_t l =
ids[il].size();
629 long dm = (il << 32) | l;
631 ids[il].push_back (
id);
633 float * vecs = (
float*)codes[il].data();
634 memcpy (vecs + l * d,
648 FAISS_THROW_IF_NOT_MSG (direct_map.size() ==
ntotal,
649 "direct map is not initialized");
650 int list_no = direct_map[key] >> 32;
651 int ofs = direct_map[key] & 0xffffffff;
652 memcpy (recons, &codes[list_no][ofs *
code_size], d *
sizeof(recons[0]));
virtual void search_preassigned(idx_t n, const float *x, idx_t k, const idx_t *assign, const float *centroid_dis, float *distances, idx_t *labels, bool store_pairs) const =0
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.
double imbalance_factor() const
1= perfectly balanced, >1: imbalanced
virtual void reset()=0
removes all elements from the database.
virtual void copy_subset_to(IndexIVF &other, int subset_type, long a1, long a2) const
char quantizer_trains_alone
size_t nprobe
number of probes at query time
virtual void train(idx_t, const float *)
void reconstruct(idx_t key, float *recons) const override
void assign(idx_t n, const float *x, idx_t *labels, idx_t k=1)
void range_search(idx_t n, const float *x, float radius, RangeSearchResult *result) const 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)
double imbalance_factor(int n, int k, const long *assign)
a balanced assignment has a IF of 1
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
Index * clustering_index
to override index used during clustering
virtual void add(idx_t n, const float *x)=0
bool own_fields
whether object owns the quantizer
long idx_t
all indices are this type
idx_t ntotal
total nb of indexed vectors
bool verbose
verbosity level
void reset() override
removes all elements from the database.
std::vector< float > centroids
centroids (k * d)
QueryResult & new_result(idx_t qno)
begin a new result
void update_vectors(int nv, idx_t *idx, const float *v)
virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const =0
the entries in the buffers are split per query
void make_direct_map(bool new_maintain_direct_map=true)
MetricType metric_type
type of metric this index uses for search
void print_stats() const
display some stats about the inverted lists
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
long remove_ids(const IDSelector &sel) override
Dataset manipulation functions.
bool maintain_direct_map
map for direct access to the elements. Enables reconstruct().
bool spherical
do we want normalized centroids?
virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const override
void search_preassigned(idx_t n, const float *x, idx_t k, const idx_t *assign, const float *centroid_dis, float *distances, idx_t *labels, bool store_pairs) const override
virtual void merge_from(IndexIVF &other, idx_t add_id)
size_t code_size
code size per vector in bytes
MetricType
Some algorithms support both an inner product version and a L2 search version.
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