Simple Algorithm
Machine Learning · Convergence · 26 min

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 MM.
  • Compare contrastive, triplet and softmax losses for deep metric learning, and explain negative mining and collapse.
  • Define cc-approximate near-neighbor search and locality-sensitive hashing, and derive the nρn^\rho query time with ρ=ln⁡(1/p1)/ln⁡(1/p2)\rho = \ln(1/p_1)/\ln(1/p_2).
  • 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 dM(x,z)=(x−z)⊤M(x−z)d_M(\mathbf x, \mathbf z) = \sqrt{(\mathbf x - \mathbf z)^\top M(\mathbf x - \mathbf z)} with M⪰0M \succeq 0 can be factored as M=L⊤LM = L^\top L, giving dM(x,z)=∥Lx−Lz∥d_M(\mathbf x, \mathbf z) = \norm{L\mathbf x - L\mathbf z}. Learning MM is learning a linear map, and a low-rank MM is a learned projection to fewer dimensions. Metric learning chooses MM 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 dM2d_M^2 over "similar" pairs, subject to the sum of (unsquared) distances over "dissimilar" pairs being at least 1, with M⪰0M \succeq 0. The constraint keeps the trivial M=0M = 0 out, and leaving it unsquared avoids a degenerate rank-one solution.

DerivationConvex in $M$, and solvable by projection
  1. ∥L(x−z)∥2=(x−z)⊤M(x−z)=Tr⁡(M (x−z)(x−z)⊤)\norm{L(\mathbf x - \mathbf z)}^2 = (\mathbf x - \mathbf z)^\top M(\mathbf x - \mathbf z) = \Tr\big(M\,(\mathbf x - \mathbf z)(\mathbf x - \mathbf z)^\top\big)

    Every squared distance is linear in M=L⊤LM = L^\top L, through a trace with a rank-one matrix:

  2. So the pull term is linear in MM and each push term is a hinge of an affine function of MM, which is convex. Over the convex cone {M⪰0}\{M \succeq 0\} this is a semidefinite program (with slack variables replacing the hinges): no spurious local minima, unlike the same objective written in LL.

  3. M←Π⪰0(M−η G),Π⪰0(∑iλivivi⊤)=∑imax⁡(λi,0) vivi⊤M \leftarrow \Pi_{\succeq 0}\big(M - \eta\,G\big),\qquad \Pi_{\succeq 0}\Big(\sum_i \lambda_i\mathbf v_i\mathbf v_i^\top\Big) = \sum_i \max(\lambda_i, 0)\,\mathbf v_i\mathbf v_i^\top

    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 fθf_\theta into Rm\R^m and measure D(x,z)=∥fθ(x)−fθ(z)∥D(\mathbf x, \mathbf z) = \norm{f_\theta(\mathbf x) - f_\theta(\mathbf z)}. The losses below train fθf_\theta so that neighbors in the embedding space share labels or identities.

LossFor one training unitNotes
Contrastive (pairs)s D2+(1−s) [m−D]+2s\,D^2 + (1 - s)\,[m - D]_+^2, with s=1s = 1 for a similar pairChopra, Hadsell & LeCun (2005); Hadsell, Chopra & LeCun (2006). Dissimilar pairs farther than mm cost nothing.
Triplet[D(a,p)2−D(a,n)2+α]+\big[D(a, p)^2 - D(a, n)^2 + \alpha\big]_+FaceNet (Schroff, Kalenichenko & Philbin, 2015): 128-dimensional embeddings on the unit sphere, anchor aa, positive pp, negative nn.
Softmax over negatives−log⁡esim(a,p)/τesim(a,p)/τ+∑jesim(a,nj)/τ-\log\dfrac{e^{\mathrm{sim}(a, p)/\tau}}{e^{\mathrm{sim}(a, p)/\tau} + \sum_{j} e^{\mathrm{sim}(a, n_j)/\tau}}One positive against many negatives, often with cosine similarity and temperature τ\tau; popularized for representation learning as InfoNCE (van den Oord, Li & Vinyals, 2018).
All three pull matching examples together and push others apart. The margin (mm or α\alpha) or the softmax normalization is essential: without a push term, mapping everything to one point, fθ≡constf_\theta \equiv \text{const}, would minimize the pull term. This failure is called collapse.

Mining. Most random triplets already satisfy D(a,n)2≥D(a,p)2+αD(a,n)^2 \ge D(a,p)^2 + \alpha, 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.

Check your understanding

During training with the triplet loss (margin α=0.2\alpha = 0.2), a triplet has D(a,p)2=0.3D(a,p)^2 = 0.3 and D(a,n)2=0.9D(a,n)^2 = 0.9. What does it contribute?

  1. A large gradient, because the negative is far away
  2. Nothing: 0.3−0.9+0.2<00.3 - 0.9 + 0.2 < 0, so the hinge is inactive
  3. A loss of 0.6
  4. It causes collapse
