Compute approximate distances from compact codes
Derive product-code storage, asymmetric distance tables, and the distinction between reconstruction and ranking error.
On this page
The question for today
What you’ll understand
- Encode a vector with separate subspace codebooks.
- Calculate an asymmetric distance estimate and its exact counterpart.
- Account for codes, codebooks, IDs, and reranking payload separately.
Product quantization saves memory by replacing each database vector with several small codebook indices. Its trick is combinatorial: a modest collection of subspace centroids implicitly describes many complete-vector reconstructions. Search can compare an uncompressed query with those reconstructions through lookup tables instead of decoding and subtracting every coordinate repeatedly. The resulting distance is approximate even when every code is scanned. Understanding this lets you distinguish two very different recall failures: a good document was never considered, or it was considered but its compressed representation placed it in the wrong order.
A product of small choices
Split a d-dimensional vector into m equal coordinate groups, assuming d is divisible by m for this basic construction. Train K centroids for each group and encode the nearest centroid index in that group. Concatenating the chosen centroids reconstructs a full vector. With K equal to a power of two, each group needs log₂K bits, and m groups provide K^m possible reconstructions without storing K^m complete vectors. The actual codebooks contain only Kd coordinate values.
The codebook is shared across the corpus and must travel with the encoded data. A code such as (1,1) has no geometric meaning without the exact centroid arrays, group ordering, and any preprocessing transform. Changing a codebook while keeping the old bytes silently changes their decoded vectors. In residual IVFPQ, the encoded quantity is typically the vector minus its coarse centroid, so the selected coarse codebook and residual convention are also part of that decoding contract.
Leave the query uncompressed
For asymmetric distance computation, construct a table of squared distances from each query subvector to every centroid in its corresponding codebook. A stored code then selects one entry from each table, and their sum is the squared distance to its reconstruction. The query keeps its original precision. This avoids adding query quantization error, but it cannot restore information discarded from the database vector. Different original vectors can share an identical code and therefore tie under the approximate score.
Reconstruction error and ranking error answer different questions. A small average reconstruction error does not ensure that the nearest two documents keep their order when their true distances are close. Conversely, a large error in an irrelevant direction might leave a particular query ranking unchanged. Measure recall under the target query distribution. If exact vectors are retained elsewhere, rerank a sufficiently broad candidate set, recognizing that exact reranking cannot recover a document omitted before that stage.
Count the whole memory and training budget
A raw float32 vector consumes four bytes per coordinate, while a PQ payload might use only a few bytes. The ratio is meaningful only after naming what is counted. Add document IDs, coarse-list structures, graph links if present, shared codebooks, query lookup tables, and any original vectors used for reranking. On a tiny corpus, shared codebooks can dominate; on a large corpus, per-document codes and identifiers usually matter more. Compression ratios should state decimal or binary byte units.
Representative training is especially important when different coordinate groups have different distributions. A codebook trained on one encoder or document population can waste its centroids on regions absent from a new corpus. Validate reconstruction error by slice and retrieval recall separately, rather than assuming one number predicts the other. If you introduce a rotation or another learned preprocessing transform, preserve that exact transform with the snapshot and apply it consistently before both encoding and querying.
Work it through
Two codebook lookups versus the original distance
Split d=4 into m=2 groups. Use C₁={(0,0),(2,2)} and C₂={(0,0),(4,4)}, indexed 0 and 1. Encode x=(1.8,2.1,3.7,4.2), then compare it with q=(2,1,4,3) using asymmetric squared L2.
Each subvector is closest to centroid 1, giving code (1,1) and reconstruction xhat=(2,2,4,4). Reconstruction squared error is 0.2²+0.1²+0.3²+0.2²=0.18; the code has 2 bits, rounded to one byte if stored independently.
For q, the selected first-group table entry is (2−2)²+(1−2)²=1. The selected second-group entry is (4−4)²+(3−4)²=1. Summing the two entries gives approximate squared distance 2.
Compute the original-vector distance directly: (2−1.8)²+(1−2.1)²+(4−3.7)²+(3−4.2)²=0.04+1.21+0.09+1.44=2.78. The distance estimate is lower by 0.78 in squared-coordinate units.
The stored code is compact, but its score 2 describes the reconstruction rather than the original vector’s score 2.78. No candidate-pruning error was needed for this discrepancy.
The living notebook
Explore the model
Interactive lab · matrix
A transform changes geometry before compression
Reset, set Diagonal scale a to 1 and Shear b to 0, predict determinant 1 and singular values 1,1, then Step. Reset, set a to 2 and b to 0, predict determinant 2 and singular values 2,1, then Step. Readouts describe the selected final matrix even while the animation interpolates. This two-dimensional triangular transform is not PQ training or a general learned rotation.
- Area scale · det A
- 1.4
- Singular values · σmax, σmin
- 1.597, 0.876
- Condition number · κ₂(A)
- 1.823
The selected matrix is A = [[a,b],[0,1]]. Playback interpolates geometry between the identity and A; readouts always describe A. Its determinant is a and its singular values come from AᵀA. Positive a makes every supported matrix invertible. This two-dimensional family is not a general eigensolver or a learned network. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forPreprocessing is part of geometry and must be preserved with compressed codes.
Pause & reason
Check your understanding
Your turn
Try it yourself
For d=8, m=4, and K=16, compute packed bytes per vector and shared codebook scalar count. Compare only vector-code payload with eight float32 coordinates, excluding IDs and metadata.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
There are four bits per centroid index and four independent groups.
Compare with the solution
Each code has 4×log₂16=16 bits, or 2 packed bytes. Shared codebooks contain Kd=16×8=128 scalars, which would occupy 512 bytes as float32. A raw vector occupies 8×4=32 bytes, so code payload alone is 16 times smaller; that ratio excludes the shared codebooks, IDs, and any retained exact vectors.
Keep the idea
Take it with you
- PQ stores subspace centroid indices plus shared codebooks.
- Asymmetric scoring is exact for the reconstruction, approximate for the original.
- Include IDs, shared structures, and reranking vectors in memory comparisons.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.