🤖 AI/ML

FAISS

Facebook AI Similarity Search

Meta's vector similarity search library. Fast approximate nearest neighbor search.

📖 Detailed Explanation

FAISS (Facebook AI Similarity Search) is a high-performance vector similarity search library developed by Meta AI Research. It can search billions of vectors in milliseconds, so it is used as core infrastructure for large-scale embedding-based search systems. It is written in C++, provides Python bindings, and supports both CPU and GPU.

FAISS was released as open source in 2017 and was developed at the time to solve Facebook's problem of searching over one billion images. With an implementation that is faster and more memory-efficient than existing ANN (Approximate Nearest Neighbor) libraries, it quickly became an industry standard. Today it is widely used as a vector store for RAG (Retrieval-Augmented Generation) systems.

The core principles are vector quantization and indexing. It clusters vectors with IVF (Inverted File Index) and compresses vectors with PQ (Product Quantization) to reduce memory usage. It also supports HNSW (Hierarchical Navigable Small World) graph-based indexes, so you can adjust the trade-off between search speed and accuracy.

In practice, FAISS is used for recommendation systems, semantic search, duplicate detection, image search, and more. LLM frameworks such as LangChain and LlamaIndex support FAISS as a default vector store. For 100,000 vectors or fewer, exact search with a Flat Index is recommended; beyond that, approximate search with IVF or HNSW is recommended.

💻 Code Example

import faiss
import numpy as np

# 1. 기본 사용법 - Flat Index (정확한 검색)
d = 128  # 벡터 차원
nb = 10000  # 데이터베이스 벡터 수
nq = 5  # 쿼리 수

# 랜덤 벡터 생성 (실제로는 임베딩 모델 출력 사용)
np.random.seed(42)
xb = np.random.random((nb, d)).astype('float32')
xq = np.random.random((nq, d)).astype('float32')

# L2 거리 기반 Flat Index
index = faiss.IndexFlatL2(d)
index.add(xb)  # 벡터 추가
print(f"인덱스 벡터 수: {index.ntotal}")

# 검색 (k=4 최근접 이웃)
k = 4
distances, indices = index.search(xq, k)
print(f"쿼리 0의 최근접 이웃: {indices[0]}")
print(f"거리: {distances[0]}")

# 2. IVF Index (대규모 데이터용 - 근사 검색)
nlist = 100  # 클러스터 수
quantizer = faiss.IndexFlatL2(d)
index_ivf = faiss.IndexIVFFlat(quantizer, d, nlist)

# IVF는 학습이 필요
index_ivf.train(xb)
index_ivf.add(xb)

# nprobe: 검색할 클러스터 수 (높을수록 정확, 느림)
index_ivf.nprobe = 10
distances, indices = index_ivf.search(xq, k)

# 3. GPU 사용 (CUDA 필요)
# res = faiss.StandardGpuResources()
# index_gpu = faiss.index_cpu_to_gpu(res, 0, index)

# 4. 인덱스 저장/로드
faiss.write_index(index, "my_index.faiss")
loaded_index = faiss.read_index("my_index.faiss")

# 5. LangChain과 함께 사용
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings

# texts = ["문서1 내용", "문서2 내용", ...]
# embeddings = OpenAIEmbeddings()
# vectorstore = FAISS.from_texts(texts, embeddings)
# results = vectorstore.similarity_search("검색 쿼리", k=3)

📊 Performance & Cost

This is a performance comparison by FAISS index type as of January 2025. (Open source, completely free)

Index Type Memory usage Query Speed Accuracy
Flat (L2/IP) d x 4 bytes/vector Slow (exhaustive search) 100% (exact)
IVF d x 4 bytes/vector Fast (adjust nprobe) 95%+ (approximate)
HNSW (d x 4 + M x 8) bytes Very fast 98%+ (approximate)
IVF-PQ 1/15 of Flat Fast 90%+ (approximate)

Recommended: Flat for 100,000 or fewer, IVF+HNSW for 1 million or fewer, and IVF-PQ for 100 million or more. HNSW accuracy 0.984, QPS 351. FAISS L2 achieves QPS 803.

🗣️ Say It Like This in Practice

In a RAG System Design Meeting

"We'll use FAISS as the vector store, and for 5 million records, an IVF-PQ combination seems good. Let's set nlist to about 2,000, which is sqrt(n), start PQ with 64 subquantizers, and tune while watching recall. About 4GB of memory should be enough."

In a Discussion with an Infrastructure Engineer

"The FAISS index is 2GB and the server has 8GB of memory, so that's fine, but loading the index takes 30 seconds on a cold start. For zero-downtime service, let's add a warm-up script that preloads the index, and handle index updates with blue-green deployment."

In an ML Engineer Technical Interview

"FAISS's IVF clusters vectors with k-means to narrow the search scope. The nprobe parameter controls the number of clusters to search; setting nprobe equal to nlist gives exact search but makes it slower. Usually you tune by raising nprobe until recall reaches 95% or higher."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Consider Data Scale When Choosing an Index Type

For 100,000 vectors or fewer, use a Flat Index for exact search; beyond that, use IVF or HNSW. For 100 million or more, you should save memory with an IVF-PQ combination. A wrong index choice can make search more than 1000 times slower.

2
Check Whether Vectors Are Normalized

To use cosine similarity, L2-normalize the vectors and then use an Inner Product (IP) index. IndexFlatIP gives the same results as cosine similarity on normalized vectors. Using IP without normalization produces unexpected results.

3
Always Call train() for IVF Indexes

IVF-family indexes must learn cluster centroids with train() before add(). At least nlist * 30 training vectors are recommended. Calling add() without train() causes an error, and insufficient training data degrades search quality.

🔗 Related Terms

📚 Learn More