Debian Codegraph @

tutorial/cpp/6-HNSW.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/IndexHNSW.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[d * nb];
26 float* xq = new float[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 k = 4;
43
44 faiss::IndexHNSWFlat index(d, 32);
45 index.add(nb, xb);
46
47 { // search xq
48 idx_t* I = new idx_t[k * nq];
49 float* D = new float[k * nq];
50
51 index.search(nq, xq, k, D, I);
52
53 printf("I=\n");
54 for (int i = nq - 5; i < nq; i++) {
55 for (int j = 0; j < k; j++) {
56 printf("%5zd ", I[i * k + j]);
57 }
58 printf("\n");
59 }
60
61 printf("D=\n");
62 for (int i = nq - 5; i < nq; i++) {
63 for (int j = 0; j < k; j++) {
64 printf("%5f ", D[i * k + j]);
65 }
66 printf("\n");
67 }
68
69 delete[] I;
70 delete[] D;
71 }
72
73 delete[] xb;
74 delete[] xq;
75
76 return 0;
77 }