Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): torch.cdist on MPS (torch >= 2.13) and a broadcasting export fallback for descriptor distances (#6429)

Dmytro Mishkinad2a08ae7fc8
diff --git a/changelog.d/6429.added.md b/changelog.d/6429.added.md
new file mode 100644
index 000000000..796df7b8f
--- /dev/null
+++ b/changelog.d/6429.added.md
@@ -0,0 +1 @@
+On MPS with torch 2.13 or later, the descriptor matchers compute distances with `torch.cdist` instead of a manual fallback: `match_snn` and `match_smnn` run 1.4-1.9x faster at 6000 descriptors, and unmasked `match_smnn_batched` runs 7.7x faster and needs about a third of the memory at 2 x 3000. Under export the distance fallback broadcasts instead of repeating the squared norms, with the same result, and runs 1.3-1.8x faster.
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 70d38f14e..23c983691 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -20,43 +20,65 @@ from typing import Any, ClassVar, Dict, List, Optional, Tuple
import torch
from torch import nn
+from kornia.core._compat import torch_version_ge
from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE
-from kornia.core.utils import _l2_normalize, is_exporting, is_mps_tensor_safe
+from kornia.core.utils import _l2_normalize, is_autocast_enabled, is_exporting, is_mps_tensor_safe
from kornia.feature.laf import get_laf_center
from kornia.feature.steerers import DiscreteSteerer
from .adalam import match_adalam
+# ``aten::_cdist_backward`` gained its MPS kernel in torch 2.13; kornia supports torch >= 2.5.1.
+_MPS_HAS_CDIST_BACKWARD = torch_version_ge(2, 13)
+
+
+def _torch_cdist_available(x: torch.Tensor) -> bool:
+ """Return whether ``torch.cdist`` can compute, and differentiate, the distances of descriptors like ``x``."""
+ if is_exporting(): # `torch.cdist` has no ONNX lowering
+ return False
+ # TorchScript cannot read ``_MPS_HAS_CDIST_BACKWARD``, so a scripted call keeps the fallback on MPS.
+ mps_has_backward = False
+ if not torch.jit.is_scripting():
+ mps_has_backward = _MPS_HAS_CDIST_BACKWARD
+ return mps_has_backward or not is_mps_tensor_safe(x)
+
def _cdist(d1: torch.Tensor, d2: torch.Tensor) -> torch.Tensor:
r"""Compute pairwise L2 distances between rows of d1 and d2.
- Uses ``torch.cdist`` on non-MPS devices outside export. Falls back to a manual
- squared-distance implementation for MPS tensors and export. Half-precision
- inputs are computed in float32: in half precision the squared norms round away
- the squared distance between nearby descriptors, and ``torch.cdist`` has no
- float16 kernel on CPU. Distances are returned in the input dtype.
+ Uses ``torch.cdist``, except under export, where it has no ONNX lowering, and on
+ MPS before torch 2.13, where it has no backward. Both fall back to the
+ matrix-multiplication form of the squared distance. Half-precision inputs are
+ computed in float32: in half precision the squared norms round away the squared
+ distance between nearby descriptors, and ``torch.cdist`` has no float16 kernel on
+ CPU. Distances are returned in the input dtype.
"""
half = (torch.float16, torch.bfloat16)
output_dtype = d1.dtype
- if output_dtype in half and d2.dtype == output_dtype:
+ # a separate `if`: TorchScript skips the body only under a bare `not torch.jit.is_scripting()`
+ if not torch.jit.is_scripting(): # noqa: SIM102
+ if d1.dtype != d2.dtype:
+ # Inside autocast, `torch.cdist` computes a mixed pair of float16, bfloat16 and float32 in float32, and
+ # so does the fallback here; autocast does not cast float64. Outside autocast, the CPU `torch.cdist`
+ # raises for a mixed pair, while on MPS it computes one of up to 25 rows in the dtype of d1.
+ castable = (torch.float16, torch.bfloat16, torch.float32)
+ if not (is_autocast_enabled() and d1.dtype in castable and d2.dtype in castable):
+ raise RuntimeError(f"The descriptors must have the same dtype, got {d1.dtype} and {d2.dtype}")
+ d1, d2 = d1.float(), d2.float()
+ if output_dtype in half:
d1, d2 = d1.float(), d2.float()
- if (
- not is_exporting() # `torch.cdist` has no ONNX lowering
- and (not is_mps_tensor_safe(d1))
- and (not is_mps_tensor_safe(d2))
- ):
+ if _torch_cdist_available(d1) and _torch_cdist_available(d2):
distances = torch.cdist(d1, d2)
else:
# Autocast would lower the matmul precision again and cancel nearby distances.
with torch.autocast(device_type="cpu", enabled=False), torch.autocast(device_type="cuda", enabled=False):
d1_sq = (d1**2).sum(dim=1, keepdim=True)
d2_sq = (d2**2).sum(dim=1, keepdim=True)
- dm = d1_sq.repeat(1, d2.size(0)) + d2_sq.repeat(1, d1.size(0)).t() - 2.0 * d1 @ d2.t()
+ dm = d1_sq + d2_sq.t() - 2.0 * d1 @ d2.t()
dm = dm.clamp(min=0.0)
mask = dm > 0.0
- safe_dm = torch.where(mask, dm, torch.ones_like(dm))
- distances = torch.where(mask, safe_dm.sqrt(), torch.zeros_like(dm))
+ safe_dm = torch.where(mask, dm, 1.0)
+ distances = torch.where(mask, safe_dm.sqrt(), 0.0)
return distances.to(output_dtype)
@@ -372,21 +394,24 @@ def match_smnn_batched(
work2 = desc2.masked_fill(~valid2.unsqueeze(-1), 0.0) if mask2 is not None else desc2
work1 = work1.float() if work1.dtype in (torch.float16, torch.bfloat16) else work1
work2 = work2.float() if work2.dtype in (torch.float16, torch.bfloat16) else work2
- if not is_exporting() and not is_mps_tensor_safe(desc1):
+ # Without the matrix-multiplication form, which it takes for unmasked pairs with more than
+ # 25 descriptors on a side, `torch.cdist` on MPS holds all (B, N, M, D) differences at once.
+ mps_direct = is_mps_tensor_safe(desc1) and (masked or max(n, m) <= 25)
+ if _torch_cdist_available(desc1) and not mps_direct:
distances = torch.cdist(
work1,
work2,
compute_mode="donot_use_mm_for_euclid_dist" if masked else "use_mm_for_euclid_dist_if_necessary",
)
else:
- # MPS/ONNX lack cdist. Accumulate direct differences in descriptor
- # chunks to bound temporary memory without looping over pairs.
+ # Export, MPS before torch 2.13 and direct distances on MPS: accumulate direct differences
+ # in descriptor chunks to bound temporary memory without looping over pairs.
squared = work1.new_zeros((batch, n, m))
for start in range(0, dim, 16):
difference = work1[:, :, None, start : start + 16] - work2[:, None, :, start : start + 16]
squared = squared + (difference * difference).sum(-1)
positive = squared > 0
- distances = torch.where(positive, torch.where(positive, squared, torch.ones_like(squared)).sqrt(), 0.0)
+ distances = torch.where(positive, torch.where(positive, squared, 1.0).sqrt(), 0.0)
else:
distances = dm
if mask1 is not None or mask2 is not None:
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index ab3b87394..35699135a 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -914,6 +914,13 @@ class TestMatchSteererLocal(BaseTester):
assert num_rot is None
+def _sine_pattern(shape, frequency, chirp, phase, device, dtype):
+ """Deterministic descriptors in ``[-1, 1]`` without the random generator, the same on every device."""
+ index = torch.arange(math.prod(shape), dtype=torch.float64)
+ values = torch.sin(frequency * index + chirp * (index % shape[-1]) ** 2 + phase).view(shape)
+ return values.to(dtype).to(device)
+
+
class TestCDist(BaseTester):
@pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("use_autocast", [False, True])
@@ -971,6 +978,28 @@ class TestCDist(BaseTester):
with pytest.raises(RuntimeError):
_cdist(torch.ones(2, 4, device=device, dtype=dtype1), torch.ones(3, 4, device=device, dtype=dtype2))
+ @pytest.mark.parametrize("exporting", [False, True])
+ @pytest.mark.parametrize("rows", [10, 30])
+ def test_mixed_pair_under_mixed_precision_is_computed(self, device, monkeypatch, rows, exporting):
+ # Inside autocast a mixed pair of float16, bfloat16 and float32 is computed in float32, by `torch.cdist` and by
+ # the fallback that export takes; more than 25 rows also send `torch.cdist` through its matrix form. Autocast
+ # does not cast float64, so a pair with it raises, as outside autocast.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("autocast region of CPU, CUDA and MPS only")
+ monkeypatch.setattr(matching, "is_exporting", lambda: exporting)
+ low = torch.bfloat16 if device.type == "cpu" else torch.float16
+ d1 = _sine_pattern((rows, 16), 0.71, 0.13, 0.0, device, torch.float32)
+ d2 = _sine_pattern((rows + 5, 16), 0.53, 0.29, 1.0, device, torch.float32)
+ with torch.autocast(device.type, dtype=low):
+ for a, b in ((d1.to(low), d2), (d1, d2.to(low))):
+ actual = _cdist(a, b)
+ assert actual.dtype == a.dtype
+ expected = torch.cdist(a.cpu().double(), b.cpu().double())
+ self.assert_close(actual.cpu().double(), expected.to(a.dtype).double(), rtol=1e-2, atol=1e-3)
+ if device.type == "cpu":
+ with pytest.raises(RuntimeError, match="same dtype"):
+ _cdist(d1.to(low), d2.double())
+
@pytest.mark.parametrize("desc_dtype", [torch.float16, torch.bfloat16])
def test_half_precision_zero_distance_gradient(self, device, desc_dtype):
if not supports_matmul(device, desc_dtype):
@@ -989,6 +1018,23 @@ class TestCDist(BaseTester):
assert d2.grad is not None
assert torch.isfinite(d2.grad).all()
+ @pytest.mark.parametrize("exporting", [False, True])
+ def test_matches_float64_cdist(self, device, dtype, monkeypatch, exporting):
+ # Export takes the matrix-multiplication fallback, as MPS does before torch 2.13. Every distance is at least
+ # 2.6, where that form does not cancel; more than 25 rows also send `torch.cdist` itself through it.
+ monkeypatch.setattr(matching, "is_exporting", lambda: exporting)
+ desc1 = _sine_pattern((30, 16), 0.71, 0.13, 0.0, device, dtype).requires_grad_()
+ desc2 = _sine_pattern((40, 16), 0.53, 0.29, 1.0, device, dtype).requires_grad_()
+ reference1 = desc1.detach().cpu().double().requires_grad_()
+ reference2 = desc2.detach().cpu().double().requires_grad_()
+ expected = torch.cdist(reference1, reference2)
+ expected_grads = torch.autograd.grad(expected.sum(), (reference1, reference2))
+ actual = _cdist(desc1, desc2)
+ actual_grads = torch.autograd.grad(actual.sum(), (desc1, desc2))
+ self.assert_close(actual, expected.to(dtype).to(device))
+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):
+ self.assert_close(actual_grad, expected_grad.to(dtype).to(device))
+
class TestMatchSMNNBatched(BaseTester):
def test_large_common_descriptor_offset(self, device):
@@ -1033,6 +1079,33 @@ class TestMatchSMNNBatched(BaseTester):
self.assert_close(actual[0], expected[0])
self.assert_close(actual[1], expected[1])
+ @pytest.mark.parametrize("masked", [False, True])
+ @pytest.mark.parametrize("rows", [20, 30])
+ def test_export_differences_match_cdist(self, device, dtype, monkeypatch, masked, rows):
+ # Export accumulates direct differences in chunks of 16 coordinates, as MPS does for masks, for at most 25
+ # rows and before torch 2.13. Every ratio is at least 0.02 from the threshold.
+ a = _sine_pattern((2, rows, 20), 0.71, 0.13, 0.0, device, dtype)
+ noise = _sine_pattern((2, rows, 20), 0.53, 0.29, 1.0, device, dtype)
+ b = torch.cat((a.flip(1) + 0.1 * noise, 2.0 * _sine_pattern((2, 4, 20), 0.83, 0.17, 2.0, device, dtype)), 1)
+ kwargs = {}
+ if masked:
+ limits = torch.tensor([[rows + 4], [rows]], device=device)
+ kwargs["mask1"] = torch.arange(rows, device=device).expand(2, rows) % 7 != 3
+ kwargs["mask2"] = torch.arange(rows + 4, device=device).expand(2, rows + 4) < limits
+ results = []
+ for exporting in (False, True):
+ monkeypatch.setattr(matching, "is_exporting", lambda exporting=exporting: exporting)
+ a_, b_ = a.clone().requires_grad_(), b.clone().requires_grad_()
+ ratios, indices = matching.match_smnn_batched(a_, b_, 0.95, **kwargs)
+ results.append((ratios, indices, *torch.autograd.grad(ratios.sum(), (a_, b_))))
+ (ratios, indices, *grads), (export_ratios, export_indices, *export_grads) = results
+ assert len(indices) > 20
+ self.assert_close(export_indices, indices)
+ self.assert_close(export_ratios, ratios)
+ for export_grad, grad in zip(export_grads, grads):
+ # Unmasked pairs over 25 rows take the matrix-multiplication form, which moves the gradients by 1e-5.
+ self.assert_close(export_grad, grad, low_tolerance=not masked and rows > 25)
+
def test_masked_gradients_are_finite(self, device, dtype):
a = torch.rand(2, 3, 4, device=device, dtype=dtype, requires_grad=True)
b = torch.rand(2, 4, 4, device=device, dtype=dtype, requires_grad=True)