Approximate nearest neighbors: choose what work to skip
近似最近邻搜索
Train a coarse index and measure recall, probe cost and filter order.
ann-searchSearch fewer vectors, but know which answers were skipped
A database holds vectors representing documents, images or other objects. For each query, an exact scan can compare every eligible vector. That is a useful non-AI baseline: no learned routing and no index approximation. If the collection or request rate makes the scan too costly, approximate nearest-neighbor search (ANN) trades some accuracy for less work, less storage, or both.
Approximation can enter at different points. A coarse index skips regions; a graph skips paths; a quantizer changes the vectors used for scoring. These choices can be combined. The Faiss GPU paper distinguishes exact distance computation, exhaustive search over compressed representations, and IVFADC, which additionally restricts candidate lists. Faiss, section 2
The engineering problem is not “find the fastest index” in isolation. It is to meet a declared recall, latency, memory, update and filtering budget for a particular workload. This article builds a coarse index while preserving exact distances inside visited lists, so its misses come from candidate selection rather than compression.
Fix the reference before measuring approximation
For query q and stored vector x, squared Euclidean distance is:
Smaller is better. Squaring does not change Euclidean nearest-neighbor order, but squared distance itself does not satisfy the ordinary triangle inequality. Dot-product search instead chooses larger scores. Cosine removes length; for nonzero unit-normalized vectors its relationship to squared Euclidean distance is:
Thus normalized inner product and normalized Euclidean distance agree in order. Raw inner product and raw Euclidean distance need not. Faiss explicitly treats the comparison rule as part of the search problem. Faiss, section 2
Our coarse index learns L centroids by k-means and assigns each database vector to one nearest centroid. For a query, visit the p closest centroids and collect their lists. Let a(x) be a vector’s assigned cell and P_p(q) the selected cells:
A vector near a cell boundary can be close to the query while assigned to an unvisited cell. The product-quantization paper’s inverted-file search addresses this by visiting multiple coarse cells. Our version uses that coarse-selection idea without residual quantization or compressed scores. PQ, section IV.C
Let E_k be exact top k among the same eligible vectors, using the same metric and deterministic tie rule. Provided at least k eligible vectors exist, average recall over Q queries is:
This measures recovery of exact neighbors, not whether those neighbors satisfy a human information need. A theoretical approximate-neighbor guarantee may instead bound the returned distance by a factor such as 1+ε, with a stated probability. That is a different contract from empirical recall; our index provides no such worst-case approximation guarantee.
With exact list scoring, query work is roughly:
The three terms are centroid scoring, candidate scoring and this implementation’s full candidate sort. They exclude construction and filtering overhead. Balanced lists suggest about Np/L candidates, but actual list sizes can be uneven; count them rather than assuming balance.
An index learned from 160 vectors
Use Python 3.12 and NumPy 1.26. Seed 23 generates 160 four-dimensional database vectors and 24 separate query vectors. Eight centroids are trained on the database by at most 30 Lloyd updates. Initialization repeatedly chooses the point farthest from its nearest current centroid; empty clusters keep their old center. This is deterministic farthest-point initialization, not k-means++ sampling.
Every database vector is assigned once. We search with 1,2,4,8 probes and compare top five with a full scan. Distances tie by ascending vector ID. The demonstration accepts bounded finite coordinates and explicitly handles an empty allowed set.
"""Original inverted-file nearest-neighbor experiment using trained coarse centroids."""
import json
import numpy as np
def matrix(x):
x=np.asarray(x,dtype=float)
if x.ndim!=2 or not 1<=len(x)<=1000 or not 1<=x.shape[1]<=32 or not np.isfinite(x).all() or np.max(np.abs(x))>1e6:
raise ValueError('bounded finite matrix required')
return x
def distances(x,y):return np.sum((x[:,None,:]-y[None,:,:])**2,axis=2)
def fit_centroids(x,count=8,steps=30):
x=matrix(x)
if type(count) is not int or not 1<=count<=len(x) or type(steps) is not int or not 1<=steps<=100:
raise ValueError('valid cluster count and1..100 steps required')
# Deterministic farthest-point initialization; ties choose smallest input ID.
centers=[x[0].copy()]
while len(centers)<count:
nearest=distances(x,np.array(centers)).min(axis=1);centers.append(x[int(np.argmax(nearest))].copy())
centers=np.array(centers)
for _ in range(steps):
labels=distances(x,centers).argmin(axis=1)
updated=np.array([x[labels==i].mean(axis=0) if np.any(labels==i) else centers[i] for i in range(count)])
if np.array_equal(updated,centers):break
centers=updated
return centers,distances(x,centers).argmin(axis=1)
def rank(query,x,ids,k):
q=matrix(np.asarray(query,dtype=float).reshape(1,-1));x=matrix(x)
if q.shape[1]!=x.shape[1] or type(k) is not int or not 1<=k<=len(x):raise ValueError('matching dimensions and valid k required')
candidates=sorted(set(ids))
if any(type(i) is not int or i<0 or i>=len(x) for i in candidates):raise ValueError('candidate ID out of range')
if not candidates:return []
values=distances(q,x[candidates])[0]
return [candidates[j] for j in sorted(range(len(candidates)),key=lambda j:(float(values[j]),candidates[j]))[:k]]
def search(query,x,centers,labels,probes,k=5,allowed=None):
x=matrix(x);centers=matrix(centers);q=matrix(np.asarray(query,dtype=float).reshape(1,-1))
if type(probes) is not int or not 1<=probes<=len(centers):raise ValueError('probe count out of range')
if centers.shape[1]!=x.shape[1] or q.shape[1]!=x.shape[1] or np.shape(labels)!=(len(x),):raise ValueError('incompatible index')
ds=distances(q,centers)[0];cells=sorted(range(len(centers)),key=lambda i:(float(ds[i]),i))[:probes]
permitted=set(range(len(x))) if allowed is None else set(allowed)
ids=[i for i in range(len(x)) if labels[i] in cells and i in permitted]
return dict(ids=rank(query,x,ids,k),vector_distances=len(ids),centroid_distances=len(centers))
def fixture():
rng=np.random.default_rng(23)
x=rng.normal(size=(160,4));queries=rng.normal(size=(24,4))
return x,queries
def demo():
x,queries=fixture();centers,labels=fit_centroids(x);exact=[rank(q,x,range(len(x)),5) for q in queries];rows=[]
for probes in [1,2,4,8]:
runs=[search(q,x,centers,labels,probes) for q in queries]
rows.append(dict(probes=probes,recall_at5=float(np.mean([len(set(r['ids'])&set(e))/5 for r,e in zip(runs,exact)])),
mean_vector_distances=float(np.mean([r['vector_distances'] for r in runs])),centroid_distances=8))
q=queries[0];global_top=exact[0];allowed=set(range(len(x)))-set(global_top)
post=[i for i in global_top if i in allowed]
pre=search(q,x,centers,labels,8,5,allowed)['ids']
v=np.array([[100.,0.],[1.,1.]]);query=np.array([1.,1.]);cos=v@query/(np.linalg.norm(v,axis=1)*np.linalg.norm(query))
return dict(rows=rows,exact_vector_distances=len(x),filtered_post=post,filtered_pre=pre,
metric_example=dict(dot_winner=int(np.argmax(v@query)),cosine_winner=int(np.argmax(cos)),l2_winner=int(np.argmin(distances(query[None,:],v)[0]))),
scope='160 seeded synthetic vectors,24 separate queries; trained coarse IVF, exact distances within selected lists; no compression or timing claim.')
if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))
Average recall at five is 0.825,0.95,1,1. The corresponding mean numbers of scored database vectors are about 22.08,44.92,87.21,160; each query also compares eight centroids. Four probes happen to recover all exact neighbors in this fixture. That is an observed result on these queries, not a guarantee for future queries. Eight probes visit every list and must match the exact reference under the same metric and tie rule.
The metric counterexample uses query [1,1] and vectors [100,0], [1,1]. Raw dot product chooses the first; cosine and Euclidean distance choose the second. Comparing an inner-product index with an unnormalized Euclidean reference would blame the index for a mismatched task.
The filtering example deliberately excludes the unfiltered top five. Filtering that already-truncated list returns nothing, although five eligible neighbors can be found by searching the eligible population. This experiment uses all cells to isolate the filtering issue from ANN misses. It is a constructed eligibility rule, not a model of a real access-control system.
A benchmark needs the whole workload
Measure build time, query latency distributions, peak memory, retained index size and update behavior. This program counts actual candidate and centroid distance evaluations, but does not benchmark wall-clock speed against a production engine. Python containers, sorting, allocation and matrix operations affect latency. The coarse index still stores the original vectors; it has not earned the storage reduction of product quantization.
Choose index settings on development queries and evaluate once on a held-out query set. Include queries near partition boundaries, clustered data, duplicates and changes in vector distribution. Rebuilding on the database vectors is unsupervised index construction, but tuning probes on final evaluation queries would still leak evaluation information. Record the exact snapshot, metric, encoder version and allowed population.
Post-filtering a short unfiltered list can starve results. Pre-filtering, filtered traversal, oversampling and exact fallback are different designs with different costs. An exact fallback must enforce the same eligibility rule. When comparing graph search, inspect HNSW’s construction quality and search budget separately; a query parameter cannot be assumed to repair every poorly built index.
Check the target and the budget
- Why does probing every coarse cell recover exact neighbors in this implementation?
Answer: Every database vector belongs to one of those cells, candidate scores use the original vectors, and the metric and tie rule match the reference. This conclusion would not follow automatically if candidate scores were compressed approximations.
- For query [1,1], compute the two raw dot products in the metric example.
Answer: They are 100 and 2. The large vector wins inner product despite pointing away from the query direction. Its squared Euclidean distance is 99²+1=9802; the second vector has distance zero.
- Does an empty result after filtering the unfiltered top five prove that no eligible neighbor exists?
Answer: No. Eligible vectors may be ranked outside that prefix. Search the eligible population, enlarge the candidate budget or use an explicit fallback, and evaluate against an eligible exact reference.
- Design a fair comparison of one and four probes.
Answer: Freeze the same index, vector snapshot, metric, eligible set and query set. Report recall against exact top five, candidate and centroid distance counts, and measured latency distributions. Include build and storage costs separately, and avoid choosing the setting on the final test queries.
Separate candidate approximation from score approximation
Read the Faiss paper’s exact, ADC and IVFADC definitions together. The PQ paper then explains why visiting multiple inverted lists can repair boundary misses while leaving quantization error as a separate issue. The program here isolates the first mechanism; it reproduces neither the GPU kernels nor the papers’ billion-scale experiments.
Make a prediction, then check
Does filtering an unfiltered top-k list necessarily return the nearest k eligible vectors?
Learning objectives
- Compare approximate results with exact neighbors under the same metric and eligible set.
- Run the original example and diagnose its approximation error.
Prerequisites & connections
Explore related knowledge →References
- Billion-scale similarity search with GPUs — arXiv v1
Jeff Johnson; Matthijs Douze; Hervé Jégou · 2017 - Product Quantization for Nearest Neighbor Search — HAL inria-00514462v2
Hervé Jégou; Matthijs Douze; Cordelia Schmid · 2011
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF2/6: exact squared-L2, IVFADC coarse/fine quantizers, candidate lists and PQ lookup tables; no GPU kernels or speed claims reproduced. 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. 5 paired equations and four explained exercises. Checked trained coarse centroids, all-cell exactness, nested-pool recall, filtering order, metric mismatch and empty/duplicate cases; no compression or latency claim.
- Checked trained coarse centroids, all-cell exactness, nested-pool recall, filtering order, metric mismatch and empty/duplicate cases; no compression or latency claim.
- 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:
- 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.
- 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.
Related topics