Skip to main content

Pairwise Metrics for PyTorch

Project description

TorchPairwise GitHub Workflow Status PyPI - Version Downloads GitHub - License DOI

This package provides highly-efficient pairwise metrics for PyTorch.

Highlights

torchpairwise is a collection of general purpose pairwise metric functions that behave similar to torch.cdist (which only implements $L_p$ distance). Instead, we offer a lot more metrics ported from other packages such as scipy.spatial.distance and sklearn.metrics.pairwise. For task-specific metrics (e.g. for evaluation of classification, regression, clustering, ...), you should be in the wrong place, please head to the TorchMetrics repo.

Written in torch's C++ API, the main differences are that our metrics:

  • are all (except some boolean distances) differentiable with backward formulas manually derived, implemented, and verified with torch.autograd.gradcheck.
  • are batched and can exploit GPU parallelization.
  • can be integrated seamlessly within PyTorch-based projects, all functions are torch.jit.script-able.

List of pairwise distance metrics

torchpairwise ops Equivalences in other libraries Differentiable
euclidean_distances sklearn.metrics.pairwise.euclidean_distances ✔️
haversine_distances sklearn.metrics.pairwise.haversine_distances ✔️
manhattan_distances sklearn.metrics.pairwise.manhattan_distances ✔️
cosine_distances sklearn.metrics.pairwise.cosine_distances ✔️
l1_distances (Alias of manhattan_distances) ✔️
l2_distances (Alias of euclidean_distances) ✔️
lp_distances (Alias of minkowski_distances) ✔️
linf_distances (Alias of chebyshev_distances) ✔️
directed_hausdorff_distances scipy.spatial.distance.directed_hausdorff [^1] ✔️
minkowski_distances scipy.spatial.distance.minkowski [^1] ✔️
wminkowski_distances scipy.spatial.distance.wminkowski [^1] ✔️
sqeuclidean_distances scipy.spatial.distance.sqeuclidean_distances [^1] ✔️
correlation_distances scipy.spatial.distance.correlation [^1] ✔️
hamming_distances scipy.spatial.distance.hamming [^1] ❌[^2]
jaccard_distances scipy.spatial.distance.jaccard [^1] ❌[^2]
kulsinski_distances scipy.spatial.distance.kulsinski [^1] ❌[^2]
kulczynski1_distances scipy.spatial.distance.kulczynski1 [^1] ❌[^2]
seuclidean_distances scipy.spatial.distance.seuclidean [^1] ✔️
cityblock_distances scipy.spatial.distance.cityblock [^1] (Alias of manhattan_distances) ✔️
mahalanobis_distances scipy.spatial.distance.mahalanobis [^1] ✔️
chebyshev_distances scipy.spatial.distance.chebyshev [^1] ✔️
braycurtis_distances scipy.spatial.distance.braycurtis [^1] ✔️
canberra_distances scipy.spatial.distance.canberra [^1] ✔️
jensenshannon_distances scipy.spatial.distance.jensenshannon [^1] ✔️
yule_distances scipy.spatial.distance.yule [^1] ❌[^2]
dice_distances scipy.spatial.distance.dice [^1] ❌[^2]
rogerstanimoto_distances scipy.spatial.distance.rogerstanimoto [^1] ❌[^2]
russellrao_distances scipy.spatial.distance.russellrao [^1] ❌[^2]
sokalmichener_distances scipy.spatial.distance.sokalmichener [^1] ❌[^2]
sokalsneath_distances scipy.spatial.distance.sokalsneath [^1] ❌[^2]
snr_distances pytorch_metric_learning.distances.SNRDistance [^1] ✔️

[^1]: These metrics are not pairwise but a pairwise form can be computed by calling scipy.spatial.distance.cdist(x1, x2, metric="[metric_name_or_callable]").

[^2]: These are boolean distances. hamming_distances can be applied for floating point inputs but involves comparison.

Other pairwise metrics or kernel functions

These metrics are usually used to compute kernel for machine learning algorithms.

torchpairwise ops Equivalences in other libraries Differentiable
linear_kernel sklearn.metrics.pairwise.linear_kernel ✔️
polynomial_kernel sklearn.metrics.pairwise.polynomial_kernel ✔️
sigmoid_kernel sklearn.metrics.pairwise.sigmoid_kernel ✔️
rbf_kernel sklearn.metrics.pairwise.rbf_kernel ✔️
laplacian_kernel sklearn.metrics.pairwise.laplacian_kernel ✔️
cosine_similarity sklearn.metrics.pairwise.cosine_similarity ✔️
additive_chi2_kernel sklearn.metrics.pairwise.additive_chi2_kernel ✔️
chi2_kernel sklearn.metrics.pairwise.chi2_kernel ✔️

