| 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/IndexFlat.h> |
| 14 |
#include <faiss/IndexIVFFlat.h> |
| 15 |
|
| 16 |
using idx_t = faiss::idx_t; |
| 17 |
|
| 18 |
int main() { |
| 19 |
int d = 64; // dimension |
| 20 |
int nb = 100000; // database size |
| 21 |
int nq = 10000; // nb of queries |
| 22 |
|
| 23 |
std::mt19937 rng; |
| 24 |
std::uniform_real_distribution<> distrib; |
| 25 |
|
| 26 |
float* xb = new float[d * nb]; |
| 27 |
float* xq = new float[d * nq]; |
| 28 |
|
| 29 |
for (int i = 0; i < nb; i++) { |
| 30 |
for (int j = 0; j < d; j++) { |
| 31 |
xb[d * i + j] = distrib(rng); |
| 32 |
} |
| 33 |
xb[d * i] += i / 1000.; |
| 34 |
} |
| 35 |
|
| 36 |
for (int i = 0; i < nq; i++) { |
| 37 |
for (int j = 0; j < d; j++) { |
| 38 |
xq[d * i + j] = distrib(rng); |
| 39 |
} |
| 40 |
xq[d * i] += i / 1000.; |
| 41 |
} |
| 42 |
|
| 43 |
int nlist = 100; |
| 44 |
int k = 4; |
| 45 |
|
| 46 |
faiss::IndexFlatL2 quantizer(d); // the other index |
| 47 |
faiss::IndexIVFFlat index(&quantizer, d, nlist); |
| 48 |
assert(!index.is_trained); |
| 49 |
index.train(nb, xb); |
| 50 |
assert(index.is_trained); |
| 51 |
index.add(nb, xb); |
| 52 |
|
| 53 |
{ // search xq |
| 54 |
idx_t* I = new idx_t[k * nq]; |
| 55 |
float* D = new float[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 |
printf("D=\n"); |
| 68 |
for (int i = nq - 5; i < nq; i++) { |
| 69 |
for (int j = 0; j < k; j++) { |
| 70 |
printf("%5f ", D[i * k + j]); |
| 71 |
} |
| 72 |
printf("\n"); |
| 73 |
} |
| 74 |
|
| 75 |
delete[] I; |
| 76 |
delete[] D; |
| 77 |
} |
| 78 |
|
| 79 |
delete[] xb; |
| 80 |
delete[] xq; |
| 81 |
|
| 82 |
return 0; |
| 83 |
} |