Search

Search papers and lessons

Accelerating Large-Scale Inference with Anisotropic Vector Quantization

Ruiqi Guo, Philip Sun, Erik Lindgren et al. · 2019

ScaNN compresses vectors with a loss that penalises errors along the datapoint more than errors across it, which keeps the top inner-product matches correct at high recall.

On this page

  • Colour = topic mix
  • Linear algebra
  • Discrete math
  • Calculus
  • Probability
  • Neural network basics
  • Algorithms
  • ReadReady to readNot yet

TL;DR

Many search systems, from product recommendations to retrieval for language models, ask which stored vector has the largest dot product with a query. ScaNN is a way to store those vectors in a few bits each. Ordinary compression minimises the error on each stored vector. ScaNN instead minimises the error on the pairs a query is likely to rank highly, which means it penalises the part of the error that points along each vector more than the part that points across it. The result is more correct top matches for the same number of bits.

Builds on: Maximum Inner Product Search, Product Quantization, Orthogonal Projection · Leads to: Product Quantization is the codebook method it modifies, and HNSW: Efficient and Robust Approximate Nearest Neighbor Search is the graph-based alternative for the same search problem

Why it mattered

Maximum inner product search (MIPS) sits behind many large systems. In recommendation, users and items are embedded in one vector space and the items with the highest dot product with a user are shown. In extreme classification, a model with millions of classes picks its label by a dot product against a weight vector per class. Training itself uses the same operation for large output layers and for sparse memory lookups.

At that scale, scoring every datapoint is too slow, so quantization is used to shrink each vector and to speed up scoring. ScaNN's main contribution is a change to the quantization objective rather than a new search structure. The authors report state-of-the-art results on the public ANN-Benchmarks suite, and the implementation was released as open-source code.

The problem

Quantization replaces each datapoint xx with an approximation x~\tilde{x} taken from a small codebook. Standard methods choose the codeword that minimises the reconstruction error ∥x−x~∥2\lVert x - \tilde{x} \rVert^2. The paper shows that, if the queries are spread uniformly over directions, this objective is the same as minimising the average inner-product error over all datapoint and query pairs. That average treats every pair as equally important.

They are not. For a fixed datapoint, a query whose inner product with it is large is the one most likely to rank it at the top, so the error on that pair matters most. An approximation error on a pair with a low score is nearly irrelevant to the answer. Reconstruction error throws this difference away, so a codeword that is close in Euclidean distance can still give a worse top-ranking score than a codeword that is slightly further away but errs in the right direction.

How it works

The method runs in an offline phase and an online phase.

  1. Offline input: the database and a weight rule. Take the nn datapoints and choose a threshold TT on the inner product. Pairs whose score is below TT are ignored; pairs above it count. Tiny instance: with T=0.2T = 0.2 and unit-norm datapoints, a query that scores 0.5 with a point contributes to its loss, and one that scores 0.1 does not.
  2. Offline: learn the codebook with the anisotropic loss. Start from random datapoints as codewords. For each datapoint, pick the codeword with the smallest anisotropic loss, which weights the error along the datapoint more than the error across it. Then recompute each codeword as the weighted average of the datapoints assigned to it, with a closed-form update. Repeat until nothing changes. Check: the procedure has the same shape as k-means, and it can only lower the loss at each step.
  3. Offline: encode. Each datapoint is stored as a short list of codeword indices. With product quantization, the vector is split into subspaces and each subspace gets its own codebook, so the list has one index per subspace.
  4. Online: build a lookup table for the query. For each subspace, compute the dot product of the query's piece with every codeword in that subspace's codebook. The cost is proportional to the codebook size times the dimension, not to the number of datapoints.
  5. Online: score by table lookup. For each stored datapoint, add up the table entries its indices point to. That gives an approximate inner product. Check: the work per datapoint is one lookup per subspace, not one multiply per dimension.
  6. Output: the highest-scoring datapoints. Rank by the approximate scores and return the top results.

