Debian Codegraph @

tutorial/cpp/7-PQFastScan.cpp

raw
1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8 #include <cassert>
9 #include <cstdio>
10 #include <cstdlib>
11 #include <random>
12
13 #include <faiss/IndexPQFastScan.h>
14
15 using idx_t = faiss::idx_t;
16
17 int main() {
18 int d = 64; // dimension
19 int nb = 100000; // database size
20 int nq = 10000; // nb of queries
21
22 std::mt19937 rng;
23 std::uniform_real_distribution<> distrib;
24
25 float* xb = new float[(int)(d * nb)];
26 float* xq = new float[(int)(d * nq)];
27
28 for (int i = 0; i < nb; i++) {
29 for (int j = 0; j < d; j++) {
30 xb[d * i + j] = distrib(rng);
31 }
32 xb[d * i] += i / 1000.;
33 }
34
35 for (int i = 0; i < nq; i++) {
36 for (int j = 0; j < d; j++) {
37 xq[d * i + j] = distrib(rng);
38 }
39 xq[d * i] += i / 1000.;
40 }
41
42 int m = 8;
43 int n_bit = 4;
44
45 faiss::IndexPQFastScan index(d, m, n_bit);
46 printf("Index is trained? %s\n", index.is_trained ? "true" : "false");
47 index.train(nb, xb);
48 printf("Index is trained? %s\n", index.is_trained ? "true" : "false");
49 index.add(nb, xb);
50
51 int k = 4;
52
53 { // search xq
54 idx_t* I = new idx_t[(int)(k * nq)];
55 float* D = new float[(int)(k * nq)];
56
57 index.search(nq, xq, k, D, I);
58
59 printf("I=\n");
60 for (int i = nq - 5; i < nq; i++) {
61 for (int j = 0; j < k; j++) {
62 printf("%5zd ", I[i * k + j]);
63 }
64 printf("\n");
65 }
66
67 delete[] I;
68 delete[] D;
69 }
70
71 delete[] xb;
72 delete[] xq;
73
74 return 0;
75 }