Skip to main content
Home › Categories › Artificial Intelligence & Computing › How Vector Embeddings and Approximate Nearest Neighbor (HNSW) Search Work Under the Hood

How Vector Embeddings and Approximate Nearest Neighbor (HNSW) Search Work Under the Hood

Author: ZUVDEX Team 4 min read
vector embeddings similarity search hnsw index algorithm explained cosine similarity vs dot product matryoshka embeddings dimension reduction binary scalar quantization vectors ivf pq vs hnsw vs diskann

Vector embeddings are dense fixed-length arrays of floating-point numbers generated by contrastive neural encoders so that semantically related texts, code snippets, or images land close together in high-dimensional geometric space. Because scanning 50 million 1,536-dimensional vectors brute-force on every query takes seconds of CPU math, production search engines build Approximate Nearest Neighbor (ANN) graph or cluster indexes—led by Hierarchical Navigable Small World (HNSW)—to find the top-k closest neighbors in single-digit milliseconds at 98%+ recall.

Key Highlights

  • Contrastive bi-encoders train on millions of positive and hard-negative pairs using InfoNCE loss, pulling synonymous meanings together on a unit hypersphere.
  • When embedding vectors are L2-normalized to unit length 1.0, Cosine Similarity and Inner (Dot) Product produce identical rankings—with dot product running faster on SIMD CPU/GPU instructions.
  • HNSW organizes vectors into a multi-layer skip-list proximity graph: upper layers take giant highway hops across vector space while lower layers refine exact local neighborhoods.
  • Combining Matryoshka Representation Learning (MRL) with 8-bit scalar or 1-bit binary quantization shrinks vector RAM footprints by 8× to 32× when paired with float rescoring.

1. How Contrastive Encoders Map Meaning Into Geometry

Unlike decoder LLMs that generate one word after another, text embedding models typically pool representations across bidirectional attention layers to emit a single vector per passage. During training with contrastive InfoNCE loss, the encoder sees an anchor query (‘how to reset Cloud Architecture for AI Workloads: Compute, Data, and Security secret’), a relevant positive passage, and dozens of subtle ‘hard negatives’ (passages mentioning Kubernetes Pods that do not explain Secrets). Gradient updates push the positive pair’s angle closer to 0° while pushing hard negatives toward orthogonal 90° angles.

Choosing a distance metric should always match how the embedding model was trained. Most modern text and multimodal encoders output L2-normalized vectors (`||v|| = 1`), where Cosine Similarity (`A·B / (||A|| ||B||)`) simplifies directly to pure Inner Product (`Σ A_i B_i`), saving square-root divisions inside tight AVX-512 or NEON SIMD loops.

2. Inside HNSW, IVF-PQ, and DiskANN Indexes

Exact k-Nearest Neighbor (`kNN`) search guarantees 100% recall by computing distances against every row in your table—great under 50,000 rows, unusable at 25 million rows. Approximate Nearest Neighbor (ANN) indexes trade 1–2% recall for 100×–1,000× speedups.

Hierarchical Navigable Small World (HNSW) works like an express-to-local transit system. Layer 3 holds only a sparse handful of landmark vectors with long-range edges; Layer 0 holds every vector in the dataset with `M` short-range neighbor links. At query time, greedy search zooms rapidly across the top sparse layer toward the right region, drops down layer by layer, and explores `ef_search` candidates at the bottom layer.

Comparison of Production Vector Index Algorithms
Index Type Query Latency RAM Footprint Recall@10 Ideal Workload
Flat / Exact Scan Slow O(N) (>200ms at 5M) 1× Raw Vectors 100% Exact <50K vectors or narrow tenant partitions
IVF-Flat / IVF-PQ 2–10 ms 0.1×–0.3× (Product Quantized) 90–96% Memory-constrained multi-million vector tables
HNSW (In-Memory) 1–5 ms O(log N) 1.3×–1.7× (Vectors + Graph Edges) 97–99.5% Gold standard for low-latency production RAG
DiskANN / Vamana 4–12 ms from NVMe SSD 0.15× RAM + NVMe SSD 95–98% 100M to 5B+ vectors where DRAM cost dominates

3. Cutting Vector Memory Costs by 16×: Matryoshka & Quantization

Ten million 1,536-dimensional FP32 vectors consume roughly 61.4 GB of raw memory—and closer to 95 GB once HNSW graph pointers are added. Two modern breakthroughs slash that infrastructure bill dramatically:

First, Matryoshka Representation Learning (MRL) applies nested loss functions at dimensions 128, 256, 512, 1024, and 1536 during training so early dimensions carry the coarsest, highest-variance semantic concepts. Truncating a Matryoshka vector from 1,536 down to 512 dimensions cuts memory by 3× while retaining ~98% retrieval accuracy. Second, Binary Quantization converts positive floats to `1` and negative floats to `0`, computing Hamming distances via single-cycle CPU `XOR + POPCNT` instructions to retrieve top-200 candidates in RAM before rescoring the top-20 against full-precision vectors on SSD.

FAQs

Can I upgrade my embedding model without re-embedding existing documents?

No. Every embedding model defines its own arbitrary coordinate rotation in high-dimensional space; comparing a query vector from Model B against document vectors from Model A produces meaningless noise. Always version your vector column or index alias for zero-downtime blue-green re-indexing.

What do HNSW hyperparameters M, ef_construction, and ef_search control?

`M` (typically 16–32) sets max bidirectional links per node, trading RAM for graph connectivity; `ef_construction` (64–200) controls index build quality at write time; and `ef_search` (40–128) tunes query-time recall vs latency dynamically without rebuilding the index.

Are higher-dimensional embeddings (e.g., 3072 dims) always better than 768 or 1024 dims?

Not necessarily. Benchmark results on MTEB show well-trained 768- or 1024-dimensional models often match or beat 3072-dimensional vectors on domain retrieval while costing 66% less RAM and indexing 3× faster.

Why does embedding a 10-page document into a single vector hurt search precision?

Compressing 5,000 words covering six distinct subtopics into one 1,024-float centroid averages all topics into a blurry middle ground, causing specific narrow queries to miss threshold similarity.

References & Sources

  • Malkov, Y. A.; Yashunin, D. A. — Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs (HNSW), IEEE TPAMI.
  • Kusupati, A. et al. — Matryoshka Representation Learning, Advances in Neural Information Processing Systems (NeurIPS).
  • Subramanya, S. J. et al. — DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node, NeurIPS.
  • Muennighoff, N. et al. — MTEB: Massive Text Embedding Benchmark, EACL.