█

AI/TLDR

Buy me a coffee
Buy me a coffee

PyTorch Metric Learning

Losses, miners and testers for training embedding models in PyTorch

Embedding Models & InferenceOpen source
Language
Python
License
MIT
$pip install pytorch-metric-learning
IN SHORT

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.

Diagram of the library's modules: a Miner and a Loss, each fed by Distance, Regularizer and Reducer objects, turn embeddings and labels into a loss that feeds a Trainer, which uses a Sampler, HookContainer, Tester and AccuracyCalculator
The library's nine modules and how they connect in a train/test workflowPyTorch Metric Learning README ↗

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.

Diagram of a customised loss: miner indices select cells of a distance matrix, per-pair losses and per-element regularizer losses are computed, and a reducer averages the high-valued ones and adds them into a final loss
How a miner, distance, loss, regularizer and reducer combine into one loss valuePyTorch Metric Learning README ↗

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.

bashbash
pip install pytorch-metric-learning

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

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

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

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

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

ToolStarsWhat it does
Sentence Transformers★ 19.2kThe standard Python framework for loading, training, and computing embeddings with sentence and reranking models.
OpenCLIP★ 14.2kAn 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.3kLosses, miners and testers for training embedding models in PyTorch
EmbeddingGemma (Gemma)★ 5.8kGoogle 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.1kHugging Face's Rust-based server for deploying embedding, reranking, and sequence-classification models with high throughput on GPU or CPU.
text2vec★ 5kPython library for sentence embeddings and text similarity, implementing Word2Vec, BM25, Sentence-BERT, CoSENT and BGE with Chinese and multilingual models.
Infinity (Embeddings)★ 3kA high-throughput serving engine for text embeddings, rerankers, CLIP, and ColPali models, exposing an OpenAI-compatible API.
ColPali★ 2.8kA vision-language embedding model that indexes whole document page images for retrieval, avoiding the need to parse PDFs into text first.