🤖 AI/ML

ANN

Approximate Nearest Neighbor

Approximate nearest neighbor search. Sacrifices a little accuracy for speed.

📖 Detailed Explanation

ANN (Approximate Nearest Neighbor) is an algorithm that quickly finds the vectors most similar to a given query in a high-dimensional vector space. Exact nearest neighbor (Exact NN) search must compare against all data, but ANN slightly sacrifices accuracy in exchange for improving search speed by tens to hundreds of times.

The need for ANN has surged with the rise of LLMs and RAG systems. OpenAI's text-embedding-ada-002 generates 1536-dimensional vectors, and Cohere's embed-multilingual-v3.0 generates 1024-dimensional vectors. To find similar documents within milliseconds among hundreds of millions of document embeddings, ANN (O(log n)) is essential instead of brute force (O(n)).

Major ANN algorithms include HNSW (Hierarchical Navigable Small World), IVF (Inverted File Index), and PQ (Product Quantization). HNSW is graph-based and provides high accuracy and fast search speed, while IVF-PQ is memory-efficient. Various libraries such as Faiss, Annoy, ScaNN, and Milvus implement these algorithms.

In practice, ANN is the core engine of vector databases (Pinecone, Weaviate, Qdrant). Search accuracy is measured by recall@k, and latency and throughput must be optimized together. Typically, a recall@10 of 95% or higher is considered production quality, with a target of p99 latency of 10ms or less.

💻 Code Example

"""
ANN(Approximate Nearest Neighbor) 검색 예제
FAISS 라이브러리를 사용한 HNSW 인덱스 구축 및 검색
"""

import numpy as np
import faiss
import time

# 랜덤 시드 고정
np.random.seed(42)

# 파라미터 설정
dimension = 768      # 임베딩 차원 (BERT 기준)
num_vectors = 100000 # 인덱싱할 벡터 수
num_queries = 100    # 쿼리 수
top_k = 10           # 반환할 이웃 수

# 샘플 데이터 생성 (실제로는 임베딩 모델 출력 사용)
print("벡터 데이터 생성 중...")
database_vectors = np.random.random((num_vectors, dimension)).astype('float32')
query_vectors = np.random.random((num_queries, dimension)).astype('float32')

# L2 정규화 (코사인 유사도 사용시 필수)
faiss.normalize_L2(database_vectors)
faiss.normalize_L2(query_vectors)

# 1. Exact Search (브루트포스) - 비교 기준
print("\n=== Exact Search (Flat Index) ===")
index_flat = faiss.IndexFlatIP(dimension)  # Inner Product = Cosine Similarity (정규화 후)
index_flat.add(database_vectors)

start = time.time()
distances_exact, indices_exact = index_flat.search(query_vectors, top_k)
exact_time = time.time() - start
print(f"검색 시간: {exact_time*1000:.2f}ms ({num_queries}개 쿼리)")

# 2. ANN Search (HNSW) - 근사 검색
print("\n=== ANN Search (HNSW Index) ===")
# HNSW 파라미터: M=32 (그래프 연결 수), efConstruction=40 (인덱스 빌드 품질)
M = 32
index_hnsw = faiss.IndexHNSWFlat(dimension, M)
index_hnsw.hnsw.efConstruction = 40  # 인덱스 빌드 품질

# 인덱스 구축
build_start = time.time()
index_hnsw.add(database_vectors)
build_time = time.time() - build_start
print(f"인덱스 빌드 시간: {build_time:.2f}s")

# efSearch 조절로 정확도-속도 트레이드오프 조절
index_hnsw.hnsw.efSearch = 64  # 검색 품질 (높을수록 정확, 느림)

start = time.time()
distances_ann, indices_ann = index_hnsw.search(query_vectors, top_k)
ann_time = time.time() - start
print(f"검색 시간: {ann_time*1000:.2f}ms ({num_queries}개 쿼리)")

# 3. Recall 계산 (정확도 측정)
def calculate_recall(exact_indices, ann_indices, k):
    """Recall@k: ANN 결과에 Exact 결과가 얼마나 포함되었는지"""
    recall_sum = 0
    for i in range(len(exact_indices)):
        exact_set = set(exact_indices[i][:k])
        ann_set = set(ann_indices[i][:k])
        recall_sum += len(exact_set & ann_set) / k
    return recall_sum / len(exact_indices)

recall = calculate_recall(indices_exact, indices_ann, top_k)
speedup = exact_time / ann_time

print(f"\n=== 성능 비교 ===")
print(f"Recall@{top_k}: {recall:.2%}")
print(f"속도 향상: {speedup:.1f}x")
print(f"메모리 사용: {index_hnsw.ntotal * dimension * 4 / 1024 / 1024:.1f}MB")

🗣️ Examples of Practical Conversations

In a RAG system architecture design meeting

"We need to index 10 million documents, but Exact KNN takes 500ms per query. Switching to HNSW-based ANN lets us keep recall at 98% while cutting latency to 5ms or less. Using a managed vector DB like Pinecone or Weaviate would also reduce the operational burden."

In an ML engineer interview

"Choosing an ANN algorithm depends on the workload. If search is the main task and the data doesn't change often, HNSW is a good choice; if there are many real-time updates, IVF-PQ is better. You can compare performance on real datasets at ann-benchmarks.com."

In a system optimization review

"Our current recall is 85%, so we have a search quality issue. Raising HNSW's efSearch from 64 to 128 improves recall to 95%, but latency doubles. Let's also consider a hybrid search approach that retrieves ANN results and then reranks them."

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

⚠️ Cautions

⚠️
The Recall vs. Latency Tradeoff

Increasing parameters such as efSearch or nprobe raises accuracy but slows down search. You need to find the optimal point for your workload, and benchmarking before production is essential.

⚠️
Index Rebuild Cost

HNSW indexes take a long time to build, and deleting vectors is difficult. If you have many real-time updates, consider IVF-family indexes or solutions that support incremental indexing.

⚠️
Memory Usage Planning

HNSW keeps a graph structure in memory in addition to the vectors themselves. 100 million 768-dimensional vectors may require about 300GB of memory. Compressing with PQ (Product Quantization) can reduce this by more than 10x.

🔗 Related Terms

📚 Learn More