Metric Learning & Fast Neighbor Search
Learned distances, trees, hashing and graph-based search.
Finding similar images, products or passages, including the retrieval step that feeds documents to language models, is nearest-neighbor search over billions of vectors in a space whose distances were learned. Two questions decide whether it works: is the distance right, and can the neighbors be found without comparing the query with everything? This lesson answers both, from Mahalanobis metrics and triplet losses to hashing, quantization and search graphs.
What you’ll learn
- Formulate Mahalanobis metric learning over positive semidefinite matrices, and show that the LMNN objective is convex in .
- Compare contrastive, triplet and softmax losses for deep metric learning, and explain negative mining and collapse.
- Define -approximate near-neighbor search and locality-sensitive hashing, and derive the query time with .
- State the known LSH exponents and lower bounds for Hamming, angular and Euclidean distances.
- Explain product quantization with asymmetric distances and graph-based search, and what theory does and does not guarantee about them.
Learning a Mahalanobis metric
A Mahalanobis distance with can be factored as , giving . Learning is learning a linear map, and a low-rank is a learned projection to fewer dimensions. Metric learning chooses from supervision: pairs that should be close, pairs that should be far, or class labels.
Xing, Ng, Jordan and Russell (2002) posed it as a convex program: minimize the sum of squared distances over "similar" pairs, subject to the sum of (unsquared) distances over "dissimilar" pairs being at least 1, with . The constraint keeps the trivial out, and leaving it unsquared avoids a degenerate rank-one solution.
Every squared distance is linear in , through a trace with a rank-one matrix:
So the pull term is linear in and each push term is a hinge of an affine function of , which is convex. Over the convex cone this is a semidefinite program (with slack variables replacing the hinges): no spurious local minima, unlike the same objective written in .
A simple solver takes subgradient steps and projects back onto the cone. The Frobenius-norm projection keeps the eigenvectors and clips negative eigenvalues to zero:
Other formulations regularize toward a prior metric, for example with the LogDet divergence in information-theoretic metric learning (Davis, Kulis, Jain, Sra & Dhillon, 2007). All linear metrics share one limit: they can stretch and rotate the space, but not bend it.
Deep metric learning
Replace the linear map with a neural network into and measure . The losses below train so that neighbors in the embedding space share labels or identities.
| Loss | For one training unit | Notes |
|---|---|---|
| Contrastive (pairs) | , with for a similar pair | Chopra, Hadsell & LeCun (2005); Hadsell, Chopra & LeCun (2006). Dissimilar pairs farther than cost nothing. |
| Triplet | FaceNet (Schroff, Kalenichenko & Philbin, 2015): 128-dimensional embeddings on the unit sphere, anchor , positive , negative . | |
| Softmax over negatives | One positive against many negatives, often with cosine similarity and temperature ; popularized for representation learning as InfoNCE (van den Oord, Li & Vinyals, 2018). |
Mining. Most random triplets already satisfy , so their loss and gradient are zero. Training therefore searches for informative examples. FaceNet used semi-hard negatives, farther from the anchor than the positive but still inside the margin; the hardest negatives can be mislabeled or degenerate and destabilize training.
A reality check. Many papers reported large gains from new metric-learning losses. Musgrave, Belongie and Lim (2020) re-ran them with matched architectures, data augmentation and hyperparameter tuning and found the improvements over classic contrastive and triplet losses to be marginal at best. Fair comparison is hard: the evaluation protocol often matters as much as the loss.
Where the neighbors live. Retrieval must compute neighbors in the full embedding space, or in a compressed code designed to preserve them, never in a low-dimensional picture of it.
During training with the triplet loss (margin ), a triplet has and . What does it contribute?
- A large gradient, because the negative is far away
- Nothing: , so the hinge is inactive
- A loss of 0.6
- It causes collapse
Show the answer
B. Nothing: , so the hinge is inactive
: the constraint is already met with room to spare, so the triplet has zero loss and zero gradient. Batches full of such easy triplets teach nothing, which is why mining matters.
Exact search hits a wall
With a good metric in hand, the remaining problem is speed. Tree indexes such as the k-d tree (Bentley, 1975) prune whole regions and answer exact queries quickly in low dimensions, but in high dimensions the pruning test almost never fires; for uniformly spread data, Weber, Schek and Blott (1998) found partitioning indexes slower than a plain scan beyond about ten dimensions. Every known exact method needs either query time close to linear in or space exponential in when is large. Practice therefore relaxes the problem.
Locality-sensitive hashing
Locality-sensitive hashing (LSH; Indyk & Motwani, 1998) uses random hash functions that make near points collide more often than far ones. A family is -sensitive if, for drawn from , whenever and whenever , with . One hash separates poorly; concatenating and repeating amplifies the gap.
Concatenate independent hashes, , so collision probabilities become and . Choose so that a far point collides with probability at most ; then each table holds, in expectation, at most one far point in the query's bucket:
A near point then collides in one table with probability , which is about with the exponent below (up to a factor from rounding up):
Build independent tables. The near point is missed by all of them with probability , a constant once . A query hashes into buckets and checks candidates: time about hash-and-distance evaluations, and space plus the data.
For example, with , and : , so ; , and . One table catches a near point with probability , so 29 tables find it with probability about 0.56, and 87 tables with about 0.92. The exponent depends on the distance and the hash family:
| Distance | Hash family | Collision probability or exponent |
|---|---|---|
| Hamming on | sample one coordinate (Indyk & Motwani, 1998) | ; |
| Angle (cosine) | , Gaussian (Charikar, 2002) | |
| Euclidean | , Gaussian, uniform on (Datar, Immorlica, Indyk & Mirrokni, 2004) | over a range of |
| Euclidean | ball carving in a random low-dimensional projection (Andoni & Indyk, 2008) | , optimal for data-independent LSH |
| Euclidean | data-dependent partitions (Andoni & Razenshteyn, 2015) |
Euclidean LSH at the optimal exponent with , over points. About how many hash tables, , are needed?
Show the answer
100 tables
, so : about 100 table lookups instead of distance computations. With bit sampling in Hamming space, would need .
Quantization and graphs: what large systems use
LSH has the cleanest guarantees, but its many tables cost memory. Billion-scale systems mostly rely on two other ideas.
Product quantization (Jégou, Douze & Schmid, 2011). Split each vector into sub-vectors, run k-means in each subspace with 256 centroids, and store each vector as one-byte centroid indices. A 128-dimensional float vector, 512 bytes, becomes 8 bytes: 64 times smaller, with an implicit codebook of centroids. For a query , precompute the distances from each query sub-vector to each centroid; the asymmetric distance to a stored vector is then a sum of table lookups. An inverted file over a coarse quantizer restricts the scan to a few lists of candidates.
Graph-based search. Link each point to some of its near neighbors and answer a query by greedy descent: move to whichever neighbor is closest to the query until no neighbor improves. Hierarchical navigable small-world graphs (HNSW; Malkov & Yashunin, 2020) add layers: each point's top layer is drawn with exponentially decaying probability, so the upper layers are sparse long-range "express" graphs and the search refines downward, keeping a beam of candidates at the bottom. As of the mid-2020s, graph methods are among the fastest at high recall in public benchmarks, and HNSW is built into many vector databases.
Retrieval in modern systems. Dense retrieval encodes queries and documents with neural networks and answers a query by approximate maximum-inner-product or nearest-neighbor search over the document vectors, as in dense passage retrieval (Karpukhin et al., 2020). Retrieval-augmented generation (Lewis et al., 2020) attaches such a dense vector index of Wikipedia, accessed by a neural retriever, to a sequence-to-sequence model. Libraries such as FAISS (Johnson, Douze & Jégou, 2021) implement quantization and graph indexes on CPUs and GPUs. Normalizing embeddings to unit length makes inner product, cosine and Euclidean rankings agree, which is why so many systems do it.
Key takeaways
- A Mahalanobis metric with is a Euclidean distance after a learned linear map; LMNN pulls target neighbors in and pushes impostors out by a margin, a convex problem in solved over the PSD cone.
- Deep metric learning trains an embedding with contrastive, triplet or softmax losses; push terms prevent collapse, mining finds informative examples, and fair comparisons show many newer losses barely beat the classics.
- Exact search in high dimension is essentially linear time; approximate search returns a point within factor of the nearest.
- LSH amplifies a hash family's gap by concatenation and repetition, giving query time with ; for Euclidean distance the optimal data-independent exponent is .
- Large systems use product quantization (compact codes, distances by table lookup) and graph search (HNSW); graphs are fast in practice but have few worst-case guarantees.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why do Mahalanobis metric-learning methods constrain ?
- To make the optimization non-convex
- So that for all pairs, making a valid (pseudo)metric, equal to a Euclidean distance after the map with
- So that is diagonal
- Because positive definite matrices are faster to invert
Show the answer
B. So that for all pairs, making a valid (pseudo)metric, equal to a Euclidean distance after the map with
A negative eigenvalue would give some pairs a negative "squared distance". Positive semidefiniteness is exactly the condition for , so is the Euclidean distance after a linear map. The PSD cone is convex, which keeps LMNN a convex program.
A hash family has collision probability for near pairs and for far pairs. What is the LSH exponent , and what does it buy?
- : queries cost more than a linear scan
- : queries cost about
- : queries cost about hash-table probes
- , the gap
Show the answer
C. : queries cost about hash-table probes
. Concatenating hashes makes far collisions rare, and about tables recover near points with constant probability: for , roughly 23 tables.
With product quantization into sub-vectors of 256 centroids each, what does computing the asymmetric distance from a query to one stored vector cost, after the query's tables are built?
- A full -dimensional distance computation
- Decompressing the vector to floats first, then a distance computation
- 256 lookups
- 16 table lookups and additions
Show the answer
D. 16 table lookups and additions
Each stored vector is 16 centroid indices. The query's table holds the squared distance from each query sub-vector to each centroid, so the distance estimate is the sum of 16 looked-up entries, independent of .
Further reading
- K. Q. Weinberger & L. K. Saul, "Distance metric learning for large margin nearest neighbor classification," Journal of Machine Learning Research 10, 207–244 (2009).
- F. Schroff, D. Kalenichenko & J. Philbin, "FaceNet: a unified embedding for face recognition and clustering," CVPR, 815–823 (2015).
- P. Indyk & R. Motwani, "Approximate nearest neighbors: towards removing the curse of dimensionality," STOC, 604–613 (1998).
- H. Jégou, M. Douze & C. Schmid, "Product quantization for nearest neighbor search," IEEE Transactions on Pattern Analysis and Machine Intelligence 33(1), 117–128 (2011).
- Yu. A. Malkov & D. A. Yashunin, "Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs," IEEE Transactions on Pattern Analysis and Machine Intelligence 42(4), 824–836 (2020).