大多數以嵌入向量為基礎的搜尋系統,會在大型集合中尋找數個接近指定向量的向量。Faiss 是 Meta 的近似最近鄰(ANN)搜尋函式庫。包括 txtai 和 Chroma 在內的許多搜尋引擎與向量資料庫都依賴這類函式庫。我安裝了 Faiss,並確認停用網路後最近鄰搜尋是否仍能運作。
Faiss 會在大型高維向量集合中搜尋最接近指定向量的項目。Meta 以 MIT 授權發布 Faiss (*1)。
1. 安裝 Faiss
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'faiss-cpu==1.14.3' 'numpy==2.5.1'
WORKDIR /work
我沒有使用嵌入模型等外部模型,因此這項測試不需要下載預先訓練的模型。
podman build -t faiss-sandbox .
2. 從三個群集中找出正確的近鄰
我在三個中心點各自的周圍產生 50 個 32 維向量,總共 150 個向量,然後使用接近其中一個群集的查詢向量進行搜尋。我在停用網路的情況下執行了測試。
import numpy as np
import faiss
rng = np.random.default_rng(0)
dim = 32
cluster_centers = rng.normal(0, 10, size=(3, dim))
vectors = np.vstack([
cluster_centers[i] + rng.normal(0, 0.5, size=(50, dim))
for i in range(3)
]).astype("float32")
labels = np.repeat([0, 1, 2], 50)
index = faiss.IndexFlatL2(dim)
index.add(vectors)
query = (cluster_centers[1] + rng.normal(0, 0.5, size=dim)).astype("float32").reshape(1, -1)
distances, indices = index.search(query, k=5)
print("nearest 5 neighbors' cluster labels:", labels[indices[0]].tolist())
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work faiss-sandbox \
python search_demo.py
-v 讓容器可以讀取及寫入指定的目錄。請在專供實驗使用的空目錄中執行。
Faiss 回傳了:
total vectors indexed: 150
nearest 5 neighbors' cluster labels: [1, 1, 1, 1, 1]
distances: [10.49, 11.06, 11.71, 11.72, 12.03]
在 150 個向量中,Faiss 選出的五個最近鄰全部來自正確的群集,也就是群集 1。結果中沒有出現其他兩個群集的向量。在這個規模下,NumPy 暴力掃描瞬間就能完成。接著我在更大規模下測量 Faiss。
3. 測量更大規模下的速度
針對 10,000、100,000 和 1,000,000 個 32 維向量,我比較了 IndexFlatL2(精確搜尋)與基本的 NumPy 暴力掃描每次查詢所需的時間。我在相同的 CPU 雙核心限制下,計算 100 次查詢的平均值。
index = faiss.IndexFlatL2(dim)
index.add(vectors)
t0 = time.perf_counter()
index.search(queries, k) # faiss
faiss_ms = (time.perf_counter() - t0) * 1000 / n_queries
for q in queries: # numpy brute force
d = ((vectors - q) ** 2).sum(axis=1)
np.argpartition(d, k)[:k]
本節使用第 2 節的指令搭配 bench_scale.py,下一節則搭配 bench_index_types.py。
vectors faiss (ms/query) numpy (ms/query)
10,000 0.305 1.175
100,000 1.395 11.308
1,000,000 13.732 205.562
使用 1,000,000 個向量時,Faiss 每次查詢花費 13.7 毫秒,NumPy 暴力掃描則花費 205.6 毫秒;即使是精確搜尋,兩者也相差約 15x。使用 10,000 個向量時,差距約為 4x,因此資料集越大,Faiss 就越有用。1,000,000 × 32 的 float32 陣列在記憶體中佔用 128 MB,而這項測試是在記憶體上限為 2 GB 的容器中完成的。
4. 測量近似索引在速度與召回率之間的取捨
除了精確搜尋,Faiss 也提供近似索引,以犧牲部分準確度換取速度。針對 100,000 個向量,我以精確搜尋的結果作為標準答案,測量 IVFFlat 和 HNSWFlat 的 recall@5,也就是前五個結果中符合標準答案的比例。
index type build ms/query recall@5
IndexFlatL2 (exact) 0.05s 1.582ms 100.0%
IVFFlat (nlist=100,nprobe=10) 5.35s 0.828ms 65.4%
HNSWFlat (M=32) 12.37s 0.072ms 63.6%
HNSW 的速度是精確搜尋的 22 倍,耗時 0.072ms;召回率降至 63.6%。IVFFlat 維持在 60% 的範圍。我使用沒有結構的均勻隨機向量,這是對近似索引最不利的輸入。實際的嵌入向量具有語意群集結構,因此召回率通常較高。我測量了這項取捨:近似索引以準確度為代價換取更快的速度,而代價取決於資料。HNSW 的建置耗時 12.37s,精確搜尋則為 0.05s。
一探搜尋引擎內部
使用 txtai 或 Chroma 等工具時,您很少看到內部運作。我單獨執行 Faiss,測量不同規模下的表現與準確度,並看到了搜尋引擎的兩項核心選擇:精確搜尋或近似搜尋,以及速度與召回率之間的平衡。單獨執行 Faiss 做一次測試,便能驗證較高階工具所抽象化的選擇。
來源
*1 Faiss (GitHub), https://github.com/facebookresearch/faiss, MIT License