Score vectors with product-quantisation lookup tables
Why it matters Billion-scale vector search (FAISS IVF-PQ, ScaNN) scores candidates with ADC tables.
Product quantisation splits a vector into m sub-vectors and stores each as the id of its nearest sub-codebook entry. Asymmetric distance computation (ADC) scores a raw query against codes using lookup tables.
Write pq_adc(q, codebooks, codes). q is (d,), codebooks is (m, K, d // m), codes is (n, m) ints. Build table T[j, c] = ||q_j - codebooks[j, c]||^2 where q_j is the j-th sub-vector of q. Return the (n,) approximate squared distances sum_j T[j, codes[i, j]].
def pq_adc(q, codebooks, codes)Example
d 2, m 2, codebooks [[[0], [1]], [[0], [2]]], codes [[1, 1]], q [1, 2] gives [0.0].
Understand the idea
Product quantisation compresses each database vector by splitting it into m pieces and storing, for each piece, only the id of its nearest codebook entry. To score a query you do not decompress anything. You build a small table of squared distances from each query piece to every codebook entry, then a vector's distance is just the sum of m table lookups. Worked example: d = 4, m = 2, two entries per block. Block 0 codebook [[0, 0], [1, 1]], block 1 codebook [[2, 0], [0, 2]]. q = [1, 1, 0, 1], so pieces [1, 1] and [0, 1]. Table row 0: [2, 0]. Table row 1: ||[0, 1] - [2, 0]||^2 = 5 and ||[0, 1] - [0, 2]||^2 = 1, so [5, 1]. Codes [[1, 1], [0, 0], [1, 0]] score 0 + 1 = 1, 2 + 5 = 7 and 0 + 5 = 5. Rule: q_j = q[j * d/m : (j + 1) * d/m]; T[j, c] = ||q_j - codebooks[j, c]||^2; distance_i = sum over j of T[j, codes[i, j]]. Return squared distances, not their square roots. Used in: FAISS IVFPQ and billion-scale vector search.
Shapes and data flow
q (d,) -> (m, d/m) codebooks (m, K, d/m) -> table T (m, K) codes (n, m) -> gather T[j, codes[:, j]] -> sum -> (n,)