Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #3379: Add tutorial for HNSW index #3381

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions tutorial/cpp/6-HNSW.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <random>

#include <faiss/IndexHNSW.h>

using idx_t = faiss::idx_t;

int main() {
int d = 64; // dimension
int nb = 100000; // database size
int nq = 10000; // nb of queries

std::mt19937 rng;
std::uniform_real_distribution<> distrib;

float* xb = new float[d * nb];
float* xq = new float[d * nq];

for (int i = 0; i < nb; i++) {
for (int j = 0; j < d; j++)
xb[d * i + j] = distrib(rng);
xb[d * i] += i / 1000.;
}

for (int i = 0; i < nq; i++) {
for (int j = 0; j < d; j++)
xq[d * i + j] = distrib(rng);
xq[d * i] += i / 1000.;
}

int nlist = 100;
int k = 4;

faiss::IndexHNSWFlat index(d, 32);
index.add(nb, xb);

{ // search xq
idx_t* I = new idx_t[k * nq];
float* D = new float[k * nq];

index.search(nq, xq, k, D, I);

printf("I=\n");
for (int i = nq - 5; i < nq; i++) {
for (int j = 0; j < k; j++)
printf("%5zd ", I[i * k + j]);
printf("\n");
}

index.search(nq, xq, k, D, I);

printf("I=\n");
for (int i = nq - 5; i < nq; i++) {
for (int j = 0; j < k; j++)
printf("%5zd ", I[i * k + j]);
printf("\n");
}

delete[] I;
delete[] D;
}

delete[] xb;
delete[] xq;

return 0;
}
3 changes: 3 additions & 0 deletions tutorial/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ target_link_libraries(4-GPU PRIVATE faiss)

add_executable(5-Multiple-GPUs EXCLUDE_FROM_ALL 5-Multiple-GPUs.cpp)
target_link_libraries(5-Multiple-GPUs PRIVATE faiss)

add_executable(6-HNSW EXCLUDE_FROM_ALL 6-HNSW.cpp)
target_link_libraries(6-HNSW PRIVATE faiss)