Chapter 21 of 40 · ~22 min read & lab+80 XP
Chapter 21 · Generative AI

Vector Search at Scale: HNSW Graphs, IVF-PQ & Semantic Caching

How vector databases search 100M+ embeddings in <10 ms via HNSW multi-layer skip-list graphs, how IVF-PQ compresses RAM by 64×, and how Semantic Caching cuts LLM latency & API bills by 50%+.

What Is It?

Vector Databases accelerate nearest-neighbor search over millions of embeddings using Approximate Nearest Neighbor indexes (HNSW graphs, IVF-PQ) and Semantic Caching.

Why Is It Required?

Brute-force scanning 50 million embeddings takes seconds per query; HNSW retrieves top-K matches in ~5ms, and semantic caches skip redundant LLM calls entirely.

Everyday Analogy: Using express highways (HNSW top layers) to jump near your destination city before taking local streets to the exact house.
Why ML Engineers & Data Scientists Actually Need This

Every vector database (pgvector, Qdrant, Pinecone, Milvus, FAISS) runs HNSW or IVF-PQ under the hood — knowing their 3 tuning knobs saves thousands of dollars in RAM and latency!

ML / AI Engineer

Tuning efSearch at query time lets you dial Recall@10 from 92% to 99% on the fly, while adding a Semantic Cache before your LLM can cut repeat FAQ spend by 40%–70%!

Data Scientist

Understanding why τ = 0.82 causes catastrophic Semantic Cache False Hits ('reset password' vs. 'delete account') keeps user-facing AI safe.

Interview & Debug Edge

Classic systems design question: 'How does HNSW achieve O(log N) search, how much RAM does 10M 1536-d vectors need, and how would you add Semantic Caching?'

Step 0 · Test Your Gut Before Any Math!

In a Semantic Cache for a customer support bot, you lower the cosine hit threshold from τ = 0.94 down to τ = 0.80 to get more cache hits. What is the biggest risk?

What You Will Master in This Chapter
  • Explain why exact brute-force O(N·d) search breaks at millions of vectors and how ANN trades 1% recall for 100× speedup
  • Trace HNSW multi-layer navigation and tune its 3 key knobs: M (edges/node), efConstruction, and efSearch
  • Contrast HNSW (fast, RAM-heavy) with IVF-PQ (disk/RAM-compact, 64× compression via sub-vector centroids)
  • Design a Semantic Cache with threshold τ (0.92–0.96) and explain the False-Hit danger when τ is set too low
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
M,efSearchM, \text{efSearch}Say aloud:“HNSW graph degree & search beam”
Plain-English Meaning
M = max edges per node (RAM vs. graph quality); efSearch = candidate beam width at query time (Recall vs. Latency)
Everyday Example
M=16–32, efSearch=64–128
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of HNSW like flying from New York to a café in Tokyo: Layer 2 is an international airport (1 giant hop across the ocean), Layer 1 is the bullet train (zooming into the right district), and Layer 0 is walking down the street to the exact café door! You reach the exact destination in O(log⁡N)O(\log N) hops without ever visiting every building on Earth!

1. HNSW: Hierarchical Navigable Small World Graphs

Everyday Story First (Zero Math Yet!)

Trace the dashed red path below: HNSW enters at the sparse top expressway layer, greedily jumps closer, and drops down to Layer 0 for local refinement.

HNSW Multi-Layer Small-World Graph: O(log N) Approximate Nearest NeighborsLayer 2 (Expressway)Layer 1 (Regional)Layer 0 (All Docs)Greedy descent: enter Layer 2 → jump close to target → refine locally in Layer 0 (efSearch controls recall/latency!)
HNSW organizes vectors into a multi-layer skip-list graph: top layers take giant highway jumps across the space, while Layer 0 performs fine-grained local neighborhood search in O(log N)!

The 3 Knobs Every Vector DB Exposes

  • M (16–64): Max bi-directional edges per node. Higher M → better recall on high-dim vectors, more RAM & slower index build.
  • efConstruction (100–400): Search width during index building. Higher = cleaner graph (build-time cost only!).
  • efSearch (32–256): Dynamic query-time beam width. Raise efSearch to push Recall@10 from 94% → 99% without rebuilding the index!

2. Scaling to Billions: IVF Clustering + Product Quantization (PQ)

Everyday Story First (Zero Math Yet!)

HNSW holds full vectors + graph links in RAM (~80 GB for 10M 1536-d FP32 vectors). When RAM runs out, IVF-PQ compresses vectors by 32×–64×!

Billion-Scale Vector Search: IVF Clustering + Product Quantization (PQ)IVF (Inverted File Index)• K-Means partitions vectors into nlist Voronoi cells• Query scans ONLY top nprobe closest cells• Skips 95%+ of the dataset per query!PQ (Product Quantization)• Slices 1536-d FP32 (6,144 B) into M=96 sub-vectors• Replaces each slice with 1-byte centroid ID (0..255)• 6,144 B → 96 B = 64× RAM compression!
IVF partitions vectors into K Voronoi clusters (searching only nprobe nearby cells), while Product Quantization (PQ) compresses each sub-vector into a 1-byte centroid ID (32×–64× RAM savings!).

