Sub topic 4
Why exact search stops scaling
This chapter assumes you can write basic Python with NumPy, know what a dot product is, and know that an embedding is a vector produced by a model. It also assumes you have read the previous chapter, where brute-force search was a single matrix product. Here you will see why that approach breaks down as the collection grows, and why the usual shortcut of a tree index does not rescue it.
The cost model of brute force
Exact nearest neighbor search compares the query with every stored vector. For a collection of N vectors with d dimensions, one query costs:
- About 2 × N × d floating-point operations, because each dot product needs d multiplications and d additions.
- A read of all N × d numbers from memory, because every vector must be touched.
Both costs grow linearly with N. Doubling the collection doubles the time per query. There is no shortcut inside this method, because skipping a vector means you can no longer promise it was not the nearest one.
The memory side usually dominates. A float32 value takes 4 bytes, so a 768-dimensional vector takes 3,072 bytes. A search over one vector reads about 3 KB, and the arithmetic on it is small compared with the time to fetch it. Brute force is therefore memory-bandwidth bound: the speed of the memory bus sets the speed of the search, not the speed of the CPU.
Putting numbers on it
Take 768-dimensional float32 vectors and one machine that can stream about 50 GB/s from RAM. The times below are lower bounds for scanning the data once per query. They are order-of-magnitude estimates, not benchmarks.
| Vectors (N) | Raw size | Scan time per query | Fits in RAM of one server? |
|---|---|---|---|
| 100,000 | 0.3 GB | about 6 ms | Yes |
| 1 million | 3.1 GB | about 60 ms | Yes |
| 10 million | 31 GB | about 0.6 s | Usually |
| 100 million | 307 GB | about 6 s | Rarely |
| 1 billion | 3.1 TB | about 60 s | No, needs a cluster |
Two things happen as N grows. Latency passes what an interactive application can tolerate, which is often tens of milliseconds. Then the data stops fitting on one machine, so you must split it across machines and every query must visit all of them.
Throughput matters as much as latency. If one query takes 60 ms and uses the whole memory bus, one server answers about 16 queries per second. Serving 1,000 queries per second would need dozens of servers that each scan their own full copy. At 10 times the data, you need about 10 times the hardware for the same query rate.
Measuring it yourself
The script below times a brute-force top-10 search at three sizes. It uses argpartition to find the top 10 without sorting every score, which is the standard efficient approach. The absolute numbers depend on your hardware. The ratio between rows is what to look at.
import time
import numpy as np
d = 768
k = 10
rng = np.random.default_rng(0)
query = rng.standard_normal(d, dtype="float32")
query /= np.linalg.norm(query)
for n in [10_000, 50_000, 200_000]:
vectors = rng.standard_normal((n, d), dtype="float32")
vectors /= np.linalg.norm(vectors, axis=1, keepdims=True)
start = time.perf_counter()
scores = vectors @ query
top = np.argpartition(-scores, k)[:k]
top = top[np.argsort(-scores[top])]
elapsed_ms = (time.perf_counter() - start) * 1000
size_mb = vectors.nbytes / 1e6
print(f"n={n:>8,} data={size_mb:>7.1f} MB time={elapsed_ms:>7.2f} ms")Expect time to grow roughly in proportion to n. The first run at each size may be slower because of cold caches, so run the script twice if the numbers look odd.
Why not use a tree, as in ordinary databases?
For low-dimensional data, such as 2D map coordinates, trees solve this problem well. A k-d tree splits space along one coordinate at a time. At query time it skips whole regions that are provably farther away than the best result found so far. This pruning cuts the search to roughly logarithmic time.
Pruning relies on a region being clearly farther than the current best candidate. In high dimensions that stops being true, for two connected reasons.
Distance concentration
As d grows, the distances from a query to random points become nearly equal. The gap between the nearest and the farthest point shrinks relative to the distances themselves. When everything is about equally far away, there is little to rule out.
The next script measures this. Its relative contrast is (farthest − nearest) / nearest over 2,000 random points. A large value means the nearest point stands out. A value near zero means it does not.
import numpy as np
rng = np.random.default_rng(0)
for d in [2, 10, 100, 1000, 10000]:
points = rng.random((2000, d))
query = rng.random(d)
dist = np.linalg.norm(points - query, axis=1)
contrast = (dist.max() - dist.min()) / dist.min()
print(f"d={d:>6} relative contrast={contrast:.3f}")The contrast falls by orders of magnitude between d = 2 and d = 10,000. The exact values vary with the random seed, but the downward trend does not.
Failure of space partitioning
A k-d tree makes one split per level, and each split uses a single coordinate. With d = 768 and N = 1 million, the tree has only about 20 levels. That is about 20 coordinates out of 768 ever being used. The query ball, the region around the query that could still contain the answer, crosses almost every split boundary, so the search cannot discard branches. It ends up visiting most of the tree, with extra overhead on top of a plain scan.
A common rule of thumb says a k-d tree beats a linear scan only when N is much larger than 2^d. For d = 768 that condition is out of reach for any real dataset. Trees in this regime are slower than brute force.
What the curse of dimensionality does not say
It is easy to over-read the argument above. Real embeddings are not uniform random points in 768 dimensions. They lie near a lower-dimensional structure, because text about the same topic produces similar vectors. The intrinsic dimension, meaning the number of directions the data varies in, is often far smaller than d. That is why graph and cluster indexes work well on real embeddings.
Random data is also close to the worst case. If you benchmark an index on random vectors, as the toy examples in this tutorial do, recall and speed will look worse than on real embeddings. Test on a sample of your own data before drawing conclusions.
Distance concentration also has a practical consequence for your results. When contrast is low, the top 10 results can differ by tiny score gaps. A small error in the stored vectors, for example from compression, can then reorder them. Keep this in mind in the chapters on quantization and recall.
Where exact search is still the right choice
Brute force is not obsolete. It is the correct choice when:
- The collection is small, up to a few hundred thousand vectors. A scan takes milliseconds and has no tuning, no build step and no recall loss.
- You need the exact baseline for measuring an approximate index. The recall of any index is defined relative to it.
- Filters are so selective that only a few thousand candidates remain. Scanning the survivors exactly is often faster than a filtered index search.
- Queries come in large batches and can share each pass over the data.
The practical rule is to start with exact search and move to an approximate index only when measured latency or cost forces it.
What approximate search gives up
Approximate indexes avoid the full scan by examining only a small part of the data. Two costs follow:
- The answer may miss some true neighbors. This is the recall loss, and the next chapter defines how to measure it.
- The index uses extra memory and build time, and it must be maintained when data changes.
The goal is to cut the work per query by factors of 100 to 1,000 while keeping recall above a level your application accepts, commonly 90 to 99 percent.
Exercise
A service stores 50 million float32 embeddings with 1,024 dimensions on one server that streams about 50 GB/s from RAM. Estimate the raw data size and the minimum time for one brute-force query. Then say whether a k-d tree would help and why.
Show answer
Size is 50,000,000 × 1,024 × 4 bytes, which is about 205 GB. Scanning it once at 50 GB/s takes about 4 seconds per query, so one server could answer only about 0.25 queries per second, and the data probably would not fit in its RAM. A k-d tree would not help. At d = 1,024 distances concentrate and each split uses only one coordinate, so the query ball crosses almost every split and the search visits most of the tree. This is why an approximate index such as HNSW or IVF, possibly with compression, is needed.
Exercise
In the contrast experiment, why does relative contrast fall as d grows, and what does that imply for a pruning-based index?
Show answer
In high dimensions the distances from a query to random points concentrate around a common value, so the farthest point is barely farther than the nearest one. A pruning-based index can only skip regions that are clearly farther than the current best candidate. When almost nothing is clearly farther, almost nothing can be skipped, and the search degrades toward a full scan.