Learning Objectives
- Explain triplet, contrastive, and proxy-based metric learning losses and pick the right one for a given dataset
- Implement L2-normalisation and cosine similarity correctly and audit the difference between "same item" and "same class" retrieval
- Build a FAISS index, query it by text and by image, and report recall@K for a held-out query set
- Use DINOv2, CLIP, and SigLIP as off-the-shelf embedding backbones and know when each wins
The Problem
Retrieval is everywhere in production vision: duplicate detection, reverse image search, visual search ("find similar products"), face re-identification, person re-ID for surveillance, instance-level matching for e-commerce. The product question is always the same: "given this query image, rank my catalogue."
Two design decisions shape the whole system. The embedding — what model produces the vectors. The index — how to find nearest neighbours at scale. Both are commodity in 2026 (DINOv2 for the embedding, FAISS for the index), which raises the bar: the hard part is defining what counts as similar for your application, then shaping the embedding space so the distances match.
That shaping is metric learning. It is a small but high-leverage discipline.
The Concept
Retrieval at a glance
flowchart LR
Q["Query image<br/>or text"] --> ENC["Encoder"]
ENC --> EMB["Query embedding"]
EMB --> IDX["FAISS index"]
CAT["Catalogue images"] --> ENC2["Encoder (same)"] --> IDX_BUILD["Build index"]
IDX_BUILD --> IDX
IDX --> RANK["Top-k nearest<br/>by cosine / L2"]
RANK --> OUT["Ranked results"]
style ENC fill:#dbeafe,stroke:#2563eb
style IDX fill:#fef3c7,stroke:#d97706
style OUT fill:#dcfce7,stroke:#16a34a
The four loss families
| Loss | Requires | Pros | Cons |
|---|---|---|---|
| Contrastive | (anchor, positive) + negatives | Simple, works with any pair label | Slow to converge without many negatives |
| Triplet | (anchor, positive, negative) | Intuitive; direct margin control | Hard-triplet mining is expensive |
| NT-Xent / InfoNCE | Pairs + batch-mined negatives | Scales to large batches | Needs big batch or momentum queue |
| Proxy-based (ProxyNCA) | Class labels only | Fast, stable, no mining | Can overfit to proxies on small datasets |
For most production use cases, start with a pretrained backbone and only add a metric-learning fine-tune if the off-the-shelf embeddings underperform on your test set.
Triplet loss formally
L = max(0, ||f(a) - f(p)||^2 - ||f(a) - f(n)||^2 + margin)
Pull anchor a close to positive p, push it away from negative n, with a margin that ensures a gap. The three-image structure generalises to any similarity ordering.
Mining matters: easy triplets (n already far from a) contribute zero loss; only hard triplets teach the network. Semi-hard mining (n further than p but within margin) is the 2016 FaceNet recipe and still dominates.
Cosine similarity vs L2
Two metrics, two conventions:
- Cosine: angle between vectors. Requires L2-normalised embeddings.
- L2: Euclidean distance. Works on raw or normalised embeddings, but is usually paired with L2-normalised + squared L2.
For most modern nets the two are equivalent: ||a - b||^2 = 2 - 2 cos(a, b) when ||a|| = ||b|| = 1. Pick the convention that matches your embedding training; mixing them silently changes what "nearest" means.
Recall@K
The standard retrieval metric:
recall@K = fraction of queries where at least one correct match is in the top K results
Report recall@1, @5, @10 side by side. A recall@10 above 0.95 with recall@1 below 0.5 means the embedding space has the right structure but the ranking is noisy — try longer fine-tunes or a re-ranking step.
For duplicate detection, precision@K matters more because every false positive is a user-visible mistake. For visual search, recall@K is the product signal.
FAISS in one paragraph
Facebook AI Similarity Search. The de-facto library for nearest-neighbour search. Three index choices:
IndexFlatIP/IndexFlatL2— brute force, exact, no training. Use up to ~1M vectors.IndexIVFFlat— partition into K cells, search only the closest few cells. Approximate, fast, needs training data.IndexHNSW— graph-based, fastest for many queries, large index size.
For 100k vectors you probably want IndexFlatIP on cosine similarity. For 10M you want IndexIVFFlat. For 100M+ combined with product quantisation (IndexIVFPQ).
Instance-level vs category-level retrieval
Two very different problems with the same name:
- Category-level — "find cats in my catalogue." Class-conditional similarity; off-the-shelf CLIP / DINOv2 embeddings work well.
- Instance-level — "find this exact product in my catalogue." Needs fine-grained discrimination between visually similar objects of the same class; off-the-shelf embeddings under-perform; fine-tuning with metric learning matters.
Always ask which one you are solving before picking a model.
Interactive figure coming later.
Build It
Step 1: Triplet loss
import torch
import torch.nn.functional as F
def triplet_loss(anchor, positive, negative, margin=0.2):
d_ap = F.pairwise_distance(anchor, positive, p=2)
d_an = F.pairwise_distance(anchor, negative, p=2)
return F.relu(d_ap - d_an + margin).mean()
One line. Works on L2-normalised or raw embeddings.
Step 2: Semi-hard mining
Given a batch of embeddings and labels, find the hardest semi-hard negative for each anchor.
def semi_hard_negatives(emb, labels, margin=0.2):
dist = torch.cdist(emb, emb)
same_class = labels[:, None] == labels[None, :]
diff_class = ~same_class
N = emb.size(0)
positives = dist.clone()
positives[~same_class] = float("-inf")
positives.fill_diagonal_(float("-inf"))
pos_idx = positives.argmax(dim=1)
semi_hard = dist.clone()
semi_hard[same_class] = float("inf")
d_ap = dist[torch.arange(N), pos_idx].unsqueeze(1)
semi_hard[dist <= d_ap] = float("inf")
neg_idx = semi_hard.argmin(dim=1)
fallback_mask = semi_hard[torch.arange(N), neg_idx] == float("inf")
if fallback_mask.any():
hardest = dist.clone()
hardest[same_class] = float("inf")
neg_idx = torch.where(fallback_mask, hardest.argmin(dim=1), neg_idx)
return pos_idx, neg_idx
Each anchor gets the hardest positive in-class and a semi-hard negative that is further than the positive but within margin.
Step 3: Recall@K
def recall_at_k(query_emb, gallery_emb, query_labels, gallery_labels, k=1):
sim = query_emb @ gallery_emb.T
_, top_k = sim.topk(k, dim=-1)
matches = (gallery_labels[top_k] == query_labels[:, None]).any(dim=-1)
return matches.float().mean().item()
Top-k by inner product on L2-normalised embeddings equals top-k by cosine. Report the mean proportion of queries with at least one correct neighbour.
Step 4: Putting it together
import torch
import torch.nn as nn
from torch.optim import Adam
class Encoder(nn.Module):
def __init__(self, in_dim=128, emb_dim=64):
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, 128), nn.ReLU(),
nn.Linear(128, emb_dim),
)
def forward(self, x):
return F.normalize(self.net(x), dim=-1)
torch.manual_seed(0)
num_classes = 6
protos = F.normalize(torch.randn(num_classes, 128), dim=-1)
def sample_batch(bs=32):
labels = torch.randint(0, num_classes, (bs,))
x = protos[labels] + 0.15 * torch.randn(bs, 128)
return x, labels
enc = Encoder()
opt = Adam(enc.parameters(), lr=3e-3)
for step in range(200):
x, y = sample_batch(32)
emb = enc(x)
pos_idx, neg_idx = semi_hard_negatives(emb, y)
loss = triplet_loss(emb, emb[pos_idx], emb[neg_idx])
opt.zero_grad(); loss.backward(); opt.step()
After a few hundred steps the embedding clusters form one cluster per class.
Use It
Production stacks in 2026:
- DINOv2 + FAISS — general-purpose visual retrieval. Works off-the-shelf.
- CLIP + FAISS — when queries are text.
- Fine-tuned DINOv2 + FAISS — instance-level retrieval, face re-ID, fashion, e-commerce.
- Milvus / Weaviate / Qdrant — managed vector DB wrappers around FAISS or HNSW.
For SOTA instance retrieval, the recipe is: DINOv2 backbone, add an embedding head, fine-tune with a triplet or InfoNCE loss on instance-labelled pairs, index in FAISS.
Ship It
This lesson produces:
outputs/prompt-retrieval-loss-picker.md— a prompt that picks triplet / InfoNCE / ProxyNCA for a given retrieval problem.outputs/skill-recall-at-k-runner.md— a skill that writes a clean evaluation harness for recall@K with train/val/gallery splits and proper data contract.
Exercises
- (Easy) Run the toy example above. Plot the embeddings with PCA before and after training to see the six clusters form.
- (Medium) Add a ProxyNCA loss implementation: one learned "proxy" per class, standard cross-entropy on cosine similarity. Compare convergence speed vs triplet loss on the toy data.
- (Hard) Take 1,000 ImageNet validation images, embed with DINOv2 via HuggingFace, build a FAISS flat index, and report recall@{1, 5, 10} against the same images as queries (should be 1.0) and against a held-out split with ImageNet labels as ground truth.
Key Terms
| Term | What people say | What it actually means |
|---|---|---|
| Metric learning | "Shape the space" | Training an encoder so distances in its output space reflect a target similarity |
| Triplet loss | "Pull and push" | L = max(0, d(a, p) - d(a, n) + margin); the canonical metric-learning loss |
| Semi-hard mining | "Useful negatives" | Negatives further from the anchor than the positive but within margin; empirically the most informative |
| Proxy-based loss | "Class prototypes" | One learned proxy per class; cross-entropy over similarity-to-proxies; no pair mining |
| Recall@K | "Top-K hit rate" | Fraction of queries with at least one correct result in the top K |
| Instance retrieval | "Find this exact thing" | Fine-grained matching; off-the-shelf features usually underperform |
| FAISS | "The NN library" | Facebook's nearest-neighbour library; supports exact and approximate indexes |
| HNSW | "Graph index" | Hierarchical navigable small world; fast approximate NN with small memory overhead |
Further Reading
- FaceNet: A Unified Embedding for Face Recognition (Schroff et al., 2015) — the triplet loss / semi-hard mining paper
- In Defense of the Triplet Loss for Person Re-Identification (Hermans et al., 2017) — practical guide to triplet fine-tuning
- FAISS documentation — every index, every trade-off
- SMoT: Metric Learning Taxonomy (Kim et al., 2021) — survey of modern losses and their connections
Code
Take-away files
prompt-retrieval-loss-picker.md
--- name: prompt-retrieval-loss-picker description: Pick triplet / InfoNCE / ProxyNCA for a given retrieval problem phase: 4 lesson: 20 --- You are a metric-learning loss selector. ## Inputs - `task_level`: instance | category - `labelled_pairs`: pair (anchor, positive) | triplet (a, p, n) | class_labels_only - `dataset_size`: small (<10k) | medium (10k-100k) | large (>100k) - `batch_size`: small (<128) | medium (128-512) | large (>512) ## Decision 1. `labelled_pairs == class_labels_only` -> **ProxyNCA / ProxyAnchor**. One proxy per class; no mining. 2. `labelled_pairs == pair` and `batch_size in [medium, large]` -> **InfoNCE / NT-Xent**. In-batch negatives scale with batch. 3. `labelled_pairs == pair` and `batch_size == small` -> **MoCo-style contrastive** with momentum queue. 4. `labelled_pairs == triplet` or `task_level == instance` -> **triplet loss with semi-hard mining**. ## Output ``` [loss] name: triplet | InfoNCE | ProxyNCA | ProxyAnchor margin: <float, if triplet> temperature: <float, if InfoNCE> embedding_dim: typical 128-768 [training] batch: <int> optimiser: Adam / SGD with weight decay lr: <float> epochs: <int> [gotchas] - always L2-normalise embeddings - watch for dead proxies in ProxyNCA on small datasets - semi-hard mining requires labels within the batch ``` ## Rules - Never combine two metric-learning losses unless you have strong evidence they are complementary; usually one wins. - For `task_level == category`, strongly prefer off-the-shelf DINOv2 / CLIP before training a custom loss. - For `dataset_size < 5k`, recommend starting from a pretrained backbone and training only the embedding head to avoid overfitting.
skill-recall-at-k-runner.md
---
name: skill-recall-at-k-runner
description: Write a clean evaluation harness for recall@K with train/val/gallery splits and proper data contract
version: 1.0.0
phase: 4
lesson: 20
tags: [retrieval, evaluation, recall, faiss]
---
# Recall@K Runner
Turn a folder of query and gallery images plus labels into a reproducible recall@K number.
## When to use
- First retrieval benchmark for a new backbone.
- Tracking embedding quality across fine-tune epochs.
- Comparing two retrieval systems on the same dataset.
## Inputs
- `query_images`: list of paths.
- `gallery_images`: list of paths (query may or may not overlap).
- `query_labels`, `gallery_labels`: class or instance IDs.
- `encoder_fn`: callable `image -> embedding` (precomputed or live).
- `ks`: list like `[1, 5, 10]`.
## Steps
1. Encode every gallery image once. Save as numpy array.
2. Encode every query image.
3. L2-normalise both sets of embeddings.
4. For each query, compute similarity against all gallery items.
5. Sort descending, take top max(ks).
6. For each K, check whether any of the top-K gallery items shares the query's label.
7. Report `recall@K = fraction of queries that had at least one correct neighbour in top K`.
## Output template
```python
import numpy as np
from sklearn.preprocessing import normalize
def encode_all(images, encoder_fn, batch=32):
out = []
for i in range(0, len(images), batch):
embs = encoder_fn(images[i:i + batch])
out.append(embs)
return np.concatenate(out)
def recall_at_k(query_emb, gallery_emb, q_labels, g_labels,
ks=(1, 5, 10), query_ids=None, gallery_ids=None):
if len(query_emb) == 0 or len(gallery_emb) == 0:
return {f"recall@{k}": 0.0 for k in ks}
g_label_set = set(g_labels.tolist())
keep = np.array([lbl in g_label_set for lbl in q_labels])
if not keep.any():
return {f"recall@{k}": 0.0 for k in ks}
q_emb_f = query_emb[keep]
q_lab_f = q_labels[keep]
q_id_f = query_ids[keep] if query_ids is not None else None
q = normalize(q_emb_f)
g = normalize(gallery_emb)
sims = q @ g.T
if q_id_f is not None and gallery_ids is not None:
self_mask = q_id_f[:, None] == gallery_ids[None, :]
sims = np.where(self_mask, -np.inf, sims)
top_k_max = min(max(ks), g.shape[0])
if top_k_max <= 0:
return {f"recall@{k}": 0.0 for k in ks}
top = np.argpartition(-sims, top_k_max - 1, axis=1)[:, :top_k_max]
sorted_top = np.take_along_axis(
top, np.argsort(-sims[np.arange(len(q))[:, None], top], axis=1), axis=1
)
out = {}
for k in ks:
k_eff = min(k, top_k_max)
hits = np.any(g_labels[sorted_top[:, :k_eff]] == q_lab_f[:, None], axis=1)
out[f"recall@{k}"] = float(hits.mean())
return out
def evaluate(query_images, query_labels, gallery_images, gallery_labels, encoder_fn, ks=(1, 5, 10)):
q_emb = encode_all(query_images, encoder_fn)
g_emb = encode_all(gallery_images, encoder_fn)
return recall_at_k(q_emb, g_emb, np.array(query_labels), np.array(gallery_labels), ks)
```
## Report
```
[evaluation]
num queries: <int>
num gallery: <int>
embedding_dim: <int>
[recall]
recall@1: <float>
recall@5: <float>
recall@10: <float>
```
## Rules
- Normalise embeddings before computing similarity; FAISS IndexFlatIP on normalised vectors equals cosine.
- When a query's ground-truth label is absent from the gallery, exclude it; otherwise recall is trivially capped below 1.
- If query and gallery overlap, exclude the query itself from its own top-K or you measure self-similarity, not retrieval.
- For `num_queries > 10,000`, batch the similarity matmul to avoid OOM.