16/39
Part 3 of 6 · EstimationLearn and do

IVF with product quantization fits a billion vectors in 40 GB

A flat index for a billion vectors doesn't fit on one machine. An approximate index changes that.

An IVF index scans only the nearest lists
the K lists, after comparing the query with K centroids
list 1list 2list 3…list K

The query is compared with K centroids, and only the nearest lists are scanned. The rest are skipped.

IVF, inverted file: k-means splits the vectors into clusters, each with a list of its members. A query scans only the few lists whose centroids sit nearest it.

A flat index is the opposite. It stores every vector as it is and compares the query with all of them: exact, and as big as the raw vectors.

On its own, IVF saves search time, not memory: its lists still hold every vector. Product quantization shrinks what the lists hold.

Product quantization (PQ) splits each vector into M sub-vectors: here one vector of 256 numbers and 1,024 bytes becomes 32 pieces of 8 numbers. For each piece, it keeps only the index of the nearest centroid in a small learned codebook. The Faiss docs put it the same way: each sub-vector is quantized to a few bits, usually 8. Eight bits, 1 byte, name one of 256 centroids. Stored: 32 bytes of codes plus an 8-byte id, 40 bytes in all.

Faiss's index table gives the size of an IVF index with PQ codes as ceil(M * nbits/8)+8 bytes per vector. Here nbits is the bits per code, and the 8 is the stored vector id. A flat float index takes 4*d bytes, where d is the vector's dimension, 256 here.

From 1,024 bytes to 40 is 25.6 times smaller, or 32 times counting only the codes. A billion vectors now take 40 GB.

So the index fits on one large machine. You add replicas, full copies, for throughput, instead of shards, pieces on different machines, for memory.

Retrieve approximately, then rescore exactlyInteractive
query. One query vector.

Compression costs accuracy. Distances computed from codes are approximate, so recall, the share of the true nearest neighbors you find, drops.

The usual fix is two steps. Pull a few hundred candidates from the compressed index. Then rescore them with full vectors kept elsewhere.

In the editor, write flat_bytes(n, d, bytes_per_value=4) and ivfpq_bytes(n, M, nbits=8): the flat size and the Faiss size for IVF with product quantization, both in bytes. With them you can size any index in one line.