Skip to content

Commit dfb78df

Browse files
JayjeetAtGithubaalekhpatel07
authored andcommitted
Fix facebookresearch#3379: Add tutorial for HNSW index (facebookresearch#3381)
Summary: Fixes facebookresearch#3379 Pull Request resolved: facebookresearch#3381 Reviewed By: junjieqi Differential Revision: D56570120 Pulled By: kuarora fbshipit-source-id: 758ea4ab866609d6dd5621e6e6ffda583ba52503
1 parent a919915 commit dfb78df

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

tutorial/cpp/6-HNSW.cpp

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its 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+
xb[d * i] += i / 1000.;
32+
}
33+
34+
for (int i = 0; i < nq; i++) {
35+
for (int j = 0; j < d; j++)
36+
xq[d * i + j] = distrib(rng);
37+
xq[d * i] += i / 1000.;
38+
}
39+
40+
int nlist = 100;
41+
int k = 4;
42+
43+
faiss::IndexHNSWFlat index(d, 32);
44+
index.add(nb, xb);
45+
46+
{ // search xq
47+
idx_t* I = new idx_t[k * nq];
48+
float* D = new float[k * nq];
49+
50+
index.search(nq, xq, k, D, I);
51+
52+
printf("I=\n");
53+
for (int i = nq - 5; i < nq; i++) {
54+
for (int j = 0; j < k; j++)
55+
printf("%5zd ", I[i * k + j]);
56+
printf("\n");
57+
}
58+
59+
index.search(nq, xq, k, D, I);
60+
61+
printf("I=\n");
62+
for (int i = nq - 5; i < nq; i++) {
63+
for (int j = 0; j < k; j++)
64+
printf("%5zd ", I[i * k + j]);
65+
printf("\n");
66+
}
67+
68+
delete[] I;
69+
delete[] D;
70+
}
71+
72+
delete[] xb;
73+
delete[] xq;
74+
75+
return 0;
76+
}

tutorial/cpp/CMakeLists.txt

+3
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,6 @@ target_link_libraries(4-GPU PRIVATE faiss)
1818

1919
add_executable(5-Multiple-GPUs EXCLUDE_FROM_ALL 5-Multiple-GPUs.cpp)
2020
target_link_libraries(5-Multiple-GPUs PRIVATE faiss)
21+
22+
add_executable(6-HNSW EXCLUDE_FROM_ALL 6-HNSW.cpp)
23+
target_link_libraries(6-HNSW PRIVATE faiss)

0 commit comments

Comments
 (0)