Week 10 • Day 1Week 10
Day 1:Week 10, Day 1: Exact Flat `kNN`, RAM/Bandwidth Math & The Curse of Dimensionality
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Week 10, Day 1: Exact Flat kNN, RAM/Bandwidth Math & The Curse of Dimensionality
1. Why Brute-Force Exact kNN (IndexFlatIP) Breaks at Scale
In Exact kNN (Flat Index), every query vector must be compared against all vectors in the corpus:
- Time Complexity: floating-point operations per query.
- Memory Footprint Formula (Raw
FP32):
Concrete Back-of-the-Envelope Capacity Math
Suppose chunks and (OpenAI text-embedding-3-small):
Because CPU DDR5 memory bandwidth is ~60 GB/s, scanning 61.44 GB of vectors from RAM for a single user query takes ~1,000 ms (1 full second)—meaning a 64-core server can only handle 1 query per second (1 QPS)!
2. The Curse of Dimensionality in High-Dimensional Spaces
In low dimensions ( or ), space is cozy and spatial trees (KD-Trees) easily prune branches.
As dimension (e.g., ), two counter-intuitive mathematical phenomena occur for uniform/Gaussian random points:
- Concentration of Measure: The ratio between the distance to the farthest point and the distance to the nearest point converges to $1$:
- Near-Orthogonality of Random Vectors: Two random unit vectors in have expected dot product $0\frac{1}{\sqrt{D}}D = 1536\frac{1}{\sqrt{1536}} \approx 0.0255—almost all random vectors are nearly \90^\circ$ orthogonal to each other!
Fortunately, real text embeddings lie on a lower-dimensional semantic manifold, which enables Approximate Nearest Neighbor (
ANN) indexes (IVFandHNSW) to search in sub-linear time!
In Simple English: Why Searching 10 Million Vectors Needs Smart Indexes
Look at the memory formula: :
- Suppose documents, each stored as decimal numbers (
float32= 4 bytes each). - Size: $10^7 \times 1,536 \times 4 \approx \mathbf{61.4\text{ GB of pure RAM}}$ just to hold raw vectors!
- Speed Problem (
Flat k-NN): Checking every single one of those 10 million vectors for every user question forces the CPU to read 61.4 GB per query (~several seconds!). That is why engineers compress vectors and build Approximate Nearest Neighbor (ANN) shortcuts!