Optimized Product Quantization and Score-Aware Quantization
Two ways to make a product quantizer optimal: rotate the space so its subspaces carry balanced information, and reshape the loss so it protects the inner products a query actually sees
Overview & motivation
The previous topic left a clean cliffhanger. Product quantization splits a vector into disjoint subvectors and quantizes each subspace independently, and it works because squared Euclidean distance separates over disjoint coordinate blocks. But that separation is also its weakness: the quantizer treats the subspaces as if they were independent and gives each the same number of bits. On a deliberately variance-imbalanced cloud — coordinates whose variance decays geometrically — raw product quantization paid a reconstruction distortion of about , because the equal bit budget over-quantizes the low-variance tail and starves the high-variance head. A rotation that balanced the variance across subspaces cut that distortion to about . We showed the direction of the effect and named the fix; this topic is the fix.
There are two independent ways to make a product quantizer better, and they are orthogonal in the literal sense. The first changes the axes: rotate the space before the split so each subspace carries a balanced share of the data’s information. This is optimized product quantization (OPQ), and it is the first half of the topic. The second changes the loss: when the downstream task is maximum-inner-product search rather than reconstruction, the error that matters is not how far the reconstruction sits from the vector, but how much it disturbs the inner products that high-scoring queries see. This is score-aware, or anisotropic, quantization — the idea behind ScaNN — and it is the second half. The laboratory below lets you switch between the four rotations, watch the alternating optimization converge, and raise the anisotropy to see a quantizer trade reconstruction for inner-product fidelity.
The first panel is the on-ramp made precise: switch among the raw axes, a naive PCA-alignment, the previous topic’s balancing heuristic, and the learned OPQ rotation, and read the distortion drop and the per-subspace variance bars. The second panel runs the alternating optimization and shows its distortion descending monotonically below the heuristic. The third panel is the score-aware story: a datapoint, its candidate codewords, and the residual split into the part that moves the inner product and the part that does not.
The rotation is a free isometry
Throughout, is a database vector, is an orthogonal matrix (), and the data splits into contiguous subspaces of width . A rotated product quantizer first maps , then product-quantizes the rotated vector.
Definition 1 (Rotated product quantizer).
Fix an orthogonal and a product codebook with centroids per subspace. The rotated product quantizer encodes by the tuple of sub-centroid indices of and reconstructs
where is the ordinary product-quantization codeword. Optimized product quantization minimizes the reconstruction distortion jointly over the rotation and the codebooks:
Why is it legitimate to rotate the data before quantizing — does it not change the retrieval problem? It does not, and this is the whole license for the method.
Theorem 1 (Rotation is a distance- and inner-product-preserving isometry).
For any orthogonal and any ,
Consequently, rotating every database vector and every query by the same leaves all pairwise distances and all inner products unchanged, so the true nearest neighbors and the true maximum-inner-product results are identical. Since ordinary product quantization is the special case , and the feasible set of optimized product quantization strictly contains it, the optimized distortion never exceeds the unoptimized one:
Proof.
Orthogonality gives , and the same computation applied to and to the polarization identity gives both equalities. Encoding as the nearest codeword of and decoding through is therefore a quantizer on the original space whose distortion equals that of ordinary product quantization applied to the rotated data. Optimizing over includes , so the minimum can only decrease.
∎The rotation is, in this exact sense, free: it cannot move a single true neighbor, but it adds degrees of freedom the quantizer can spend to reduce distortion. The companion code verifies the isometry directly and confirms that rotating both the database and the queries leaves every true nearest neighbor in place. The only question left is which to choose.
Parametric OPQ: balance the product, not the sum
When the data is well modeled by a Gaussian, the optimal rotation has a closed form. Write for the covariance of , and after rotation let , partitioned into diagonal blocks of size — one per subspace. High-rate quantization theory bounds the distortion of a -centroid quantizer of a Gaussian by a constant times , the determinant to the power. Applying that bound per subspace and summing gives the quantity OPQ must minimize.
Theorem 2 (Parametric optimum: decorrelate and balance the determinant).
Under and the high-rate bound, the product-quantization distortion after rotation satisfies
and minimizing the right-hand side over is equivalent to minimizing . By the arithmetic–geometric-mean inequality and Fischer’s inequality,
a bound that is constant in . It is attained if and only if (i) the off-diagonal blocks of vanish — the subspaces are decorrelated, achieved by aligning to the principal axes — and (ii) the block determinants are equal across subspaces, i.e. the product of the eigenvalues assigned to each subspace is balanced.
The two conditions are distinct, and both are needed. Diagonalizing by PCA makes Fischer’s inequality tight — it removes cross-subspace correlation — but it does not say which eigen-axis belongs to which subspace. The arithmetic–geometric-mean step is tight only when the products of eigenvalues match across subspaces, and that is a question of allocation: distribute the eigenvalues into groups so the products are as equal as possible. The greedy eigenvalue allocation does exactly this — it repeatedly places the largest unassigned eigen-axis into the subspace with the smallest current product (equivalently, the smallest sum of log-eigenvalues).
This is where the previous topic’s heuristic and the true optimum part ways, and the difference is provable rather than cosmetic. The balancing heuristic equalized the sum of variances across subspaces — the trace of each block. The parametric optimum equalizes the product — the determinant. Under the high-rate bound the distortion is governed by the geometric mean of the variances, not the arithmetic mean, so balancing the sum is only an approximation while balancing the product is exact. In the companion code, the spread of per-subspace log-variances on the imbalanced cloud falls from about under the raw contiguous blocks to about under the eigenvalue allocation: the determinant is balanced almost perfectly, which the sum-balancing heuristic does not achieve.
The Gaussian assumption is doing real work here, and we flag it: on data that is not Gaussian, the eigenvalue allocation is a principled construction and an excellent starting point, but not a certified optimum. For that we need an algorithm that makes no distributional assumption at all.
Non-parametric OPQ: alternating optimization
Drop the Gaussian model and return to the raw objective of Definition 1. It couples the rotation and the codebooks, and it is not jointly convex — but it splits into two subproblems, each of which we can solve to its global optimum, and alternating between them is a descent.
Theorem 3 (The rotation step is an Orthogonal Procrustes problem).
Hold the codebooks fixed, and let collect the current reconstructions — one per training vector — with the data and reconstructions stacked as columns. The rotation that minimizes the reconstruction error,
has the closed form
read directly off the singular value decomposition of the cross-covariance . Holding the rotation fixed instead, the codebook subproblem is ordinary product quantization on the rotated data — independent Lloyd problems. Alternating the two steps produces a sequence of distortions that is monotone non-increasing and converges.
Proof.
Expand the objective: , so minimizing it is maximizing . With and orthogonal, , since the singular values are non-negative and the diagonal of an orthogonal matrix is bounded by one in magnitude. Equality holds when , i.e. . Each step is the global optimum of its subproblem — the codebook step by Lloyd’s monotonicity, the rotation step by this closed form — so the joint distortion cannot increase. Bounded below by zero, the sequence converges.
∎The guarantee is monotone descent, not global optimality: alternating optimization over a non-convex coupled objective reaches a local optimum that depends on the initialization, and the standard remedy is to warm-start from the parametric eigenvalue-allocation rotation, which is what the companion code does. On the imbalanced cloud the trajectory starts at the heuristic’s distortion of about and descends monotonically to about — the second panel of the laboratory traces it. The extra gain over the balancing heuristic comes from the within-block rotation the Procrustes step finds; the per-subspace variance sums barely move, which is why the variance bars for the heuristic and for OPQ look almost identical even though the distortion differs. We cross-check the rotation step against scipy.linalg.orthogonal_procrustes rather than trust an opaque library, and assert the monotone descent as a test.
Score-aware quantization: protect the inner product
Everything so far minimized reconstruction error, . For maximum-inner-product search that is the wrong objective. What a search actually cares about is the inner-product error — how much quantization perturbs — and, more sharply, it cares about that error only for the queries that score highly enough to retrieve it. A reconstruction that is excellent on average but distorts the high-scoring inner products is worse than one that is mediocre on average but preserves them.
Make the residual explicit and split it relative to the datapoint’s own direction.
Definition 2 (Parallel and orthogonal residual).
For a datapoint and a reconstruction , decompose the residual into its component parallel to and the orthogonal remainder:
The parallel component is the one that moves the inner product. For a query roughly aligned with — which is what a high-scoring query is — the inner-product error is dominated by the part of the residual along , while the orthogonal part is largely invisible to it. Averaging over queries drawn uniformly from the unit sphere makes this exact.
Theorem 4 (Anisotropic decomposition of the score-aware loss).
Let be uniform on the unit sphere in , and weight each query by a score-dependent weight . The expected weighted inner-product error decomposes as an anisotropic sum of the two residual magnitudes,
and for any weight that is zero on negative scores and non-decreasing on positive ones, . For the threshold weight , the ratio grows with dimension and, for bounded away from , has the large- form
The ratio is the entire content of the result: the parallel error is penalized at least as heavily as the orthogonal error, and strictly more as the score threshold rises. At every query counts equally and the exact ratio is — the isotropic endpoint that the displayed large- form, which tracks only how grows as rises, does not itself capture — and the loss collapses back to ordinary reconstruction. As only near-perfectly-aligned queries count and , penalizing only the parallel error. So the score-aware quantizer minimizes
and chooses, for each datapoint, the codeword that best preserves its magnitude along its own direction even at the cost of larger orthogonal error. The third panel of the laboratory shows the swap: at the quantizer picks the Euclidean-nearest codeword; raise and it switches to a codeword lying exactly on the datapoint’s direction, with zero parallel residual.
The closed-form weight is a large-dimension limit, the threshold (equivalently ) is a tuned knob, and the additive objective above is cleanest when the database has constant norm — all of which we flag. What survives those caveats is the mechanism, and it is robust: protecting the parallel component protects the inner products a query sees.
Honest accounting
The rotated, score-aware codebook is the atom the production indexes assemble. An inverted-file index quantizes the residual after a coarse partition; a multi-vector index quantizes each token embedding; and both inherit, unchanged, the rotation that balances the determinant and the loss that protects the inner product. Those are the topics that follow.
Connections
- optimized product quantization IS product quantization with a learned orthogonal rotation applied before the subspace split: the additive distortion decomposition, the per-subspace Lloyd training, the asymmetric distance lookup, and the variance-imbalanced cloud that motivated the rotation are all inherited unchanged, and the companion code imports the previous topic's train_pq, pq_distortion, and rotation_distortion_study and re-derives its raw, PCA-only, and balanced baselines rather than reimplementing them product-quantization
- the parametric rotation begins exactly where PCA does — diagonalize the covariance to decorrelate the subspaces — and the eigenvalue allocation that balances the variance product across subspaces is a permutation of the principal axes, so optimized PQ is a structured application of the eigendecomposition and variance-ordering developed there pca-dimensionality-reduction
- score-aware quantization decomposes the residual relative to the datapoint's direction on the unit sphere and integrates the inner-product error over queries drawn uniformly from that sphere, so the directional and concentration geometry developed there is exactly the machinery the anisotropic weight ratio is derived from hypersphere-vmf-geometry
References & Further Reading
- paper Optimized Product Quantization — Ge, He, Ke & Sun (2014) The source of both results in the rotation half: the parametric eigenvalue-allocation solution (decorrelate and balance the product of eigenvalues) and the non-parametric alternating algorithm whose rotation step is an Orthogonal Procrustes problem
- paper Accelerating Large-Scale Inference with Anisotropic Vector Quantization — Guo, Sun, Lindgren, Geng, Simcha, Chern & Kumar (2020) The ScaNN paper: the score-aware quantization loss, the parallel/orthogonal residual decomposition, and the proof that for any score-increasing weight the parallel error is penalized at least as heavily as the orthogonal one
- paper Product Quantization for Nearest Neighbor Search — Jégou, Douze & Schmid (2011) The product quantizer optimized here, and the source of the sum-of-variances balancing heuristic that the parametric optimum supersedes
- paper A Generalized Solution of the Orthogonal Procrustes Problem — Schönemann (1966) The closed-form SVD solution R = VU^T to the orthogonal-matrix least-squares problem that is the non-parametric rotation step
- documentation Faiss: Billion-Scale Similarity Search — Johnson, Douze & Jégou (2019) How production ANN indexes implement the OPQ pre-rotation as a matrix multiply composed with PQ encoding (IndexPreTransform + IndexPQ / IndexIVFPQ)