Custom cdist and pdist

Furthermore, we provide a convenient wrapper function analoguous to torch.cdist excepts that it takes a string metric: str = "minkowski" indicating the desired metric to be used as the third argument, and extra metric-specific arguments are passed as keywords.

import torch, torchpairwise

# directed_hausdorff_distances is a pairwise 2d metric
x1 = torch.rand(10, 6, 3)
x2 = torch.rand(8, 5, 3)

generator = torch.Generator().manual_seed(1)
output = torchpairwise.cdist(x1, x2,
                             metric="directed_hausdorff",
                             shuffle=True,  # kwargs exclusive to directed_hausdorff
                             generator=generator)

Note that pairwise metrics on the second table are currently not allowed keys for cdist because they are not dist. We have a similar plan for pdist (which is equivalent to calling cdist(x1, x1) but avoid storing duplicated positions). However, that requires a total overhaul of existing C++/Cuda kernels and won't be available soon.

Future Improvements

  • Add more metrics (contact me or create a feature request issue).
  • Add memory-efficient argkmin for retrieving pairwise neighbors' distances and indices without storing the whole pairwise distance matrix.
  • Add an equivalence of torch.pdist with metric: str = "minkowski" argument.
  • (Unlikely) Support sparse layouts.

Requirements

  • torch>=2.7.0,<2.8.0 (torch>=1.9.0 if compiled from source)

Notes:

Since torch extensions are not forward compatible, I have to fix a maximum version for the PyPI package and regularly update it on GitHub (but I am not always available). If you use a different version of torch or your platform is not supported, please follow the instructions to install from source.

Installation

From PyPI:

To install prebuilt wheels from torchpairwise, simply run:

pip install torchpairwise

Note that the Linux and Windows wheels in PyPI are compiled with torch==2.7.0 and Cuda 12.8. We only do a non-strict version checking and a warning will be raised if torch's and torchpairwise's Cuda versions do not match.

From Source:

Make sure your machine has a C++17 and a Cuda compiler installed, then clone the repo and run:

pip install .

Usage

The basic usecase is very straight-forward if you are familiar with sklearn.metrics.pairwise and scipy.spatial.distance:

scikit-learn / SciPy TorchPairwise
import numpy as np
import sklearn.metrics.pairwise as sklearn_pairwise

x1 = np.random.rand(10, 5)
x2 = np.random.rand(12, 5)

output = sklearn_pairwise.cosine_similarity(x1, x2)
print(output)
import torch
import torchpairwise

x1 = torch.rand(10, 5, device='cuda')
x2 = torch.rand(12, 5, device='cuda')

output = torchpairwise.cosine_similarity(x1, x2)
print(output)
import numpy as np
import scipy.spatial.distance as distance

x1 = np.random.binomial(
    1, p=0.6, size=(10, 5)).astype(np.bool_)
x2 = np.random.binomial(
    1, p=0.7, size=(12, 5)).astype(np.bool_)

output = distance.cdist(x1, x2, metric='jaccard')
print(output)
import torch
import torchpairwise

x1 = torch.bernoulli(
    torch.full((10, 5), fill_value=0.6, device='cuda')).to(torch.bool)
x2 = torch.bernoulli(
    torch.full((12, 5), fill_value=0.7, device='cuda')).to(torch.bool)

output = torchpairwise.jaccard_distances(x1, x2)
print(output)

Please check the tests folder where we will add more examples.

Citation