The tiny instance that makes the difference concrete: a unit-norm datapoint xx and two candidate codewords. Candidate A leaves an error of length 0.2 across the datapoint (orthogonal). Candidate B leaves an error of length 0.15 along it (parallel). Euclidean reconstruction prefers B, since 0.15<0.20.15 \lt 0.2. The anisotropic loss, with the paper's weight at T=0.2T = 0.2 in dimension 100, gives A the loss 0.040.04 and B the loss 4.125×0.152≈0.0934.125 \times 0.15^2 \approx 0.093, so it prefers A.

flowchart LR
  A[Datapoints and threshold T] --> B[Anisotropic codebook learning]
  B --> C[Encode each point as codeword indices]
  Q[Query] --> D[Lookup table of codeword dot products]
  C --> E[Sum table entries per datapoint]
  D --> E
  E --> F[Top matches]

The math

Let x~\tilde{x} be the quantised version of xx, and let qq be a query drawn from a distribution Q\mathcal{Q}. The score-aware quantization loss weights the squared error on the inner product by a function ww of the true score, ℓ(x,x~,w)=Eq[w(⟨q,x⟩)⟨q,x−x~⟩2]\ell(x, \tilde{x}, w) = \mathbb{E}_{q}\left[ w(\langle q, x \rangle) \langle q, x - \tilde{x} \rangle^2 \right]. With a constant ww and isotropic queries, the loss reduces to ordinary reconstruction loss, which is why the standard methods optimise it. The choice w(t)=I(t≥T)w(t) = \mathbf{I}(t \geq T) counts only queries whose score is at least TT.

Step 2 in symbols: splitting the error into two parts

Write the residual as x−x~x - \tilde{x}. Its component along xx is the parallel part r∥=⟨x−x~,x⟩∥x∥2xr_\parallel = \frac{\langle x - \tilde{x}, x \rangle}{\lVert x \rVert^2} x, and the rest is the orthogonal part r⊥=(x−x~)−r∥r_\perp = (x - \tilde{x}) - r_\parallel. The paper's Theorem 3.2 shows that for any weight ww and queries uniform on the sphere, the loss splits as ℓ=h∥∥r∥∥2+h⊥∥r⊥∥2\ell = h_\parallel \lVert r_\parallel \rVert^2 + h_\perp \lVert r_\perp \rVert^2, with weights that depend only on ww and ∥x∥\lVert x \rVert.

Step 2 in symbols: the anisotropic ratio

For the threshold weight in high dimension dd, the ratio η=h∥/h⊥\eta = h_\parallel / h_\perp has the limit ηd−1→(T/∥x∥)21−(T/∥x∥)2\frac{\eta}{d - 1} \to \frac{(T / \lVert x \rVert)^2}{1 - (T / \lVert x \rVert)^2}. Theorem 3.3 shows η≥1\eta \geq 1 for any non-decreasing weight, so the parallel error is never penalised less than the orthogonal one. Up to a constant, the loss is η∥r∥∥2+∥r⊥∥2\eta \lVert r_\parallel \rVert^2 + \lVert r_\perp \rVert^2.

Step 2 in symbols: the codebook update

Within a partition XjX_j, the codeword update is the closed form cj∗=(∑xi∈Xjhi,⊥I+∑xi∈Xjhi,∥−hi,⊥∥xi∥2xixiT)−1∑xi∈Xjhi,∥xic_j^{*} = \left( \sum_{x_i \in X_j} h_{i,\perp} I + \sum_{x_i \in X_j} \frac{h_{i,\parallel} - h_{i,\perp}}{\lVert x_i \rVert^2} x_i x_i^T \right)^{-1} \sum_{x_i \in X_j} h_{i,\parallel} x_i. When the two weights are equal, this reduces to the ordinary weighted mean, which is the k-means update.

Step 4 in symbols: the score of a stored point

With product quantization, xx is split into MM pieces, each quantised by one of MM codebooks of kk entries. The approximate score is ⟨q,x~⟩=∑m=1M⟨q(m),cim(m)⟩\langle q, \tilde{x} \rangle = \sum_{m=1}^{M} \langle q^{(m)}, c^{(m)}_{i_m} \rangle, where imi_m is the index chosen for piece mm. The table holds the MkM k values ⟨q(m),cj(m)⟩\langle q^{(m)}, c^{(m)}_j \rangle, computed once per query.

