| 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 |
# |
| 3 |
# This source code is licensed under the MIT license found in the |
| 4 |
# LICENSE file in the root directory of this source tree. |
| 5 |
|
| 6 |
import faiss |
| 7 |
import numpy as np |
| 8 |
|
| 9 |
d = 64 # dimension |
| 10 |
nb = 100000 # database size |
| 11 |
nq = 10000 # nb of queries |
| 12 |
np.random.seed(1234) # make reproducible |
| 13 |
xb = np.random.random((nb, d)).astype('float32') # 64-dim *nb queries |
| 14 |
xb[:, 0] += np.arange(nb) / 1000. |
| 15 |
xq = np.random.random((nq, d)).astype('float32') |
| 16 |
xq[:, 0] += np.arange(nq) / 1000. |
| 17 |
|
| 18 |
m = 8 # 8 specifies that the number of sub-vector is 8 |
| 19 |
k = 4 # number of dimension in extracted vector |
| 20 |
n_bit = 4 # 4 specifies that each sub-vector is encoded as 4 bits |
| 21 |
bbs = 32 # build block size ( bbs % 32 == 0 ) for PQ |
| 22 |
|
| 23 |
index = faiss.IndexPQFastScan(d, m, n_bit, faiss.METRIC_L2) |
| 24 |
index_refine = faiss.IndexRefineFlat(index) |
| 25 |
# construct FastScan and run index refinement |
| 26 |
|
| 27 |
assert not index_refine.is_trained |
| 28 |
index_refine.train(xb) # Train vectors data index within mockup database |
| 29 |
assert index_refine.is_trained |
| 30 |
|
| 31 |
index_refine.add(xb) |
| 32 |
params = faiss.IndexRefineSearchParameters(k_factor=3) |
| 33 |
D, I = index_refine.search(xq[:5], 10, params=params) |
| 34 |
print(I) |
| 35 |
print(D) |
| 36 |
index.nprobe = 10 # make comparable with experiment above |
| 37 |
D, I = index.search(xq[:5], k) # search |
| 38 |
print(I[-5:]) |