File: test_binary_flat.cpp

package info (click to toggle)
faiss 1.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,572 kB
  • sloc: cpp: 85,627; python: 27,889; sh: 905; ansic: 425; makefile: 41
file content (62 lines) | stat: -rw-r--r-- 1,639 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <cstdio>
#include <cstdlib>

#include <gtest/gtest.h>

#include <faiss/IndexBinaryFlat.h>
#include <faiss/utils/hamming.h>

TEST(BinaryFlat, accuracy) {
    // dimension of the vectors to index
    int d = 64;

    // size of the database we plan to index
    size_t nb = 1000;

    // make the index object and train it
    faiss::IndexBinaryFlat index(d);

    std::vector<uint8_t> database(nb * (d / 8));
    for (size_t i = 0; i < nb * (d / 8); i++) {
        database[i] = rand() % 0x100;
    }

    { // populating the database
        index.add(nb, database.data());
    }

    size_t nq = 200;

    { // searching the database

        std::vector<uint8_t> queries(nq * (d / 8));
        for (size_t i = 0; i < nq * (d / 8); i++) {
            queries[i] = rand() % 0x100;
        }

        int k = 5;
        std::vector<faiss::idx_t> nns(k * nq);
        std::vector<int> dis(k * nq);

        index.search(nq, queries.data(), k, dis.data(), nns.data());

        for (size_t i = 0; i < nq; ++i) {
            faiss::HammingComputer8 hc(queries.data() + i * (d / 8), d / 8);
            hamdis_t dist_min = hc.hamming(database.data());
            for (size_t j = 1; j < nb; ++j) {
                hamdis_t dist = hc.hamming(database.data() + j * (d / 8));
                if (dist < dist_min) {
                    dist_min = dist;
                }
            }
            EXPECT_EQ(dist_min, dis[k * i]);
        }
    }
}