15/36
Part 2 of 5 · Stages and retrievalLearn and do

Product quantization shrinks each vector to a few bytes

Product quantization cuts one vector of 8 numbers, [0.12 0.80 | 0.33 0.05 | 0.91 0.40 | 0.27 0.66], into 4 pieces. Each piece becomes 1 byte, here 17, 203, 4 and 88, which names the nearest of 256 centers learned for that piece. 4 bytes in all.

Product quantization (PQ) cuts each vector into pieces and replaces each piece with the number of its nearest center, from a small list learned for that piece. With 256 centers, a piece fits in one byte. PQ usually sits inside an IVF index.

At a billion 256-dimensional vectors, it takes the index from 1 TB to 40 GB: 32 bytes of codes plus an 8-byte id for each vector. The design method lesson works that math.

In the editor, write encode(vec), which turns an 8-number vector into 4 codes, and index_gb(n, code_bytes), the size of an index of n encoded vectors. codebooks holds the learned centers, 3 for each of the 4 pieces here instead of 256, so you can check the codes by eye.