1. Faiss簡介
Faiss是Facebook開源的一款用于大規模P維向量最近鄰檢索的工具。
Faiss is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and parameter tuning. Faiss is written in C++ with complete wrappers for Python/numpy. Some of the most useful algorithms are implemented on the GPU. It is developed by Facebook AI Research.
他底層采用C ++編寫,并且提供了python的封裝代碼。主要功能是,對于一個給定的向量,在所有已知的向量庫中找出與其相似度較高的向量,即該向量的前k個最近鄰向量。
尤其是隨著萬物皆可Embedding時代的到來,Faiss越來越受到人們關注。
2. Faiss安裝
可以pip安裝
pip install faiss-cpu --no-cache
也可以采用conda安裝
#CPU 版本
conda install faiss-cpu -c pytorch
# GPU 版本
conda install faiss-gpu cudatoolkit=8.0 -c pytorch # For CUDA8
conda install faiss-gpu cudatoolkit=9.0 -c pytorch # For CUDA9
conda install faiss-gpu cudatoolkit=10.0 -c pytorch # For CUDA10
3. Faiss Action
faiss的使用方法也比較簡單,歸納為以下三個步驟:
- 構建向量庫,對已知的數據進行向量,最終以矩陣的形式表示
- 為矩陣選擇合適的index,將第一步得到的矩陣add到index中
- search得到最終結果
以IndexFlatL2為例,看一下faiss的用法:
import numpy as np
import faiss
d = 64
nb = 100000
nq = 10000
# 構建向量庫
xb = np.random.random((nb, d)).astype('float32')
xb[:, 0] += np.arange(nb) / 1000.
xq = np.random.random((nq, d)).astype('float32')
xq[:, 0] += np.arange(nq) / 1000.
# 關鍵步驟,build index
index = faiss.IndexFlatL2(d)
index.add(xb)
k = 4
D, I = index.search(xq[:5], k) # 分別返回距離和索引