#370Product Quantization (PQ) Encode + ADCHardNeural NetworksLLMsML System DesignAsked atMeta · Google · Cohere
Product Quantization (PQ) Encode + ADC
Background
Product Quantization (PQ) splits each vector into subspaces, learns centroids per subspace (typically → 8-bit codes), and encodes each db vector as small codes. Asymmetric Distance Computation (ADC) then approximates the distance from query to db vector via precomputed lookup-table sums. Foundation of IVF-PQ and FAISS.
Problem statement
Implement two functions:
pq_encode(vecs, codebooks)— for each row, split into subspaces; encode each subspace as the index of its nearest centroid. Return shape(n, M)of ints.pq_distance(query, codes, codebooks)— build the lookup table . Return per-db-row distance .
codebooks has shape .
Input
vecs—np.ndarrayshape .codebooks—np.ndarrayshape .query— 1-Dnp.ndarrayof length .codes—np.ndarrayshape $(n, M)`, integer codes.
Output
pq_encodereturnsnp.ndarrayshape $(n, M)ofint`.pq_distancereturnsnp.ndarrayof length offloat.
Examples
Example 1 — code shape
Input: vecs (10, 8); codebooks (4, 16, 2) # M=4, K=16, d/M=2
Output: codes shape (10, 4)
Example 2 — ADC = 0 when query exactly matches a centroid-aligned db row
Input: db row built by concatenating centroid 0 from each subspace
Output: pq_distance(that row's vec, codes, codebooks)[0] ≈ 0
Example 3 — ADC is non-negative
Input: any random query and codes
Output: all distances ≥ 0
Constraints
- must be divisible by .
- Distances are squared L2 (not Euclidean) — same ordering, cheaper to compute.
- Returns
np.ndarray.
Notes
- Why asymmetric. "Asymmetric" because the query is not quantised; only the db is. Symmetric distance computation quantises both, which is faster but loses recall.
- IVF-PQ. PQ is typically combined with IVF: IVF picks candidate cells, PQ scores candidates within those cells. Billion-scale search on a single machine.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: encoding selects the nearest centroid per subspace
- •Reference case: ADC equals the reference per-subspace distance sum
- •Sample centroid-aligned row has zero asymmetric distance