Skip to content
E
Educatum

When dealing with large-scale embeddings, propose and implement an efficient method for nearest neighbor search to quickly retrieve similar embeddings from a massive database.

Curated by Educatum AI teamLast updated:
Embeddings
Direct Answer

Large-scale nearest neighbor search over millions or billions of dense embeddings relies on Approximate Nearest Neighbor (ANN) algorithms such as Hierarchical Navigable Small World (HNSW) graphs, Inverted File with Product Quantization (IVF-PQ), and Locality-Sensitive Hashing (LSH) via libraries like Faiss or ScaNN. These methods trade a tiny drop in recall for sub-linear query latency and compressed RAM footprints, avoiding the O(N d) brute-force scan and the curse of dimensionality that cripples k-d trees above ~20–32 dimensions.

Study Card: Efficient Nearest Neighbor Search for Large-Scale Embeddings

Direct Answer

Exact nearest-neighbor search over NN vectors of dimension dd requires O(Nd)O(N d) operations per query, which becomes prohibitive when NN reaches millions or billions. Production retrieval systems (e.g., RAG, visual search, recommender retrieval) therefore rely on Approximate Nearest Neighbor (ANN) algorithms implemented in libraries such as Faiss, HNSWlib, or ScaNN:

  1. HNSW (Hierarchical Navigable Small World): Builds a multi-layer proximity graph where upper sparse layers enable rapid coarse jumps across the embedding space and lower dense layers refine exact local neighbors. HNSW delivers O(log⁡N)O(\log N) query time and high recall (>98%), though the graph metadata adds memory overhead.
  2. IVF-PQ (Inverted File + Product Quantization): Partitions the vector space via kk-means into nlist Voronoi cells (IVF), restricting search to the top nprobe closest centroids, while Product Quantization (PQ) compresses each vector into short quantized codebook bytes for fast cache-friendly Asymmetric Distance Computation and 16×16\times–64×64\times memory savings.
  3. LSH (Locality-Sensitive Hashing): Maps nearby points into identical buckets using random projections or hyperplanes with sub-linear lookup, though typically superseded in modern high-dimensional dense retrieval by HNSW and IVF-PQ.
  4. Why k-d Trees Fail at High Dimensions: Because of the curse of dimensionality, distances concentrate and hyper-rectangular space partitions intersect query hyperspheres across almost every branch once d≳32d \gtrsim 32, causing k-d tree backtracking to degrade to O(N)O(N) linear scans.

Key Terms

  • Approximate Nearest Neighbor (ANN): Retrieval algorithms trading negligible recall loss for orders-of-magnitude faster latency and lower memory.
  • HNSW: Multi-layered navigable graph algorithm offering top recall-vs-latency trade-offs for in-memory high-dimensional search.
  • IVF-PQ: Coarse clustering (IVF) combined with subspace codebook quantization (PQ) for billion-scale RAM-constrained search.
  • Recall@K: Fraction of true exact top-KK neighbors recovered by the ANN index, benchmarked against queries-per-second (QPS).
  • Curse of Dimensionality: Phenomenon where orthogonal space-partitioning trees (k-d trees, ball trees) lose pruning efficiency in high dimensions (d≥64d \ge 64).

Example

Consider retrieving top-10 candidate documents from 10M 768-D embeddings (float32 raw vectors alone require ~30.7 GB). A brute-force scan computes 10M 768-D inner products per query, taking tens to hundreds of milliseconds on CPU. Switching to IVF16384,PQ64 (with nprobe=32) compresses the database to ~640 MB and probes <0.2% of clusters, returning candidates in ~1–2 ms; or using HNSW (M=32) with optional int8 scalar quantization achieves >99% Recall@10 at sub-millisecond latency—followed by exact float32 rescoring of the top-100 ANN hits.

Code Implementation

import torch
import torch.nn.functional as F

torch.manual_seed(0)

# 1. Exact PyTorch batched cosine similarity search (fast on GPU for <= ~1M vectors)
num_embeddings, dimension = 10_000, 128
db_embeddings = F.normalize(torch.randn(num_embeddings, dimension), dim=-1)
query = F.normalize(torch.randn(1, dimension), dim=-1)

# Cosine similarity equals dot product on L2-normalized vectors
similarities = query @ db_embeddings.T  # (1, num_embeddings)
top_k = torch.topk(similarities, k=10, dim=-1)
top_indices = top_k.indices[0]
top_scores = top_k.values[0]
print("PyTorch Exact Top-5 indices:", top_indices[:5].tolist())
print("PyTorch Exact Top-5 cosine scores:", [round(x, 4) for x in top_scores[:5].tolist()])

# 2. Billion-scale ANN with Faiss (requires faiss-cpu / faiss-gpu)
# import faiss
# import numpy as np
# xb = db_embeddings.numpy().astype("float32")
# xq = query.numpy().astype("float32")
#
# # (a) HNSW Graph Index (high recall, fast in-memory search)
# index_hnsw = faiss.IndexHNSWFlat(dimension, 32)  # M=32 neighbors per node
# index_hnsw.hnsw.efSearch = 64
# index_hnsw.add(xb)
# D_hnsw, I_hnsw = index_hnsw.search(xq, k=10)
#
# # (b) IVF-PQ Index (note positional args: quantizer, d, nlist, m_subquantizers, nbits)
# nlist, m, nbits = 100, 8, 8
# quantizer = faiss.IndexFlatL2(dimension)
# index_pq = faiss.IndexIVFPQ(quantizer, dimension, nlist, m, nbits)
# index_pq.train(xb)
# index_pq.add(xb)
# index_pq.nprobe = 10  # Number of Voronoi cells probed at query time
# D_pq, I_pq = index_pq.search(xq, k=10)
  • DiskANN & Vamana Graphs: SSD-backed graph ANN architectures enabling billion-scale retrieval on single machines with minimal RAM.
  • Two-Stage Retrieval & Re-ranking: Fast ANN candidate generation (top-100) followed by exact cosine rescoring and cross-encoder re-ranking (top-10).
  • Vector Quantization (Scalar int8 / Binary): Complementary compression schemes commonly paired with HNSW or IVF.
  • ScaNN (Scalable Nearest Neighbors): Google’s anisotropic vector quantization algorithm optimizing inner-product recall for high-scoring candidates.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.