Candidate generation scores a user vector against hundreds of millions of item vectors. Exact search is out of budget, so production indexes combine two ideas: an inverted file (IVF) that restricts the search to a few k-means cells, and product quantization (PQ) that compresses every vector to a few bytes so distances come from lookup tables. Implement both with NumPy, using squared Euclidean distance throughout.
lloyd(X, k, iters)
k rows of X as the initial centroids and iters full assign-then-update rounds. A cluster that loses all its points keeps its previous centroid. Return the (k, d) centroid array.build_ivf(X, centroids)
len(centroids) ascending index lists.train_pq(X, m, k, iters)
d dimensions into m equal contiguous sub-vectors and run lloyd on each with k codewords. Return the codebooks as an array of shape (m, k, d // m).encode_pq(X, codebooks)
(n, m) integer array of nearest-codeword indices per sub-vector.adc_distances(q, codes, codebooks)
(m, k) table of squared distances from each sub-vector of q to each codeword, then return the (n,) array of approximate squared distances by summing table entries selected by the codes.ivf_pq_search(q, codes, codebooks, centroids, ivf, nprobe, k)
nprobe cells whose centroids are closest to q, compute ADC distances for the vectors in those cells only, and return the k best global indices ascending by approximate distance (ties by lower index) as a Python list.recall_at_k(found, exact)
k indices present in found, rounded to 4 decimals.np.argmin over a (n, k) distance matrix gives the assignments; ((X[:, None, :] - C[None]) ** 2).sum(-1) is the matrix.m additions instead of d multiplications.