Debian Codegraph @

tutorial/python/4-GPU.py

raw
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 numpy as np
7
8 d = 64 # dimension
9 nb = 100000 # database size
10 nq = 10000 # nb of queries
11 np.random.seed(1234) # make reproducible
12 xb = np.random.random((nb, d)).astype('float32')
13 xb[:, 0] += np.arange(nb) / 1000.
14 xq = np.random.random((nq, d)).astype('float32')
15 xq[:, 0] += np.arange(nq) / 1000.
16
17 import faiss # make faiss available
18
19 res = faiss.StandardGpuResources() # use a single GPU
20
21 ## Using a flat index
22
23 index_flat = faiss.IndexFlatL2(d) # build a flat (CPU) index
24
25 # make it a flat GPU index
26 gpu_index_flat = faiss.index_cpu_to_gpu(res, 0, index_flat)
27
28 gpu_index_flat.add(xb) # add vectors to the index
29 print(gpu_index_flat.ntotal)
30
31 k = 4 # we want to see 4 nearest neighbors
32 D, I = gpu_index_flat.search(xq, k) # actual search
33 print(I[:5]) # neighbors of the 5 first queries
34 print(I[-5:]) # neighbors of the 5 last queries
35
36
37 ## Using an IVF index
38
39 nlist = 100
40 quantizer = faiss.IndexFlatL2(d) # the other index
41 index_ivf = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
42 # here we specify METRIC_L2, by default it performs inner-product search
43
44 # make it an IVF GPU index
45 gpu_index_ivf = faiss.index_cpu_to_gpu(res, 0, index_ivf)
46
47 assert not gpu_index_ivf.is_trained
48 gpu_index_ivf.train(xb) # add vectors to the index
49 assert gpu_index_ivf.is_trained
50
51 gpu_index_ivf.add(xb) # add vectors to the index
52 print(gpu_index_ivf.ntotal)
53
54 k = 4 # we want to see 4 nearest neighbors
55 D, I = gpu_index_ivf.search(xq, k) # actual search
56 print(I[:5]) # neighbors of the 5 first queries
57 print(I[-5:]) # neighbors of the 5 last queries