Faiss

- Main Page
- Namespaces
- Classes
- Files

- File List

All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
demo_imi_pq.cpp
1 /**
2 * Copyright (c) 2015-present, Facebook, Inc.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD+Patents license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9 // Copyright 2004-present Facebook. All Rights Reserved
10
11
12 #include <cmath>
13 #include <cstdio>
14 #include <cstdlib>
15
16 #include <sys/time.h>
17
18
19 #include <faiss/IndexPQ.h>
20 #include <faiss/IndexIVFPQ.h>
21 #include <faiss/IndexFlat.h>
22 #include <faiss/index_io.h>
23
24 double elapsed ()
25 {
26 struct timeval tv;
27 gettimeofday (&tv, nullptr);
28 return tv.tv_sec + tv.tv_usec * 1e-6;
29 }
30
31
32 int main ()
33 {
34 double t0 = elapsed();
35
36 // dimension of the vectors to index
37 int d = 64;
38
39 // size of the database we plan to index
40 size_t nb = 1000 * 1000;
41 size_t add_bs = 10000; // # size of the blocks to add
42
43 // make a set of nt training vectors in the unit cube
44 // (could be the database)
45 size_t nt = 100 * 1000;
46
47 //---------------------------------------------------------------
48 // Define the core quantizer
49 // We choose a multiple inverted index for faster training with less data
50 // and because it usually offers best accuracy/speed trade-offs
51 //
52 // We here assume that its lifespan of this coarse quantizer will cover the
53 // lifespan of the inverted-file quantizer IndexIVFFlat below
54 // With dynamic allocation, one may give the responsability to free the
55 // quantizer to the inverted-file index (with attribute do_delete_quantizer)
56 //
57 // Note: a regular clustering algorithm would be defined as:
58 // faiss::IndexFlatL2 coarse_quantizer (d);
59 //
60 // Use nhash=2 subquantizers used to define the product coarse quantizer
61 // Number of bits: we will have 2^nbits_coarse centroids per subquantizer
62 // meaning (2^12)^nhash distinct inverted lists
63 //
64 // The parameter bytes_per_code is determined by the memory
65 // constraint, the dataset will use nb * (bytes_per_code + 8)
66 // bytes.
67 //
68 // The parameter nbits_subq is determined by the size of the dataset to index.
69 //
70 size_t nhash = 2;
71 size_t nbits_subq = 9;
72 size_t ncentroids = 1 << (nhash * nbits_subq); // total # of centroids
73 int bytes_per_code = 16;
74
75 faiss::MultiIndexQuantizer coarse_quantizer (d, nhash, nbits_subq);
76
77 printf ("IMI (%ld,%ld): %ld virtual centroids (target: %ld base vectors)",
78 nhash, nbits_subq, ncentroids, nb);
79
80 // the coarse quantizer should not be dealloced before the index
81 // 4 = nb of bytes per code (d must be a multiple of this)
82 // 8 = nb of bits per sub-code (almost always 8)
83 faiss::MetricType metric = faiss::METRIC_L2; // can be METRIC_INNER_PRODUCT
84 faiss::IndexIVFPQ index (&coarse_quantizer, d, ncentroids, bytes_per_code, 8);
85 index.quantizer_trains_alone = true;
86
87 // define the number of probes. 2048 is for high-dim, overkill in practice
88 // Use 4-1024 depending on the trade-off speed accuracy that you want
89 index.nprobe = 2048;
90
91
92 { // training.
93
94 // The distribution of the training vectors should be the same
95 // as the database vectors. It could be a sub-sample of the
96 // database vectors, if sampling is not biased. Here we just
97 // randomly generate the vectors.
98
99 printf ("[%.3f s] Generating %ld vectors in %dD for training\n",
100 elapsed() - t0, nt, d);
101
102 std::vector <float> trainvecs (nt * d);
103 for (size_t i = 0; i < nt; i++) {
104 for (size_t j = 0; j < d; j++) {
105 trainvecs[i * d + j] = drand48();
106 }
107 }
108
109 printf ("[%.3f s] Training the index\n", elapsed() - t0);
110 index.verbose = true;
111 index.train (nt, trainvecs.data());
112 }
113
114 // the index can be re-loaded later with
115 // faiss::Index * idx = faiss::read_index("/tmp/trained_index.faissindex");
116 faiss::write_index(&index, "/tmp/trained_index.faissindex");
117
118 size_t nq;
119 std::vector<float> queries;
120
121 { // populating the database
122 printf ("[%.3f s] Building a dataset of %ld vectors to index\n",
123 elapsed() - t0, nb);
124
125 std::vector <float> database (nb * d);
126 std::vector <long> ids (nb);
127 for (size_t i = 0; i < nb; i++) {
128 for (size_t j = 0; j < d; j++) {
129 database[i * d + j] = drand48();
130 }
131 ids[i] = 8760000000L + i;
132 }
133
134 printf ("[%.3f s] Adding the vectors to the index\n", elapsed() - t0);
135
136 for (size_t begin = 0; begin < nb; begin += add_bs) {
137 size_t end = std::min (begin + add_bs, nb);
138 index.add_with_ids (end - begin,
139 database.data() + d * begin,
140 ids.data() + begin);
141 }
142
143 // remember a few elements from the database as queries
144 int i0 = 1234;
145 int i1 = 1244;
146
147 nq = i1 - i0;
148 queries.resize (nq * d);
149 for (int i = i0; i < i1; i++) {
150 for (int j = 0; j < d; j++) {
151 queries [(i - i0) * d + j] = database [i * d + j];
152 }
153 }
154 }
155
156 // A few notes on the internal format of the index:
157 //
158 // - the positing lists for PQ codes are index.codes, which is a
159 // std::vector < std::vector<uint8_t> >
160 // if n is the length of posting list #i, codes[i] has length bytes_per_code * n
161 //
162 // - the corresponding ids are stored in index.ids
163 //
164 // - given a vector float *x, finding which k centroids are
165 // closest to it (ie to find the nearest neighbors) can be done with
166 //
167 // long *centroid_ids = new long[k];
168 // float *distances = new float[k];
169 // index.quantizer->search (1, x, k, dis, centroids_ids);
170 //
171
172 faiss::write_index(&index, "/tmp/populated_index.faissindex");
173
174 { // searching the database
175 int k = 5;
176 printf ("[%.3f s] Searching the %d nearest neighbors "
177 "of %ld vectors in the index\n",
178 elapsed() - t0, k, nq);
179
180 std::vector<faiss::Index::idx_t> nns (k * nq);
181 std::vector<float> dis (k * nq);
182
183 index.search (nq, queries.data(), k, dis.data(), nns.data());
184
185 printf ("[%.3f s] Query results (vector ids, then distances):\n",
186 elapsed() - t0);
187
188 for (int i = 0; i < nq; i++) {
189 printf ("query %2d: ", i);
190 for (int j = 0; j < k; j++) {
191 printf ("%7ld ", nns[j + i * k]);
192 }
193 printf ("\n dis: ");
194 for (int j = 0; j < k; j++) {
195 printf ("%7g ", dis[j + i * k]);
196 }
197 printf ("\n");
198 }
199 }
200 return 0;
201 }
faiss::IndexIVFPQ
Definition: IndexIVFPQ.h:29
faiss::MultiIndexQuantizer
Definition: IndexPQ.h:135
faiss::MetricType
MetricType
Some algorithms support both an inner product vetsion and a L2 search version.
Definition: Index.h:43