|
| 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/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[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 m = 8; |
| 41 | + int n_bit = 4; |
| 42 | + |
| 43 | + faiss::IndexPQFastScan index(d, m, n_bit); |
| 44 | + printf("Index is trained? %s\n", index.is_trained ? "true" : "false"); |
| 45 | + index.train(nb, xb); |
| 46 | + printf("Index is trained? %s\n", index.is_trained ? "true" : "false"); |
| 47 | + index.add(nb, xb); |
| 48 | + |
| 49 | + int k = 4; |
| 50 | + |
| 51 | + { // search xq |
| 52 | + idx_t* I = new idx_t[k * nq]; |
| 53 | + float* D = new float[k * nq]; |
| 54 | + |
| 55 | + index.search(nq, xq, k, D, I); |
| 56 | + |
| 57 | + printf("I=\n"); |
| 58 | + for (int i = nq - 5; i < nq; i++) { |
| 59 | + for (int j = 0; j < k; j++) |
| 60 | + printf("%5zd ", I[i * k + j]); |
| 61 | + printf("\n"); |
| 62 | + } |
| 63 | + |
| 64 | + delete[] I; |
| 65 | + delete[] D; |
| 66 | + } |
| 67 | + |
| 68 | + delete[] xb; |
| 69 | + delete[] xq; |
| 70 | + |
| 71 | + return 0; |
| 72 | +} // namespace facebook::detail |
0 commit comments