Show the answer

B. Nothing: 0.3−0.9+0.2<00.3 - 0.9 + 0.2 < 0, so the hinge is inactive

[0.3−0.9+0.2]+=[−0.4]+=0[0.3 - 0.9 + 0.2]_+ = [-0.4]_+ = 0: 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 nn or space exponential in dd when dd 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 H\mathcal H is (r,cr,p1,p2)(r, cr, p_1, p_2)-sensitive if, for hh drawn from H\mathcal H, P[h(x)=h(z)]≥p1P[h(\mathbf x) = h(\mathbf z)] \ge p_1 whenever d(x,z)≤rd(\mathbf x, \mathbf z) \le r and P[h(x)=h(z)]≤p2P[h(\mathbf x) = h(\mathbf z)] \le p_2 whenever d(x,z)≥crd(\mathbf x, \mathbf z) \ge cr, with p1>p2p_1 > p_2. One hash separates poorly; concatenating and repeating amplifies the gap.

DerivationAmplification: query time $n^ ho$
  1. k=⌈log⁡1/p2n⌉⟹n p2 k≤1k = \Big\lceil\log_{1/p_2} n\Big\rceil \quad\Longrightarrow\quad n\,p_2^{\,k} \le 1

    Concatenate kk independent hashes, g=(h1,…,hk)g = (h_1, \dots, h_k), so collision probabilities become p1kp_1^k and p2kp_2^k. Choose kk so that a far point collides with probability at most 1/n1/n; then each table holds, in expectation, at most one far point in the query's bucket:

  2. p1 k≈p1log⁡1/p2n=n−ρ,ρ=ln⁡(1/p1)ln⁡(1/p2)<1p_1^{\,k} \approx p_1^{\log_{1/p_2} n} = n^{-\rho},\qquad \rho = \frac{\ln(1/p_1)}{\ln(1/p_2)} < 1

    A near point then collides in one table with probability p1kp_1^k, which is about n−ρn^{-\rho} with the exponent below (up to a factor p1p_1 from rounding kk up):

  3. L=O(nρ) tables⟹query time O(nρ (k+d)),space O(n1+ρ+nd)L = \order{n^\rho}\ \text{tables}\qquad\Longrightarrow\qquad \text{query time } \order{n^\rho\,(k + d)},\quad \text{space } \order{n^{1+\rho} + nd}

    Build LL independent tables. The near point is missed by all of them with probability (1−p1k)L≤e−Lp1k(1 - p_1^k)^L \le e^{-Lp_1^k}, a constant once L≈nρ/p1L \approx n^\rho/p_1. A query hashes into LL buckets and checks O(L)\order{L} candidates: time about nρn^\rho hash-and-distance evaluations, and space O(n1+ρ)\order{n^{1+\rho}} plus the data.

For example, with p1=0.8p_1 = 0.8, p2=0.4p_2 = 0.4 and n=106n = 10^6: log⁡2.5106≈15.1\log_{2.5}10^6 \approx 15.1, so k=16k = 16; ρ=ln⁡1.25/ln⁡2.5≈0.24\rho = \ln 1.25/\ln 2.5 \approx 0.24, and nρ≈29n^\rho \approx 29. One table catches a near point with probability 0.816≈0.0280.8^{16} \approx 0.028, 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:

DistanceHash familyCollision probability or exponent
Hamming on {0,1}d\{0,1\}^dsample one coordinate (Indyk & Motwani, 1998)P=1−dist/dP = 1 - \text{dist}/d; ρ≤1/c\rho \le 1/c
Angle (cosine)h(x)=sign⁡(a⊤x)h(\mathbf x) = \sign(\mathbf a^\top\mathbf x), a\mathbf a Gaussian (Charikar, 2002)P=1−θ(x,z)/πP = 1 - \theta(\mathbf x, \mathbf z)/\pi
Euclideanh(x)=⌊(a⊤x+b)/w⌋h(\mathbf x) = \lfloor(\mathbf a^\top\mathbf x + b)/w\rfloor, a\mathbf a Gaussian, bb uniform on [0,w)[0, w) (Datar, Immorlica, Indyk & Mirrokni, 2004)ρ<1/c\rho < 1/c over a range of cc
Euclideanball carving in a random low-dimensional projection (Andoni & Indyk, 2008)ρ=1/c2+o(1)\rho = 1/c^2 + o(1), optimal for data-independent LSH
Euclideandata-dependent partitions (Andoni & Razenshteyn, 2015)ρ=1/(2c2−1)\rho = 1/(2c^2 - 1)
The Gaussian projection a⊤x\mathbf a^\top\mathbf x works for Euclidean distance because the Gaussian is 2-stable: a⊤(x−z)\mathbf a^\top(\mathbf x - \mathbf z) is distributed as ∥x−z∥\norm{\mathbf x - \mathbf z} times a standard normal. For the lower bound, O'Donnell, Wu and Zhou showed ρ≥1/c−o(1)\rho \ge 1/c - o(1) for Hamming space, which implies ρ≥1/c2−o(1)\rho \ge 1/c^2 - o(1) for Euclidean space, matching ball carving.
Predict before you look