Worked examples

Example
1. Tiny: two codewords, one datapoint

Let xx have norm 1 in dimension d=100d = 100, with threshold T=0.2T = 0.2, so η=4.125\eta = 4.125. The value of η\eta follows from Theorem 3.4: (0.2)21−(0.2)2=0.040.96≈0.04167\frac{(0.2)^2}{1 - (0.2)^2} = \frac{0.04}{0.96} \approx 0.04167, and multiplying by d−1=99d - 1 = 99 gives 4.1254.125.

  1. Candidate A has orthogonal error 0.2 and parallel error 0. Loss: η⋅02+0.22=0.04\eta \cdot 0^2 + 0.2^2 = 0.04.
  2. Candidate B has parallel error 0.15 and orthogonal error 0. Loss: η⋅0.152+0=4.125⋅0.0225≈0.093\eta \cdot 0.15^2 + 0 = 4.125 \cdot 0.0225 \approx 0.093.
  3. Euclidean reconstruction loss: A gives 0.22=0.040.2^2 = 0.04 and B gives 0.152=0.02250.15^2 = 0.0225, so reconstruction prefers B.
  4. Interpretation: the anisotropic loss prefers A, which errs across the datapoint, because B's error would change the scores of the queries most likely to rank xx at the top.
Example
2. Standard: the cost of a lookup table

Take nn datapoints in dimension dd. Exact scoring costs ndn d multiply-adds. With product quantization using MM codebooks of kk entries, the query table costs kdk d multiply-adds once, and each datapoint costs MM lookups and additions.

  1. Exact work with n=1,000,000n = 1{,}000{,}000 and d=100d = 100: 1,000,000⋅100=100,000,0001{,}000{,}000 \cdot 100 = 100{,}000{,}000 multiply-adds.
  2. Table work with k=256k = 256: 256⋅100=25,600256 \cdot 100 = 25{,}600, a negligible one-off cost.
  3. Lookup work with M=25M = 25: 1,000,000⋅25=25,000,0001{,}000{,}000 \cdot 25 = 25{,}000{,}000 lookups.
  4. Interpretation: the lookups replace multiply-adds by a quarter, so the scan is about four times less arithmetic. The values of nn, dd, kk and MM here are chosen for the arithmetic; the paper's experiments use their own settings.
Example
3. Realistic: the Glove benchmark setting

The paper's main dataset is Glove with 1.2 million 100-dimensional word vectors, searched by cosine similarity. Because the datapoints are unit-normalised, the inner product and the cosine give the same ranking, so the method applies directly.

  1. Dimension and count: 100 dimensions and 1,200,000 vectors.
  2. Exact scoring of one query: 1,200,000⋅100=120,000,0001{,}200{,}000 \cdot 100 = 120{,}000{,}000 multiply-adds.
  3. Threshold chosen by the authors: T=0.2T = 0.2, giving η=4.125\eta = 4.125, which they use for all later experiments.
  4. Interpretation: the anisotropic loss changes how codewords are chosen, not how queries are scored. The lookup step is the same as for a standard product quantizer with the same codebook sizes, so any gain comes from the codebook.
  5. Try it: with 25 codebooks, how many lookups does one query need across all 1.2 million vectors, and what fraction of the exact multiply-adds is that? Answer: 1,200,000⋅25=30,000,0001{,}200{,}000 \cdot 25 = 30{,}000{,}000 lookups, which is 30,000,000/120,000,000=0.2530{,}000{,}000 / 120{,}000{,}000 = 0.25, a quarter of the exact work.

Results

