Product quantization: many vectors, a few small codebooks
乘积量化
Train subspace codebooks, compare ADC and SDC, and account for real storage.
product-quantizationStore a combination of addresses instead of every coordinate
Suppose a vector has eight coordinates. Instead of storing all eight numbers for every item, split the vector into smaller blocks and represent each block by the ID of a nearby learned center. Reconstructing an item means looking up those centers and concatenating them. This loses information, but it can make the stored codes much smaller.
A single codebook with many high-dimensional centers is expensive. Product quantization (PQ) combines several small codebooks implicitly: every choice of one center per block defines a possible reconstructed vector, without storing every combination. Jégou, Douze and Schmid describe both the representation and nearest-neighbor scoring from these codes. The journal article is from 2011; the cited HAL v2 deposit is dated 2013-05-22, a different event. PQ, cover and section II
This article studies representation error and lookup distances. Approximate nearest-neighbor search separately studies skipping candidates. Compression can be used even when every stored code is searched.
The codebook is a Cartesian product
Assume D is divisible by the number of blocks m. Write the vector and its reconstruction as concatenated blocks:
Each block has K centers trained by k-means on that block’s training coordinates. Encode by nearest center; ties in this implementation choose the smallest center ID:
The Cartesian product has K^m possible reconstructions, yet the codebooks contain only mK block centers. Their total scalar count is KD, because each block center has D/m coordinates. The squared reconstruction error is the sum of the squared block errors. Learning the blocks independently therefore minimizes an additive distortion objective, though Lloyd iterations only find a local solution and depend on initialization. PQ, section II.B
Fixed-width subcodes and uncompressed codebooks require:
Here b is bytes per stored center coordinate. These figures exclude IDs, container overhead and padding. Eight centers need three bits per subcode in principle. A NumPy uint8 still occupies eight bits; getting three-bit storage requires explicit bit packing. More blocks at fixed K increase the code length, so an improvement from that change is not a fixed-bit-rate comparison.
Asymmetric distance computation (ADC) keeps query q uncompressed and uses reconstructed database vectors. Precompute a table of query-block distances to every center, then sum one entry per block:
The lookup equals distance to the reconstruction, not necessarily distance to the original x. Symmetric distance computation (SDC) also quantizes the query, with code b_j:
ADC avoids query quantization error; it does not guarantee a better ranking for every query. Both variants are described in the original paper. Faiss’s IVFADC additionally quantizes residuals within coarse lists; our example uses plain PQ and scans every code. PQ, section III.A Faiss, sections 2 and 5.2
The reverse triangle inequality bounds error in Euclidean distance:
This is not the same bound for squared distances. Even a small distance error can swap two nearly tied neighbors. Reconstruction distortion and neighbor recall are related measurements, not interchangeable ones. PQ, section III.B
Train, encode, look up and check the bill
Use Python 3.12 and NumPy 1.26. Seed 37 generates a common eight-dimensional linear transform and separate training, database and query arrays of sizes 256,128,20. These synthetic arrays share a distribution but contain different sampled rows. Train eight centers per block, using deterministic farthest-point initialization and at most 30 Lloyd updates. Empty clusters keep their old center.
Compare m=1,2,4,8. Codes use uint8, codebooks and original vectors use NumPy float64, and no bits are packed. We inspect exact top five, ADC top five and SDC top five with ascending-ID tie rules. Every code is scored; there is no candidate pruning to obscure the compression effect.
"""Original product quantizer with Lloyd training, ADC and SDC; no Faiss dependency."""
import json
import math
import numpy as np
def matrix(x):
x=np.asarray(x,dtype=float)
if x.ndim!=2 or not 1<=len(x)<=2000 or not 1<=x.shape[1]<=32 or not np.isfinite(x).all() or np.max(np.abs(x))>1e6:
raise ValueError('bounded nonempty matrix required')
return x
def squared(x,y):return ((x[:,None,:]-y[None,:,:])**2).sum(axis=2)
def fit(x,parts=2,centroids=8,steps=30):
x=matrix(x);n,d=x.shape
if type(parts) is not int or parts<1 or d%parts or type(centroids) is not int or not 2<=centroids<=min(256,n):
raise ValueError('parts must divide dimension;2..min(256,N) centroids')
if type(steps) is not int or not 1<=steps<=100:raise ValueError('steps1..100 required')
books=[];histories=[]
for block in np.split(x,parts,axis=1):
c=[block[0].copy()]
while len(c)<centroids:c.append(block[int(np.argmax(squared(block,np.array(c)).min(axis=1)))].copy())
c=np.array(c);history=[]
for _ in range(steps):
dist=squared(block,c);labels=dist.argmin(axis=1);history.append(float(dist.min(axis=1).mean()))
updated=np.array([block[labels==j].mean(axis=0) if np.any(labels==j) else c[j] for j in range(centroids)])
if np.array_equal(updated,c):break
c=updated
history.append(float(squared(block,c).min(axis=1).mean()));books.append(c);histories.append(history)
return np.array(books),histories
def encode(x,books):
x=matrix(x)
if books.ndim!=3 or x.shape[1]!=books.shape[0]*books.shape[2] or not np.isfinite(books).all():raise ValueError('compatible finite codebooks required')
return np.column_stack([squared(block,c).argmin(axis=1) for block,c in zip(np.split(x,len(books),axis=1),books)]).astype(np.uint8)
def validate_codes(codes,books):
codes=np.asarray(codes)
if books.ndim!=3 or not np.isfinite(books).all() or np.max(np.abs(books))>1e6:raise ValueError('bounded finite codebooks required')
if codes.ndim!=2 or codes.shape[1]!=len(books) or not np.issubdtype(codes.dtype,np.integer) or np.any(codes<0) or np.any(codes>=books.shape[1]):raise ValueError('valid integer codes required')
return codes
def decode(codes,books):
codes=validate_codes(codes,books)
return np.concatenate([books[j,codes[:,j]] for j in range(len(books))],axis=1)
def adc(query,codes,books,symmetric=False):
q=matrix(np.asarray(query,dtype=float).reshape(1,-1));codes=validate_codes(codes,books)
if q.shape[1]!=books.shape[0]*books.shape[2]:raise ValueError('query dimension mismatch')
if symmetric:q=decode(encode(q,books),books)
table=np.array([squared(block,c)[0] for block,c in zip(np.split(q,len(books),axis=1),books)])
return table[np.arange(len(books))[None,:],codes].sum(axis=1)
def rank(values,k=5):return sorted(range(len(values)),key=lambda i:(float(values[i]),i))[:k]
def fixture():
rng=np.random.default_rng(37);mix=rng.normal(size=(8,8))
train=rng.normal(size=(256,8))@mix
database=rng.normal(size=(128,8))@mix
queries=rng.normal(size=(20,8))@mix
return train,database,queries
def demo():
train,database,queries=fixture();exact=[rank(squared(q[None,:],database)[0]) for q in queries];rows=[]
for parts in [1,2,4,8]:
books,_=fit(train,parts);codes=encode(database,books);reconstructed=decode(codes,books)
adc_scores=[adc(q,codes,books) for q in queries];sdc_scores=[adc(q,codes,books,True) for q in queries]
rows.append(dict(parts=parts,ideal_bits=parts*3,code_bytes=int(codes.nbytes),codebook_bytes=int(books.nbytes),
reconstruction_mse=float(np.mean(np.sum((database-reconstructed)**2,axis=1))),
adc_recall_at5=float(np.mean([len(set(rank(v))&set(e))/5 for v,e in zip(adc_scores,exact)])),
sdc_recall_at5=float(np.mean([len(set(rank(v))&set(e))/5 for v,e in zip(sdc_scores,exact)])),
table_max_error=float(max(np.max(np.abs(v-squared(q[None,:],reconstructed)[0])) for q,v in zip(queries,adc_scores)))))
# Euclidean (not squared-distance) error is bounded by reconstruction error.
bounds=np.linalg.norm(database-reconstructed,axis=1)
worst=max(float(np.max(np.abs(np.sqrt(squared(q[None,:],database)[0])-np.sqrt(adc(q,codes,books)))-bounds)) for q in queries)
return dict(rows=rows,original_database_bytes=int(database.nbytes),euclidean_bound_max_excess=worst,
scope='Separate seeded synthetic training256/database128/query20 vectors;8 centroids per subspace; uint8 codes are not bit-packed; NumPy float64 codebooks.')
if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))
The original database occupies 8,192 array bytes. Codes occupy 128,256,512,1,024 bytes as m increases, plus 512 codebook bytes in each case. Ideal code lengths are 3,6,12,24 bits per vector, but the actual code arrays use 8,16,32,64 bits per vector. Report both rather than presenting theoretical bits as allocated memory.
ADC recall at five is 0.20,0.36,0.56,0.77, while SDC recall is 0.20,0.30,0.44,0.66. Mean squared reconstruction error—mean of each vector’s summed squared coordinate errors—is about 36.28,28.84,13.48,3.18. More blocks help this fixture while spending more bits. These results do not establish the best partition or bit allocation on another dataset.
Lookup distances agree with explicit distances to decoded vectors within floating-point tolerance. The executable checks also verify a two-block hand example, non-increasing Lloyd distortion, additive block error and the Euclidean error bound. ADC’s input validation checks codes without reconstructing the entire database; a regression check guards that distinction.
Small codes do not remove every cost
For a query, building distance tables costs O(KD) arithmetic and O(mK) storage; scanning N codes then needs O(Nm) lookups and additions before top-k selection. This implementation validates O(Nm) code entries on each call and sorts all N scores in O(N log N). A production engine can organize validation and selection differently. The teaching code makes no wall-clock speed claim.
Training and encoding also cost time, and codebooks must accompany the codes. IDs, alignment, metadata, index structures and retained originals add memory. If exact reranking needs the original vectors, count that storage too. A new codebook cannot decode old codes unless their version mapping is preserved.
Coordinate blocks impose a partition; correlations across blocks can hurt quantization. Rotations, optimized partitions, residual quantization and other code lengths are alternatives to investigate, not features implemented here. Faiss combines a coarse quantizer and residual PQ for IVFADC and discusses GPU-specific layouts; neither GPU kernels nor that full index are reproduced here. Faiss, sections 2 and 5.2
Select code size and training settings on development data, then measure held-out neighbor recall, distortion, latency and total retained memory. A code collision creates tied approximate distances, and exact reranking cannot recover a true neighbor omitted from the candidate shortlist. Keep metric and tie conventions identical when comparing methods.
Count bits, then inspect the neighbors
- With D=8, m=4 and K=8, how many reconstructions and stored center scalars are possible?
Answer: There are 8⁴=4,096 combinations, but only KD=64 stored center scalars. The representation assembles combinations from separate block codebooks rather than storing 4,096 full vectors.
- Four three-bit subcodes require how much space theoretically, and how much in this uint8 implementation?
Answer: The fixed-width bit payload is 12 bits per vector. Four uint8 entries occupy 32 bits, or four bytes. Bit packing is required to approach the theoretical payload; array and row alignment may add further overhead.
- Is ADC lookup exact or approximate?
Answer: It is exact, up to floating-point arithmetic, for distance from the uncompressed query to the reconstructed database vector. It approximates distance to the original vector. Those are different targets.
- Reconstruction error is small but recall is poor. What would you inspect?
Answer: Inspect near ties, code collisions, the chosen coordinate blocks and the query distribution. Small perturbations can reorder very close neighbors. Compare exact and approximate distances on failed queries, then evaluate a larger code or exact reranking under the same total memory and candidate budget.
Compression and candidate selection are separate approximations
The original PQ paper derives the codebook product, ADC/SDC and a distance-error analysis before adding inverted files. The Faiss paper shows how those pieces enter a large-scale GPU design. Reading them in that order helps distinguish what a compact representation changes from what a candidate-pruning algorithm skips.
Make a prediction, then check
Eight centroids need3 bits per subcode. Does NumPy uint8 store that subcode in3 bits?
Learning objectives
- Derive product-code distances and distinguish theoretical bits from stored array bytes.
- Run the original example and diagnose its approximation error.
Prerequisites & connections
Explore related knowledge →References
- Product Quantization for Nearest Neighbor Search — HAL inria-00514462v2
Hervé Jégou; Matthijs Douze; Cordelia Schmid · 2011 - Billion-scale similarity search with GPUs — arXiv v1
Jeff Johnson; Matthijs Douze; Hervé Jégou · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Read HAL cover: journal2011, archive deposit2013-05-22. Viewed physical PDF3/4/5/6/8: Lloyd conditions, product codebook, ADC/SDC, Euclidean error bound and inverted lists. No benchmark reproduction. Viewed physical PDF2/6: exact squared-L2, IVFADC coarse/fine quantizers, candidate lists and PQ lookup tables; no GPU kernels or speed claims reproduced. 6 paired equations and four explained exercises. Checked hand ADC/SDC, lookup against reconstruction, nonincreasing Lloyd distortion, additive block error, Euclidean bound and actual uint8/codebook bytes; ADC validation cannot decode the database.
- Checked hand ADC/SDC, lookup against reconstruction, nonincreasing Lloyd distortion, additive block error, Euclidean bound and actual uint8/codebook bytes; ADC validation cannot decode the database.
- Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- Product Quantization for Nearest Neighbor Search — HAL inria-00514462v2 · Read HAL cover: journal2011, archive deposit2013-05-22. Viewed physical PDF3/4/5/6/8: Lloyd conditions, product codebook, ADC/SDC, Euclidean error bound and inverted lists. No benchmark reproduction.
- Billion-scale similarity search with GPUs — arXiv v1 · Viewed physical PDF2/6: exact squared-L2, IVFADC coarse/fine quantizers, candidate lists and PQ lookup tables; no GPU kernels or speed claims reproduced.
Related topics