Euclidean LSH at the optimal exponent ρ=1/c2\rho = 1/c^2 with c=2c = 2, over n=108n = 10^8 points. About how many hash tables, nρn^\rho, are needed?

Show the answer

100 tables

ρ=1/4\rho = 1/4, so nρ=(108)1/4=100n^\rho = (10^8)^{1/4} = 100: about 100 table lookups instead of 10810^8 distance computations. With bit sampling in Hamming space, ρ=1/c=1/2\rho = 1/c = 1/2 would need 10410^4.

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 mm sub-vectors, run k-means in each subspace with 256 centroids, and store each vector as mm one-byte centroid indices. A 128-dimensional float vector, 512 bytes, becomes 8 bytes: 64 times smaller, with an implicit codebook of 2568=264256^8 = 2^{64} centroids. For a query q\mathbf q, precompute the m×256m \times 256 distances from each query sub-vector to each centroid; the asymmetric distance to a stored vector is then a sum of mm 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 dMd_M with M=L⊤L⪰0M = L^\top L \succeq 0 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 MM 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 cc of the nearest.
  • LSH amplifies a hash family's gap by concatenation and repetition, giving query time nρn^\rho with ρ=ln⁡(1/p1)/ln⁡(1/p2)\rho = \ln(1/p_1)/\ln(1/p_2); for Euclidean distance the optimal data-independent exponent is 1/c21/c^2.
  • 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.

Question 1

Why do Mahalanobis metric-learning methods constrain M⪰0M \succeq 0?

  1. To make the optimization non-convex
  2. So that (x−z)⊤M(x−z)≥0(\mathbf x - \mathbf z)^\top M(\mathbf x - \mathbf z) \ge 0 for all pairs, making dMd_M a valid (pseudo)metric, equal to a Euclidean distance after the map LL with M=L⊤LM = L^\top L
  3. So that MM is diagonal
  4. Because positive definite matrices are faster to invert
Show the answer

B. So that (x−z)⊤M(x−z)≥0(\mathbf x - \mathbf z)^\top M(\mathbf x - \mathbf z) \ge 0 for all pairs, making dMd_M a valid (pseudo)metric, equal to a Euclidean distance after the map LL with M=L⊤LM = L^\top L

A negative eigenvalue would give some pairs a negative "squared distance". Positive semidefiniteness is exactly the condition for M=L⊤LM = L^\top L, so dMd_M is the Euclidean distance after a linear map. The PSD cone is convex, which keeps LMNN a convex program.

Question 2

A hash family has collision probability p1=0.9p_1 = 0.9 for near pairs and p2=0.5p_2 = 0.5 for far pairs. What is the LSH exponent ρ\rho, and what does it buy?

  1. ρ=0.9/0.5=1.8\rho = 0.9/0.5 = 1.8: queries cost more than a linear scan
  2. ρ=0.5\rho = 0.5: queries cost about n\sqrt n
  3. ρ=ln⁡(1/0.9)/ln⁡(1/0.5)≈0.15\rho = \ln(1/0.9)/\ln(1/0.5) \approx 0.15: queries cost about n0.15n^{0.15} hash-table probes
  4. ρ=0.4\rho = 0.4, the gap p1−p2p_1 - p_2
Show the answer

C. ρ=ln⁡(1/0.9)/ln⁡(1/0.5)≈0.15\rho = \ln(1/0.9)/\ln(1/0.5) \approx 0.15: queries cost about n0.15n^{0.15} hash-table probes

ρ=ln⁡(1/p1)/ln⁡(1/p2)=0.105/0.693≈0.15\rho = \ln(1/p_1)/\ln(1/p_2) = 0.105/0.693 \approx 0.15. Concatenating k=log⁡2nk = \log_2 n hashes makes far collisions rare, and about n0.15n^{0.15} tables recover near points with constant probability: for n=109n = 10^9, roughly 23 tables.

Question 3

With product quantization into m=16m = 16 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?

  1. A full dd-dimensional distance computation
  2. Decompressing the vector to floats first, then a distance computation
  3. 256 lookups
  4. 16 table lookups and additions
Show the answer

D. 16 table lookups and additions

Each stored vector is 16 centroid indices. The query's 16×25616 \times 256 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 dd.

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).