@software{hoang_nhat_tran_2025_14699364,
  author       = {Hoang-Nhat Tran},
  title        = {inspiros/torchpairwise: v0.2.0},
  month        = jan,
  year         = 2025,
  publisher    = {Zenodo},
  version      = {v0.2.0},
  doi          = {10.5281/zenodo.14699364},
  url          = {https://doi.org/10.5281/zenodo.14699364},
  swhid        = {swh:1:dir:14f42479843d299e136d10046bc7a12ea20da3ad
                   ;origin=https://doi.org/10.5281/zenodo.14699363;vi
                   sit=swh:1:snp:a3d823c1213301aca562bfd3d8c5a4a6d126
                   9bca;anchor=swh:1:rel:075a27f09a969eb7a1d8235b2264
                   1d8e347ab554;path=inspiros-torchpairwise-3af3663
                  },
}

License

The code is released under the MIT license. See LICENSE.txt for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

torchpairwise-0.3.0.tar.gz (52.9 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

torchpairwise-0.3.0-cp313-cp313-win_amd64.whl (20.9 MB view details)

Uploaded CPython 3.13Windows x86-64

torchpairwise-0.3.0-cp313-cp313-manylinux_2_34_x86_64.whl (57.1 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.34+ x86-64

torchpairwise-0.3.0-cp313-cp313-macosx_10_13_universal2.whl (1.4 MB view details)

Uploaded CPython 3.13macOS 10.13+ universal2 (ARM64, x86-64)

torchpairwise-0.3.0-cp312-cp312-win_amd64.whl (20.9 MB view details)

Uploaded CPython 3.12Windows x86-64

torchpairwise-0.3.0-cp312-cp312-manylinux_2_34_x86_64.whl (57.1 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.34+ x86-64

torchpairwise-0.3.0-cp312-cp312-macosx_10_13_universal2.whl (1.4 MB view details)

Uploaded CPython 3.12macOS 10.13+ universal2 (ARM64, x86-64)

torchpairwise-0.3.0-cp311-cp311-win_amd64.whl (20.9 MB view details)

Uploaded CPython 3.11Windows x86-64

torchpairwise-0.3.0-cp311-cp311-manylinux_2_34_x86_64.whl (57.1 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.34+ x86-64

torchpairwise-0.3.0-cp311-cp311-macosx_10_9_universal2.whl (1.4 MB view details)

Uploaded CPython 3.11macOS 10.9+ universal2 (ARM64, x86-64)

torchpairwise-0.3.0-cp310-cp310-win_amd64.whl (20.9 MB view details)

Uploaded CPython 3.10Windows x86-64

torchpairwise-0.3.0-cp310-cp310-manylinux_2_34_x86_64.whl (57.1 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.34+ x86-64

torchpairwise-0.3.0-cp310-cp310-macosx_10_9_universal2.whl (1.4 MB view details)

Uploaded CPython 3.10macOS 10.9+ universal2 (ARM64, x86-64)

torchpairwise-0.3.0-cp39-cp39-win_amd64.whl (20.9 MB view details)

Uploaded CPython 3.9Windows x86-64

torchpairwise-0.3.0-cp39-cp39-manylinux_2_34_x86_64.whl (57.1 MB view details)

Uploaded CPython 3.9manylinux: glibc 2.34+ x86-64

torchpairwise-0.3.0-cp39-cp39-macosx_10_9_universal2.whl (1.4 MB view details)

Uploaded CPython 3.9macOS 10.9+ universal2 (ARM64, x86-64)

File details

Details for the file torchpairwise-0.3.0.tar.gz.

File metadata

  • Download URL: torchpairwise-0.3.0.tar.gz
  • Upload date:
  • Size: 52.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.22

File hashes

Hashes for torchpairwise-0.3.0.tar.gz
Algorithm Hash digest
SHA256 f07f085925b233aa5980b7fb3922c17c0bc89adc22fe04a124a9f1ce8d58b4cf
MD5 295ab0ceed95432cbdb572df2de5a6ff
BLAKE2b-256 24f710dd5d170eff656604e364aea1092ad31227ab8acb6089cf687fc67b0e0b

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp313-cp313-win_amd64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 a31cb79726bfe7a23ceb739541c7d1b4131b7902b070a584af4af89269f0ad1b
MD5 20394b19eac3b087a5550be887d944b3
BLAKE2b-256 e195606f410c96c86b2013156acafccb5f5ce6050874ebdebb61be1dcde8da74

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp313-cp313-manylinux_2_34_x86_64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp313-cp313-manylinux_2_34_x86_64.whl
Algorithm Hash digest
SHA256 7e1cf190be4bbe3a20c2ccea8800fbc10d24d51e208b97bc59cd61a453654b6b
MD5 be7c07138158f4da8ce6233a678a3c42
BLAKE2b-256 d10c241ef8c612af2cba92bf939156a4f9864dddf8e7b350cf3514194d0a6f08

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp313-cp313-macosx_10_13_universal2.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp313-cp313-macosx_10_13_universal2.whl
Algorithm Hash digest
SHA256 bfe84490baa5980d0406555ea860ab8dd29cfe625198aa351c262b4a4a2c7ea4
MD5 bee8f6dc358b745760facd3991982707
BLAKE2b-256 723259980d22eb1d8c9c0e7d32b3473dc67a8a8c293174ee3865459929fe9b8d

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 ac31ba303c9348dfe82b3fea791339788e5b89468ac502417bdce719ea76b1cb
MD5 d652bd2e9f4b1bc5ad4a3af446a40b8f
BLAKE2b-256 138351a9e44a1c6e6340b02d54b763425ccd78fdf66c2cdcc630d8c001cc3300

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp312-cp312-manylinux_2_34_x86_64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp312-cp312-manylinux_2_34_x86_64.whl
Algorithm Hash digest
SHA256 e4a2235e40327658ce1f3bcadb5e4ca89aed08c03a90993fbed2c60001beee72
MD5 d6aef93dc0bc4c4054dc43afa4f22027
BLAKE2b-256 c75301eb60b5d960ed928eab14ed6c045cf634ed2d09cfdbce1a2c0183e60834

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp312-cp312-macosx_10_13_universal2.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp312-cp312-macosx_10_13_universal2.whl
Algorithm Hash digest
SHA256 8a7610cad4220efcffff26e638b94fb4ac505017e19fc65673b8f5f380f7160a
MD5 a0cf8ca9095ea36fa2786335f80bbd9f
BLAKE2b-256 49e394c33711647721dbbe54a85247d86285ed0521b571e90f723aa4e6f28972

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 0fc0f49ae8342449e6b2d6efd3d94829332f43f9d5cf312d9e25291f3bb3a746
MD5 c3789c1a815c5f2bc20b98b82b726672
BLAKE2b-256 04d88aa79be7c31d97753d6b0e36c6dc39fb23809360ca68fa800099511ee0b1

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp311-cp311-manylinux_2_34_x86_64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp311-cp311-manylinux_2_34_x86_64.whl
Algorithm Hash digest
SHA256 18c240d2b6c3e7e854a4a3b79499efea483703c3e0d50216eaf84d518d26c023
MD5 de19e35821ab88bedad26bd5f575bebd
BLAKE2b-256 57a337f9e4e8efefa5fbcc6cb6e11a319da01126e77c4c83caa83a68cf6352d1

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp311-cp311-macosx_10_9_universal2.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp311-cp311-macosx_10_9_universal2.whl
Algorithm Hash digest
SHA256 faff461cc6ee503c383c354a4bc9eb374201d84323a63224ae9e128b04c620b2
MD5 47f5f2de62ff2256c3f0e66fc356d2aa
BLAKE2b-256 dd32d274ca3bffa4eaadec97b7724788cf5e3ecd37443f73306c6d7c3857f4c7

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 7b3593593b206b1571c57ea6dd2e6264934cd4e69bdd85fa106f47aea127dec3
MD5 f5ce6bde1684cec931be703c0623d907
BLAKE2b-256 2e2d979352512b01806d2b7f99e3ff61a19e0a5d144681b5b562b0dc4f344482

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp310-cp310-manylinux_2_34_x86_64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp310-cp310-manylinux_2_34_x86_64.whl
Algorithm Hash digest
SHA256 7f2ded235cd4ce38120bf7fcfc4706c7d8ff70e2be30f2ef46e24f269c7de451
MD5 d8d6431395bd1cfeb80448b86ff4d27d
BLAKE2b-256 4e16abbf9049b5d19fa97231118350dd7e14d28c63fa71cc0068b4801c280d3f

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp310-cp310-macosx_10_9_universal2.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp310-cp310-macosx_10_9_universal2.whl
Algorithm Hash digest
SHA256 bd74e927a493946b972daf11761bd1dc4afa8a43f491c848e07fc3a864a0d914
MD5 9c2e5bae998e470a229b8b7134c8c5ab
BLAKE2b-256 77f3ecf966aaf1c57323904eea4d75d5210e96256c5c2efd51f326cdb469c138

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp39-cp39-win_amd64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 d30c13e0850c549db9ce38fdad37841c23bda52550ee3f8de26bb59e24229b3c
MD5 d453399a01b0eea8bca027f19c72ecec
BLAKE2b-256 c34739fba8d1df177aa65b16cbc7b67b79785631561cc10f56baa595c19df5fa

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp39-cp39-manylinux_2_34_x86_64.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp39-cp39-manylinux_2_34_x86_64.whl
Algorithm Hash digest
SHA256 2747662874f0adb9431daa6ab4ef2d2c9f15453ce3297a08a19fc073dc39bc35
MD5 e3d748e329ec577e8065921f2a6781bb
BLAKE2b-256 b7ab70347c85159ecda2f756534d716f0ce28f061bb66c56e9ef967435de7051

See more details on using hashes here.

File details

Details for the file torchpairwise-0.3.0-cp39-cp39-macosx_10_9_universal2.whl.

File metadata

File hashes

Hashes for torchpairwise-0.3.0-cp39-cp39-macosx_10_9_universal2.whl
Algorithm Hash digest
SHA256 fda4e5e8512676a3cadbe9384a6da99375f51c15f28298cb596f95e97d2f0432
MD5 099272aacfea01b1865fbdc8889384ee
BLAKE2b-256 9ab5df833d67ebdc1cf27a73ce1ac9aa1090faf48ccfa63a19e0a97703735d20

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page