3.x 版本要求 Python 3.12+、PyTorch 2.14.0+、NumPy 2.5.3+,旧环境需先升级;从 2.x 升级需按迁移指南改名;Faiss 检索后端和 NMI/AMI 聚类指标需另装 [faiss]、[clustering] 可选依赖。
pytorch-metric-learning
KevinMusgraveMIT活跃维护基于 PyTorch 的度量学习库,提供对比损失、难例挖掘、采样器和检索指标,用来训练和评估相似度搜索所需的嵌入向量。
Train and evaluate embeddings for similarity search with PyTorch. Includes contrastive losses, hard example mining, samplers, and retrieval metrics.
uv pip install pytorch-metric-learning
pip install pytorch-metric-learningREADME 未说明具体硬件要求;核心包只依赖 PyTorch 和 NumPy,未提及显存或 GPU 型号。
PyTorch 度量学习组件库,用可组合的损失、挖掘器和采样器训练嵌入模型
基于 PyTorch 的度量学习库,提供对比损失、难例挖掘、采样器和检索指标,用来训练和评估相似度搜索所需的嵌入向量。
核心能力
- 提供对比损失等可组合的 PyTorch 损失函数
- 内置难例挖掘器、距离、reducer 和正则化器
- 提供采样器与检索评估指标,用于相似度检索
- 组件可直接嵌入自有训练循环,无需改写框架
- 可选 Faiss 检索后端与聚类指标扩展
容易踩的坑
- v3.0.2最新正式版2026-11-08 · 2026-11-08 06:03 UTC
Version 3.0.2
Version 3.0.2 fixes low-precision reductions and regularization, small-batch regularization, and NumPy sampler inputs. Public signatures and minimum supported Python, PyTorch, and NumPy versions are unchanged.
Numerical fixes
ClassWeightedReducermultiplies and averages float16 and bfloat16 losses in float32, then returns the scalar in the input dtype. Stored weights keep their precision until multiplication, avoiding premature underflow, overflow, and rounding (#775).CenterInvariantRegularizerwidens float16 and bfloat16 inputs before computing norms and squared deviations. Its reduced scalar remains float32 for those inputs so a later regularization weight can scale a large finite penalty. This corrects loss values and gradients affected by low-precision rounding or overflow; float32 and float64 behavior and the configurable Lp norm are preserved (#776).RegularFaceRegularizerreturns differentiable zero for empty and singleton inputs. It continues to validate its inputs and retains the existing nearest-neighbor objective for two or more centers (#777).
Sampler inputs
Samplers preserve categorical and hashable NumPy label values and accept views with negative strides or non-native byte order. Invalid label dimensions and hierarchy columns produce descriptive errors at construction (#778).
Benchmark tooling
Capacity searches report a batch size only after successful confirmation. They return no verified capacity when every probe or a confirmation fails, preserve the confirmation failure status, and correctly refine brackets whose starting batch is not aligned to the search granularity. Invalid search settings are rejected before launching a probe (#779). Previously published benchmark measurements are unchanged.
Contributors
Thanks to @Afloat16 for all five fixes. The original contribution commits are preserved in this release.
- v3.0.12026-11-01 · 2026-11-01 06:53 UTC
查看更新说明
Version 3.0.1
Version 3.0.1 fixes a large time and memory regression in low-precision Euclidean distances, including the default distance used by Contrastive and TripletMargin losses. Public signatures and minimum supported Python, PyTorch, and NumPy versions are unchanged. No migration is required.
Low-precision Euclidean distances
In v3.0.0, float16 and BF16 matrices always used the direct
torch.cdistkernel to preserve nearby-point accuracy. Its CUDA backward pass can allocate memory proportional to queries × references × embedding dimensions.Large eager Euclidean calls now use float32 matrix evaluation when a numerical screen shows that it is safe. Self comparisons reuse prepared inputs and keep their diagonal exactly zero. Nearby or duplicate points, other norms, small matrices, compiled execution, CUDA graph capture, and reduced float32 matmul precision retain the accurate direct calculation. Global precision settings are unchanged.
The improvement is measured on standard-normal inputs; clustered training embeddings can still take the slower direct path. Values and gradients are checked for random, nearby, duplicate, and mixed-scale float16/BF16 inputs.
Measured impact
The fix was measured at commit
32bcfa8, whose numerical code is included unchanged in this release. Each successful timing configuration averages 900 forward/backward pairs across three fresh processes after warmup.At BF16 batch 2,048, 128 dimensions, and four samples per class:
GPU Loss v3.0.0 → fix time per pair (ms) v3.0.0 → fix peak allocation (MiB) RTX 5090 Contrastive 13.3 → 2.23 2,118 → 356 RTX 5090 Batch-hard + Triplet 16.4 → 1.38 2,118 → 151 A100 Contrastive 23.4 → 6.32 2,118 → 308 A100 Batch-hard + Triplet 30.0 → 5.47 2,118 → 103 These are loss/miner measurements, excluding an encoder, optimizer, and data loading. Peak allocation is total PyTorch tensor allocation, not total device usage. The fix does not beat v2.9.0 in every case: RTX 5090 batch-hard triplet still takes 25.6% longer in this configuration. See the complete comparison and limitations for process ranges, controls, numerical checks, and reproduction instructions.
Broader benchmark coverage
The new five-GPU benchmark report compares released v3.0.0 with v2.9.0 on RTX 4090, RTX 5090, L40S, A100, and H100 systems. It covers seven common losses plus batch-hard triplet mining, absolute forward and backward time, total and incremental peak memory, and verified batch limits. CSV tables, SVG scaling charts, raw measurements, and hardware/source provenance are included. Those original release results remain separate from the two-GPU fix measurements.
- v3.0.02026-10-31 · 2026-10-31 19:36 UTC
查看更新说明
3.0.0
Version 3 focuses the library on composable metric-learning components used from ordinary PyTorch code. It removes training and evaluation orchestration, makes tensor and extension contracts explicit and typed, and corrects numerical, distributed, and retrieval behavior. It adds losses, evaluation tools, and memory controls.
It is a clean break from version 2, with no compatibility aliases. Look up any version 2 name in the migration guide. This page summarizes the changes since 2.9.0, and each release candidate's notes hold the complete list: rc1, rc2, rc3, rc4, and rc5.
Requirements
- Python 3.12 or newer, with PyTorch 2.14.0 and NumPy 2.5.3 as tested minimums.
- Optional extras:
faissfor the Faiss retrieval backends, andclusteringfor NMI and AMI. Thewith-hooks,with-hooks-cpu,docs, anddevextras are removed. - The package is typed and ships
py.typed.pytorch_metric_learning.__version__is removed; useimportlib.metadata.version("pytorch-metric-learning").
Breaking changes
- Removed: trainers, testers, logging presets,
InferenceModel, thedatasetspackage, and recorded statistics. The training and evaluation recipes show the equivalent PyTorch code. - Package layout: retrieval lives in
evaluation, distributed wrappers indistributed, andutils.indexingreplacesutils.loss_and_miner_utils. Every other part ofutilsis private. See the public API. - Tensor contracts:
ref_emb=Nonemeans a query set compared with itself, and passingref_embdescribes a separate set. Miners return named tuples, labels must be on the embeddings' device, and modules are never moved or cast duringforward. - Extension: losses, miners, and regularizers extend
torch.nn.Moduledirectly and take keyword-only options. Custom losses implementcompute_loss, custom reducers implementelement_reduction, and classification losses derive fromBaseProxyLoss. - Arguments: many options are renamed, and the migration guide lists each one.
- Samplers:
MPerClassSampleryields whole batches, so pass it asDataLoader(dataset, batch_sampler=sampler). It takesbatch_sizeandnum_batches. Seeded sequences differ from version 2.
Changed defaults
DotProductSimilarity()computes a plain dot product. Passnormalize_embeddings=Truefor the previous behavior.TripletMarginLossdefaults tomargin=0.2. Passmargin=0.05for the previous default.AccuracyCalculatorsearches with exact PyTorch squared Euclidean distance on the input device instead of Faiss.- Several losses exclude anchors that lack the pairs their term needs, so means average
only anchors that have them. Miner weights changed in
ProxyAnchorLossandProxyNCALoss, and the rc1 notes give the details.
New features
Losses:
- CenterLoss
- CentroidTripletLoss, rewritten for version 3, from an or
- v3.0.0rc5pre-release2026-10-31 · 2026-10-31 16:21 UTC
查看更新说明
3.0.0rc5
This is the fifth release candidate for version 3.0.0. The 3.0.0rc1 notes describe version 3 as a whole, and the migration guide covers version 2 names.
New features
- Compatible losses and miners accept a precomputed distance matrix through the
keyword-only
matargument. One matrix can serve a miner and several losses, and a matrix can depend on per-batch metadata that a distance does not receive, without changing the distance object. Losses reject a matrix with no autograd graph, nothing is cached, and unsupported modules raise. See precomputed distance matrices (#211, #697). - Every miner accepts
tuples_per_anchor, which keeps a random subset of each anchor's mined tuples, without replacement. See bounding the output (#193). losses.anchor_batched_backwardcomputes the gradient of a tuple loss in chunks of anchors. Its result equals a full-batchbackward(), and losses whose objective does not split by anchor are rejected. Seeanchor_batched_backward(#586).losses.DecoupledContrastiveLossimplements DCL and DCLW from Decoupled Contrastive Learning by Yeh et al. See DecoupledContrastiveLoss (#375).losses.SelectivelyContrastiveTripletLossimplements the loss from Hard Negative Examples are Hard, but Useful by Xuan et al. See SelectivelyContrastiveTripletLoss (#287).regularizers.SphericalEmbeddingRegularizerimplements the spherical embedding constraint from Deep Metric Learning with Spherical Embedding by Zhang et al. It differs fromCenterInvariantRegularizer, which compares squared norms. See SphericalEmbeddingRegularizer (#346).losses.CentroidTripletLossreturns, rewritten for version 3. It implements On the Unreasonable Effectiveness of Centroids in Image Retrieval by Wieczorek et al. Classes of different sizes now work, a class with one embedding provides a negative centroid instead of raising, andswapandtriplets_per_anchorare gone. The default distance is now the paper's squared Euclidean distance. Thanks to cwkeam, who contributed the original implementation, and pgrosjean, who diagnosed the failure. See CentroidTripletLoss (#451).losses.GE2ELossimplements both variants of Generalized End-to-End Loss for Speaker Verification by Wan et al., with the anchor left out of its own class's
- Compatible losses and miners accept a precomputed distance matrix through the
keyword-only
- v3.0.0rc4pre-release2026-10-31 · 2026-10-31 03:01 UTC
查看更新说明
3.0.0rc4
This is the fourth release candidate for version 3.0.0. It adds evaluation utilities and fixed-pair sampling. The 3.0.0rc1 notes describe version 3 as a whole, and the migration guide covers version 2 names.
New features
evaluation.select_thresholdchooses a match/no-match threshold from validation scores, boolean labels, and an explicit metric, and the result works directly withMatchFinder. Built-in metrics arematch_accuracy,match_balanced_accuracy, andmatch_f1. See threshold selection (#733).samplers.FixedSetOfPairsdraws a fixed, balanced set of positive and negative pairs and yields whole batches, so a pair is never split. The sampler documentation includes a completeDataLoader-to-loss loop (#259).evaluation.ndcg_metricregisters NDCG from a graded relevance function, normalized by the ideal ranking over the whole reference set. Multi-column labels can drive NDCG and binary metrics in one calculator, and each keeps its own rule for which queries count. See graded relevance and NDCG (#339).
Evaluation changes
RetrievalInputsgains the required fieldsreference_labelsandref_includes_query. Only code that constructsRetrievalInputsdirectly needs to change.RetrievalMetricgainsexclude_lone_queries, defaultTrue. A metric that sets it toFalsedecides through NaN which queries count.
Fixes
AccuracyCalculatorno longer raisesTypeErrorwith MPS inputs. The search stays on MPS and metric arithmetic runs on CPU, because MPS has no float64.
Documentation
- The evaluation recipe adds
nearest-centroid accuracy, composed from
AccuracyCalculator(#205). - Measuring performance adds benchmark cases that compare separate distance computation with one reused matrix.
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。

Train embedding models with composable PyTorch losses, hard-example miners, distances, reducers, and regularizers. Use them in your own training loop for retrieval, clustering, recognition, or learning from pairs and triplets.
Docs for humans · Documentation source
Install
Install from PyPI with uv or pip:
uv pip install pytorch-metric-learning
pip install pytorch-metric-learning
The core package needs only PyTorch and NumPy. Optional extras add the Faiss
retrieval backend, pytorch-metric-learning[faiss], and scikit-learn for the
NMI/AMI clustering metrics, pytorch-metric-learning[clustering].
Version 3 requires Python 3.12 or newer, PyTorch 2.14.0 or newer, and NumPy 2.5.3 or newer. Upgrading from version 2? Read the release notes and look up old names in the migration guide. The version 2 documentation remains available.
A minimal training step
Your model produces one embedding per input. Equal labels identify positive pairs; different labels identify negatives. Here a contrastive loss pulls positive pairs together and pushes negatives apart:
import torch
from pytorch_metric_learning import losses
torch.manual_seed(17)
model = torch.nn.Linear(8, 4)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
data = torch.randn(12, 8)
labels = torch.arange(4).repeat_interleave(3)
loss_func = losses.ContrastiveLoss(neg_margin=1.4)
optimizer.zero_grad(set_to_none=True)
loss = loss_func(model(data), labels)
loss.backward()
optimizer.step()
The model returns embeddings shaped (12, 4) and labels have shape (12,).
This loss L2-normalizes embeddings by default. It averages active positive and
negative pair penalties separately, then adds them. See the
contrastive-loss contract for distances,
margins, and reduction options.
Learn more
The documentation starts with a task index and a concepts overview of embeddings, tuples, distances, loss terms, and reducers. Every component page states its signature, defaults, tensor contract, and paper, and the recipes show complete training and evaluation code.
Contributing
See CONTRIBUTING.md. Thanks to all contributors, upstream projects, and supporters.
Citing this library
If you use this library in your research, please cite the PyTorch Metric Learning paper:
@article{Musgrave2020PyTorchML,
title={PyTorch Metric Learning},
author={Kevin Musgrave and Serge J. Belongie and Ser-Nam Lim},
journal={ArXiv},
year={2020},
volume={abs/2008.09164}
}