大多数基于 embedding 向量的搜索系统,都会在一个大型集合中查找多个与给定向量接近的向量。Faiss 是 Meta 用于近似最近邻(ANN)搜索的库。包括 txtai 和 Chroma 在内的许多搜索引擎和向量数据库,都依赖这类库。我安装了 Faiss,并在禁用网络的情况下确认最近邻搜索能够正常工作。
Faiss 会在大型高维向量集合中搜索与指定向量最接近的向量。Meta 以 MIT License 发布 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
我没有使用 embedding 模型之类的外部模型,因此这次测试不需要下载预训练模型。
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 找到的 5 个最近邻全部来自正确的簇,也就是簇 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 毫秒;即使是精确搜索,两者也相差约 15 倍。在 10,000 个向量时,差距约为 4 倍,因此数据集越大,Faiss 越有用。一个 1,000,000 × 32 的 float32 数组占用 128 MB 内存,这次测试在内存上限为 2 GB 的容器中完成。
4. 测量近似索引在速度和召回率之间的取舍
除了精确搜索,Faiss 还提供了近似索引,用少量准确性换取速度。对于 100,000 个向量,我将精确搜索结果视为真实结果,并测量了 IVFFlat 和 HNSWFlat 的 recall@5,即前 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 每次查询耗时 0.072ms,速度是精确搜索的 22 倍;召回率则降到了 63.6%。IVFFlat 的召回率保持在 60% 左右。我使用的是没有任何结构的均匀随机向量,这是对近似索引最不利的输入。真实 embedding 向量通常具有语义簇结构,因此召回率往往更高。我测量到的取舍是:近似索引以牺牲准确性为代价换来更高速度,而代价大小取决于数据。HNSW 的构建耗时为 12.37s,精确搜索则为 0.05s。
一窥搜索引擎内部
使用 txtai 或 Chroma 这类工具时,你几乎看不到内部具体做了什么。我单独运行 Faiss,测量了它在不同规模下的表现和准确性,并看到了搜索引擎的两个核心选择:精确搜索还是近似搜索,以及如何在速度和召回率之间取得平衡。单独运行 Faiss 做一次测试,就能验证高级工具替你抽象掉的这些选择。
来源
*1 Faiss (GitHub), https://github.com/facebookresearch/faiss, MIT License