What is PyTorch Metric Learning?
PyTorch Metric Learning is an MIT-licensed Python library for training models whose output is an embedding — a vector where similar items land close together and different ones far apart. It sits in the Embedding Models & Inference category of the Retrieval & Knowledge (RAG) tools and is open-source, written in Python and licensed MIT.
Overview
PyTorch Metric Learning is an MIT-licensed Python library for training models whose output is an embedding — a vector where similar items land close together and different ones far apart. That is the training side of image retrieval, face and person re-identification, deduplication and contrastive or self-supervised representation learning. The library began during its author Kevin Musgrave's internship at Facebook AI and is described in a 2020 arXiv paper by Musgrave, Serge Belongie and Ser-Nam Lim.

It is organised as nine modules that work on their own or together: losses, miners, distances, reducers, regularizers, samplers, trainers, testers and an AccuracyCalculator. The core pattern drops into an ordinary PyTorch training loop: compute embeddings with your model, pass them with their labels to a loss such as TripletMarginLoss, and call backward. A miner can find the hardest positive and negative pairs in the batch first, and the library converts between pairs and triplets automatically when a loss needs the other form.

Losses are built from swappable parts. A distance object (Euclidean, or cosine similarity) computes the distance matrix, a regularizer adds per-embedding penalties, and a reducer decides how per-pair and per-element losses become one number — for example by keeping only losses above a threshold. A SelfSupervisedLoss wrapper turns any tuple loss into a self-supervised one by comparing embeddings with their augmented views, and CrossBatchMemory supports MoCo-style queues. Release 2.9.0, published to PyPI on 17 August 2025, added SmoothAPLoss; a Datasets module downloads common benchmarks such as CUB-200, Cars196, iNaturalist 2018 and Stanford Online Products.
What it does
- A large set of metric-learning losses, from TripletMarginLoss and contrastive losses to SupConLoss, CircleLoss, ArcFace variants and SmoothAPLoss
- Miners such as MultiSimilarityMiner and BatchEasyHardMiner that select hard pairs or triplets inside each batch
- Composable losses: swap the distance, add an embedding regularizer, or change the reducer without writing a new loss
- SelfSupervisedLoss wrapper and CrossBatchMemory for self-supervised and MoCo-style training
- Trainers, testers and an AccuracyCalculator (k-NN and clustering metrics, mean reciprocal rank) for complete train/evaluate workflows
- A Datasets module for CUB-200-2011, Cars196, iNaturalist 2018 and Stanford Online Products, plus Colab example notebooks
Getting started
Versions from 0.9.90 on require torch 1.6 or newer; the other dependencies are numpy, scikit-learn, tqdm and torchvision.
Install
From PyPI, or from conda-forge with `conda install -c conda-forge pytorch-metric-learning`. The `[with-hooks]` extra (or `[with-hooks-cpu]`) adds faiss, record-keeper and tensorboard for the testing and logging modules.
pip install pytorch-metric-learningAdd a loss to your training loop
Embeddings have shape (N, embedding_size) and labels shape (N). TripletMarginLoss builds every valid triplet in the batch from the labels.
from pytorch_metric_learning import losses
loss_func = losses.TripletMarginLoss()
for i, (data, labels) in enumerate(dataloader):
optimizer.zero_grad()
embeddings = model(data)
loss = loss_func(embeddings, labels)
loss.backward()
optimizer.step()Mine hard pairs
A miner picks the pairs it judges most difficult and passes them to the loss.
from pytorch_metric_learning import miners, losses
miner = miners.MultiSimilarityMiner()
loss_func = losses.TripletMarginLoss()
hard_pairs = miner(embeddings, labels)
loss = loss_func(embeddings, labels, hard_pairs)Customise the loss
Use cosine similarity instead of Euclidean distance, discard triplet losses above 0.3 and L2-regularise the embeddings.
from pytorch_metric_learning.distances import CosineSimilarity
from pytorch_metric_learning.reducers import ThresholdReducer
from pytorch_metric_learning.regularizers import LpRegularizer
from pytorch_metric_learning import losses
loss_func = losses.TripletMarginLoss(
distance=CosineSimilarity(),
reducer=ThresholdReducer(high=0.3),
embedding_regularizer=LpRegularizer(),
)Go self-supervised
Wrap a tuple loss and compare each batch with an augmented view of itself — no labels needed.
from pytorch_metric_learning.losses import SelfSupervisedLoss, TripletMarginLoss
loss_func = SelfSupervisedLoss(TripletMarginLoss())
embeddings = model(data)
augmented = model(augment(data))
loss = loss_func(embeddings, augmented)Commands and code are distilled from the project's own documentation — always check the official repo for the latest.
When to use it
- Training an image-retrieval or product-search model where similar items must be nearest neighbours
- Face, person or vehicle re-identification with ArcFace-style or triplet losses
- Self-supervised pre-training of an encoder from augmented views of unlabelled data
- Comparing metric-learning losses and miners on standard benchmarks with the built-in datasets and AccuracyCalculator
How PyTorch Metric Learning compares
PyTorch Metric Learning alongside other open-source embedding models & inference tools AI/TLDR tracks, ranked by GitHub stars.
| Tool | Stars | What it does |
|---|---|---|
| Sentence Transformers | ★ 19.2k | The standard Python framework for loading, training, and computing embeddings with sentence and reranking models. |
| OpenCLIP | ★ 14.2k | An open implementation of CLIP for training and running image-text embedding models, with a large catalogue of pretrained checkpoints for zero-shot classification and retrieval. |
| PyTorch Metric Learning | ★ 6.3k | Losses, miners and testers for training embedding models in PyTorch |
| EmbeddingGemma (Gemma) | ★ 5.8k | Google DeepMind's Gemma repo, home to EmbeddingGemma, a 308M multilingual embedding model small enough to run on-device for RAG and semantic search. |
| Text Embeddings Inference (TEI) | ★ 5.1k | Hugging Face's Rust-based server for deploying embedding, reranking, and sequence-classification models with high throughput on GPU or CPU. |
| text2vec | ★ 5k | Python library for sentence embeddings and text similarity, implementing Word2Vec, BM25, Sentence-BERT, CoSENT and BGE with Chinese and multilingual models. |
| Infinity (Embeddings) | ★ 3k | A high-throughput serving engine for text embeddings, rerankers, CLIP, and ColPali models, exposing an OpenAI-compatible API. |
| ColPali | ★ 2.8k | A vision-language embedding model that indexes whole document page images for retrieval, avoiding the need to parse PDFs into text first. |