How Product Quantization Achieves 64× Compression

  1. Split a 1536-d FP32 vector (6,144 bytes) into M=96M = 96 sub-vectors of 16 dims each.
  2. Run K-Means (K=256K = 256 centroids → fits in 1 byte!) on each slice.
  3. Replace each slice with its 1-byte centroid ID → 96 bytes total (64× smaller!).
  4. Pro Tip (Two-Step Rescore): Search PQ codes to fetch Top-100 fast, then rescore Top-100 using exact FP16/FP32 vectors from disk/NVMe (DiskANN / Qdrant oversampling) for ~99% recall!

3. Semantic Caching: Turning Repeat Queries into 15 ms Hits

Everyday Story First (Zero Math Yet!)

Slide threshold τ in the mini-lab below to see the exact razor's edge between catching valid paraphrases and triggering dangerous False Hits!

Semantic Cache Architecture: Instant 15 ms Hits at Zero LLM CostUser QueryEmbed → q̂Cache Vector Lookupmax cos(q̂, c_i) ≥ τ ?HIT (≥ 0.94): Return cached (~15 ms, $0)MISS: Call LLM → Store (q̂, ans)
Semantic Caching embeds incoming queries and checks a high-similarity threshold (τ ≈ 0.92–0.96): cache hits return in ~15 ms at $0 LLM token cost!

Production Semantic Cache Best Practices

  • Threshold τ∈[0.92,0.96]\tau \in [0.92, 0.96]: High enough to block 'reset password' vs. 'delete account'.
  • TTL + Invalidation: Always attach a Time-To-Live (e.g., 24h) and invalidate when underlying RAG docs update.
  • Scope by Metadata: Partition cache by (tenant_id, model_version, prompt_version) so private answers never leak across users!
Walk Through With Me · Interactive Worked Example

Worked Example: Estimating HNSW RAM for 1 Million 1536-d Vectors

1,000,000 documents, 1536-dim FP32 (4 bytes/float), HNSW M = 16.

11. Raw vector memoryStep 1 / 2

106×1536×4 bytes≈6.14 GB10^6 \times 1536 \times 4\text{ bytes} \approx \mathbf{6.14\text{ GB}}.

Teacher's Note: Switching to FP16/INT8 immediately halves/quarters this!
Animated Mini-Lab • 4.2

Semantic Cache Threshold τ Tuner

How do I reset my password?sim=0.96 → CACHE HIT ✓
Steps to change my login passwordsim=0.93 → CACHE HIT ✓
How do I delete my account?sim=0.84 → MISS → LLM
Pause & Check · Quick Intuition Pulse

Which HNSW parameter can you increase AT QUERY TIME (without rebuilding the index) to trade slightly higher latency for higher Recall@10?

Try It YourselfStandard

In pgvector or Qdrant, your HNSW recall dropped when you added a strict WHERE category = 'legal' SQL filter (pre-filtering vs. post-filtering). Why?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

No! Below ~50,000 vectors, exact brute-force dot product (IndexFlatIP) takes <2 ms, gives 100% exact recall, and has zero index-build or graph-RAM overhead!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Multi-Layer HNSW Graph Descent Animator hop from Layer 2 down to Layer 0.
Interactive Animation • 4.2 Deep Lab

Multi-Layer HNSW Graph Descent Animator (O(log N) Search)

Watch greedy beam search start on sparse highway Layer 2 and zoom straight into the target neighborhood in Layer 0.

Layer 2 · Hop 1/6
L2L1L0
Enter sparse expressway node #1
0%
Enter sparse expressway node #1
Intuition Takeaway: HNSW delivers O(log⁡N)O(\log N) millisecond vector search via multi-layer skip-list graphs, IVF-PQ compresses billion-scale indexes by 64×, and strict-threshold Semantic Caching (τ≈0.94\tau \approx 0.94) slashes repeat LLM costs.
Where This Powers Real ML, Deep Learning & Generative AI

pgvector / Qdrant / Milvus Production RAG

HNSW + scalar INT8 quantization gives 4× RAM reduction with <0.5% recall loss.

Enterprise Support Semantic Cache

Intercepts 40%–65% of high-frequency queries in ~15 ms before touching expensive frontier LLMs.

Production NumPy & PyTorch Code Patterns
import torch
import torch.nn.functional as F

# Semantic Cache: Skip Expensive LLM Generation When Cosine Similarity >= Threshold
class SemanticCache:
    def __init__(self, threshold: float = 0.92):
        self.threshold = threshold
        self.keys: list[torch.Tensor] = []
        self.values: list[str] = []

    def put(self, emb: torch.Tensor, response: str):
        self.keys.append(F.normalize(emb, dim=-1))
        self.values.append(response)

    def get(self, query_emb: torch.Tensor) -> str | None:
        if not self.keys:
            return None
        q = F.normalize(query_emb, dim=-1)
        sims = torch.stack(self.keys) @ q
        best_sim, idx = sims.max(dim=0)
        return self.values[idx.item()] if best_sim.item() >= self.threshold else None

cache = SemanticCache(threshold=0.92)
e1 = torch.randn(32)
cache.put(e1, "Cached answer: FlashAttention tiles Q, K, V in GPU SRAM.")
print("Cache hit:", cache.get(e1 + 0.05 * torch.randn(32)))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Caching personalized or time-sensitive queries ('What is my order status?') in a global Semantic Cache.
Best Practice: Only semantically cache stateless/public knowledge queries, or strictly scope by (user_id, entity_id, TTL)!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1When is exact brute-force cosine search (IndexFlatIP) preferable to building an HNSW index?

Apply What You Learned — Solve Matching Coding Problems