SuperAPI AI 工具集

faiss

数据与分析

查看项目

更新于 10-21 16:17

技能介绍

用途

FAISS 是 Meta(Facebook)AI 研究团队开发的库,用于高效的稠密向量相似度搜索与聚类。它适用于以下场景:

  • 需要在大型向量数据集(百万/十亿级)上进行快速相似度搜索
  • 需要 GPU 加速
  • 只需要纯向量相似度(无需元数据过滤)
  • 高吞吐、低延迟至关重要
  • 对嵌入向量进行离线/批量处理

当需要元数据过滤时,可考虑 Chroma/Pinecone;需要完整数据库功能时,可考虑 Weaviate;追求更简单、功能更少时,可考虑 Annoy。

主要能力

  • 处理十亿级向量
  • C++ 编写,提供 Python 绑定
  • 支持多种索引类型:Flat(精确搜索)、IVF(倒排文件,快速近似)、HNSW(分层 NSW,质量/速度最佳)、Product Quantization(乘积量化,内存高效)
  • 支持 GPU 加速(单 GPU 与多 GPU)
  • 支持索引的保存与加载
  • 提供 LangChain 与 LlamaIndex 集成

使用方式

安装

# CPU only
pip install faiss-cpu

# GPU support
pip install faiss-gpu

基本用法

import faiss
import numpy as np

# Create sample data (1000 vectors, 128 dimensions)
d = 128
nb = 1000
vectors = np.random.random((nb, d)).astype('float32')

# Create index
index = faiss.IndexFlatL2(d)  # L2 distance
index.add(vectors)             # Add vectors

# Search
k = 5  # Find 5 nearest neighbors
query = np.random.random((1, d)).astype('float32')
distances, indices = index.search(query, k)

print(f"Nearest neighbors: {indices}")
print(f"Distances: {distances}")

索引类型

1. Flat(精确搜索)

# L2 (Euclidean) distance
index = faiss.IndexFlatL2(d)

# Inner product (cosine similarity if normalized)
index = faiss.IndexFlatIP(d)

# Slowest, most accurate

2. IVF(倒排文件)—— 快速近似

# Create quantizer
quantizer = faiss.IndexFlatL2(d)

# IVF index with 100 clusters
nlist = 100
index = faiss.IndexIVFFlat(quantizer, d, nlist)

# Train on data
index.train(vectors)

# Add vectors
index.add(vectors)

# Search (nprobe = clusters to search)
index.nprobe = 10
distances, indices = index.search(query, k)

3. HNSW(分层 NSW)—— 质量/速度最佳

# HNSW index
M = 32  # Number of connections per layer
index = faiss.IndexHNSWFlat(d, M)

# No training needed
index.add(vectors)

# Search
distances, indices = index.search(query, k)

4. Product Quantization —— 内存高效

# PQ reduces memory by 16-32×
m = 8   # Number of subquantizers
nbits = 8
index = faiss.IndexPQ(d, m, nbits)

# Train and add
index.train(vectors)
index.add(vectors)

保存与加载

# Save index
faiss.write_index(index, "large.index")

# Load index
index = faiss.read_index("large.index")

# Continue using
distances, indices = index.search(query, k)

GPU 加速

# Single GPU
res = faiss.StandardGpuResources()
index_cpu = faiss.IndexFlatL2(d)
index_gpu = faiss.index_cpu_to_gpu(res, 0, index_cpu)  # GPU 0

# Multi-GPU
index_gpu = faiss.index_cpu_to_all_gpus(index_cpu)

# 10-100× faster than CPU

LangChain 集成

from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings

# Create FAISS vector store
vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())

# Save
vectorstore.save_local("faiss_index")

# Load
vectorstore = FAISS.load_local(
    "faiss_index",
    OpenAIEmbeddings(),
    allow_dangerous_deserialization=True
)

# Search
results = vectorstore.similarity_search("query", k=5)

LlamaIndex 集成

from llama_index.vector_stores.faiss import FaissVectorStore
import faiss

# Create FAISS index
d = 1536
faiss_index = faiss.IndexFlatL2(d)

vector_store = FaissVectorStore(faiss_index=faiss_index)

适用场景与最佳实践

  • 选择合适的索引类型:小于 1 万用 Flat,1 万至 100 万用 IVF,追求质量用 HNSW
  • 余弦相似度需归一化:使用 IndexFlatIP 配合归一化向量
  • 大数据集使用 GPU:比 CPU 快 10-100 倍
  • 保存已训练的索引:训练开销较大
  • 调整 nprobe/ef_search:平衡速度与准确率
  • 监控内存:大数据集使用 PQ
  • 批量查询:更好地利用 GPU

性能参考

索引类型 构建时间 搜索时间 内存 准确率
Flat 快 慢 高 100%
IVF 中 快 中 95-99%
HNSW 慢 最快 高 99%
PQ 中 快 低 90-95%

限制与注意事项

  • 纯向量相似度搜索,不提供元数据过滤;需要元数据过滤时应改用 Chroma/Pinecone 等
  • 不提供完整数据库功能;需要时应改用 Weaviate 等
  • 版本相关的函数、标志或端点可能随安装版本变化,应以所安装版本的官方文档为准,不要臆造 API
  • 涉及花费金钱、占用共享 GPU 或云配额、触及个人或患者数据、或不可撤销的操作前应先征得同意

资源

  • GitHub:https://github.com/facebookresearch/faiss (⭐ 31,700+)
  • Wiki:https://github.com/facebookresearch/faiss/wiki
  • 许可证:MIT