The experiments compare the losses, then whole systems, all on Glove with 1.2 million vectors unless noted.

  • Same quantizer, different loss. With product quantization fixed, the score-aware loss gives significantly higher Recall 1@10 than reconstruction loss once TT is chosen reasonably, and the authors fix T=0.2T = 0.2 for the rest of the paper. It also gives lower relative error in estimating the top inner product at every bit rate tested. The paper points out that this matters for softmax approximations, where the inner products are used as logits.
  • Against other quantizers at fixed bits. At 100 and 200 bits per datapoint, the anisotropic method has higher Recall 1@N than LSQ and the three QUIPS variants, for all values of N tested.
  • End-to-end speed against recall. On the ANN-Benchmarks protocol with 11 baseline algorithms, run on a single CPU thread, the method is the fastest at high recall on Glove. The paper argues that this end-to-end timing captures overheads such as learned rotation and lookup-table construction, which fixed-bit comparisons leave out.
  • Other data. The paper reports similar gains on an extreme-classification dataset, Amazon-670k, in its appendix, and applies the same loss change to binary quantization with a one-line modification.

Limits. The main claims rest on one dataset with cosine similarity, and the analysis assumes queries are uniform on the sphere when no query distribution is known. The threshold TT is a hand-chosen hyperparameter, and recall gains depend on choosing it reasonably. The speed comparison is on one CPU thread, and the implementation relies on SIMD distance computation. The conclusion is that anisotropic loss helps quantized MIPS, not that it dominates graph-based methods on every workload.

Reading guide

  • Section 1, Introduction. Read with Maximum Inner Product Search and Recommender System open. The examples there are the reasons the search problem matters.
  • Section 2, Background. Needs Dot Product, Vector Quantization and K-Means Clustering. The list of quantization families is a map of alternatives, not a set of prerequisites.
  • Section 3, Problem formulation. Needs Expected Value and Orthogonal Projection. Theorem 3.2 is the key: it splits the loss into parallel and orthogonal parts, and Figure 1 shows why the split matters.
  • Section 4, Application to quantization. Needs Product Quantization. Read the vector quantization update first; the product version reuses it with subspaces.
  • Section 5, Experiments. Figures 3 and 4 are the evidence; check each caption for the bit rate or the metric before reading the lines.
  • Appendix, Proofs. Only needed if you want the derivation of the splitting in Theorem 3.2.

Check yourself

QuestionRecall: what is the difference between reconstruction loss and the score-aware loss?Show answer

Reconstruction loss minimises the squared error on each stored vector, treating every query as equally likely. The score-aware loss weights the squared error on each query by a function of its true score, so errors on high-scoring pairs count more. For the threshold weight, that makes errors along the datapoint count more than errors across it.

QuestionWith d=100d = 100 and T=0.2T = 0.2 for a unit-norm datapoint, what is the anisotropic ratio η\eta?Show answer

Use the limit ηd−1≈(0.2)21−(0.2)2=0.040.96≈0.04167\frac{\eta}{d - 1} \approx \frac{(0.2)^2}{1 - (0.2)^2} = \frac{0.04}{0.96} \approx 0.04167. Multiplying by d−1=99d - 1 = 99 gives η≈4.125\eta \approx 4.125, the value the paper uses.

QuestionWhy does product quantization make the query-time work cheaper than exact scoring, even though each datapoint still needs one operation per subspace?Show answer

The per-subspace dot products with the codewords are computed once for the query, in a table of size proportional to the codebook size times the dimension. After that, each datapoint needs only one table lookup per subspace, which is far fewer operations than one multiply per dimension when the number of subspaces is much smaller than the dimension.

QuestionA quantizer with the anisotropic loss has slightly higher reconstruction error than a standard quantizer. Is that a failure?Show answer

Not by the paper's standard. Reconstruction error is not the target. What matters is the Recall 1@N of the top matches and the accuracy of the top inner-product estimates, and the paper reports that the anisotropic quantizer wins on those measures. A higher reconstruction error is expected when the codebook trades off error across the datapoint for error along it.

Sources

  • Guo et al., "Accelerating Large-Scale Inference with Anisotropic Vector Quantization", 2019 (arXiv:1908.10396).
  • ANN-Benchmarks, the public benchmark of approximate nearest neighbor search.
  • Vector quantization, Wikipedia.

Read the full paper

Ruiqi Guo, Philip Sun, Erik Lindgren et al., 2019. arXiv:1908.10396