pytorch-metric-learning

KevinMusgraveMIT活跃维护

基于 PyTorch 的度量学习库,提供对比损失、难例挖掘、采样器和检索指标,用来训练和评估相似度搜索所需的嵌入向量。

Train and evaluate embeddings for similarity search with PyTorch. Includes contrastive losses, hard example mining, samplers, and retrieval metrics.

v3.0.2发布于 2026-11-08 06:03 UTC6,342star663fork同步于 2026-11-10 17:35 UTC

怎么上手

由 README 提炼,执行前请确认
uv pip install pytorch-metric-learning
pip install pytorch-metric-learning
硬件要求按 README 说明

README 未说明具体硬件要求;核心包只依赖 PyTorch 和 NumPy,未提及显存或 GPU 型号。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

PyTorch 度量学习组件库,用可组合的损失、挖掘器和采样器训练嵌入模型

基于 PyTorch 的度量学习库,提供对比损失、难例挖掘、采样器和检索指标,用来训练和评估相似度搜索所需的嵌入向量。

核心能力

  • 提供对比损失等可组合的 PyTorch 损失函数
  • 内置难例挖掘器、距离、reducer 和正则化器
  • 提供采样器与检索评估指标,用于相似度检索
  • 组件可直接嵌入自有训练循环,无需改写框架
  • 可选 Faiss 检索后端与聚类指标扩展

容易踩的坑

3.x 版本要求 Python 3.12+、PyTorch 2.14.0+、NumPy 2.5.3+,旧环境需先升级;从 2.x 升级需按迁移指南改名;Faiss 检索后端和 NMI/AMI 聚类指标需另装 [faiss]、[clustering] 可选依赖。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v3.0.2
  1. 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

    • ClassWeightedReducer multiplies 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).
    • CenterInvariantRegularizer widens 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).
    • RegularFaceRegularizer returns 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.

  2. 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.cdist kernel 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:

    GPULossv3.0.0 → fix time per pair (ms)v3.0.0 → fix peak allocation (MiB)
    RTX 5090Contrastive13.3 → 2.232,118 → 356
    RTX 5090Batch-hard + Triplet16.4 → 1.382,118 → 151
    A100Contrastive23.4 → 6.322,118 → 308
    A100Batch-hard + Triplet30.0 → 5.472,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.

  3. 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: faiss for the Faiss retrieval backends, and clustering for NMI and AMI. The with-hooks, with-hooks-cpu, docs, and dev extras are removed.
    • The package is typed and ships py.typed. pytorch_metric_learning.__version__ is removed; use importlib.metadata.version("pytorch-metric-learning").

    Breaking changes

    • Removed: trainers, testers, logging presets, InferenceModel, the datasets package, and recorded statistics. The training and evaluation recipes show the equivalent PyTorch code.
    • Package layout: retrieval lives in evaluation, distributed wrappers in distributed, and utils.indexing replaces utils.loss_and_miner_utils. Every other part of utils is private. See the public API.
    • Tensor contracts: ref_emb=None means a query set compared with itself, and passing ref_emb describes a separate set. Miners return named tuples, labels must be on the embeddings' device, and modules are never moved or cast during forward.
    • Extension: losses, miners, and regularizers extend torch.nn.Module directly and take keyword-only options. Custom losses implement compute_loss, custom reducers implement element_reduction, and classification losses derive from BaseProxyLoss.
    • Arguments: many options are renamed, and the migration guide lists each one.
    • Samplers: MPerClassSampler yields whole batches, so pass it as DataLoader(dataset, batch_sampler=sampler). It takes batch_size and num_batches. Seeded sequences differ from version 2.

    Changed defaults

    • DotProductSimilarity() computes a plain dot product. Pass normalize_embeddings=True for the previous behavior.
    • TripletMarginLoss defaults to margin=0.2. Pass margin=0.05 for the previous default.
    • AccuracyCalculator searches 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 ProxyAnchorLoss and ProxyNCALoss, and the rc1 notes give the details.

    New features

    Losses:

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

  5. 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_threshold chooses a match/no-match threshold from validation scores, boolean labels, and an explicit metric, and the result works directly with MatchFinder. Built-in metrics are match_accuracy, match_balanced_accuracy, and match_f1. See threshold selection (#733).
    • samplers.FixedSetOfPairs draws a fixed, balanced set of positive and negative pairs and yields whole batches, so a pair is never split. The sampler documentation includes a complete DataLoader-to-loss loop (#259).
    • evaluation.ndcg_metric registers 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

    • RetrievalInputs gains the required fields reference_labels and ref_includes_query. Only code that constructs RetrievalInputs directly needs to change.
    • RetrievalMetric gains exclude_lone_queries, default True. A metric that sets it to False decides through NaN which queries count.

    Fixes

    • AccuracyCalculator no longer raises TypeError with MPS inputs. The search stays on MPS and metric arithmetic runs on CPU, because MPS has no float64.

    Documentation

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    PyTorch Metric Learning

    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

    How embeddings flow through miners, losses, reducers, and retrieval metrics.

    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}
    }