π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Added possibility to run tests for mps locally (#1716)
Dmytro Mishkin9b334a92be7a
diff --git a/Makefile b/Makefileindex 80b46f88a..448d669f4 100644--- a/Makefile+++ b/Makefile@@ -11,6 +11,9 @@ test-cpu: FORCEtest-cuda: FORCEpytest -v --device cuda --dtype all --cov=kornia test/ --flake8 --mypy+test-mps: FORCE+ pytest -v --device mps --dtype float32 -k "not (grad or exception or jit)" test/+test-module: FORCEpytest -v --device all --dtype all test/$(module) --flake8 --mypydiff --git a/conftest.py b/conftest.pyindex 57a4be4f7..964986a49 100644--- a/conftest.py+++ b/conftest.py@@ -23,6 +23,9 @@ def get_test_devices() -> Dict[str, torch.device]:import torch_xla.core.xla_model as xmdevices["tpu"] = xm.xla_device()+ if hasattr(torch.backends, 'mps'):+ if torch.backends.mps.is_available(): # type: ignore+ devices["mps"] = torch.device("mps")return devicesdiff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 5163ccd73..59b01aee8 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -4,7 +4,7 @@ import torchimport torch.nn as nnimport torch.nn.functional as F-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.testing import KORNIA_CHECK_SHAPE, is_mps_tensor_safeurls: Dict[str, str] = {}urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"@@ -73,7 +73,11 @@ class HardNet(nn.Module):@staticmethoddef _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:"""Utility function that normalizes the input by batch."""- sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)+ if not is_mps_tensor_safe(x):+ sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)+ else:+ mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True)+ sp = torch.std(x, dim=(-3, -2, -1), keepdim=True)# WARNING: we need to .detach() input, otherwise the gradients produced by# the patches extractor with F.grid_sample are very noisy, making the detector# training totally unstable.@@ -159,7 +163,11 @@ class HardNet8(nn.Module):@staticmethoddef _normalize_input(x: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:"""Utility function that normalizes the input by batch."""- sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)+ if not is_mps_tensor_safe(x):+ sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)+ else:+ mp = torch.mean(x, dim=(-3, -2, -1), keepdim=True)+ sp = torch.std(x, dim=(-3, -2, -1), keepdim=True)# WARNING: we need to .detach() input, otherwise the gradients produced by# the patches extractor with F.grid_sample are very noisy, making the detector# training totally unstable.diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex 5ad6e3cb1..0bef5ecf2 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -4,11 +4,22 @@ import torchimport torch.nn as nnfrom kornia.feature.laf import get_laf_center-from kornia.testing import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE, Tensor+from kornia.testing import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE, Tensor, is_mps_tensor_safefrom .adalam import get_adalam_default_config, match_adalam+def _cdist(d1: torch.Tensor, d2: torch.Tensor) -> torch.Tensor:+ r"""Manual `torch.cdist` for M1."""+ if (not is_mps_tensor_safe(d1)) and (not is_mps_tensor_safe(d2)):+ return torch.cdist(d1, d2)+ 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 = dm.clamp(min=0.0).sqrt()+ return dm++def _get_default_fginn_params():config = {"th": 0.85, "mutual": False, "spatial_th": 10.0}return config@@ -25,7 +36,7 @@ def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensorto each descriptor in desc2, shape of :math:`(B1, B2)`."""if dm_ is None:- dm = torch.cdist(desc1, desc2)+ dm = _cdist(desc1, desc2)else:KORNIA_CHECK_DM_DESC(desc1, desc2, dm_)dm = dm_@@ -91,7 +102,6 @@ def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuplif (len(desc1) == 0) or (len(desc2) == 0):return _no_match(desc1)distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)-ms = min(distance_matrix.size(0), distance_matrix.size(1))match_dists, idxs_in_2 = torch.min(distance_matrix, dim=1)match_dists2, idxs_in_1 = torch.min(distance_matrix, dim=0)@@ -130,11 +140,9 @@ def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[TensorKORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])- distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)-if desc2.shape[0] < 2: # We cannot perform snn check, so output empty matches- return _no_match(distance_matrix)-+ return _no_match(desc1)+ distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)vals, idxs_in_2 = torch.topk(distance_matrix, 2, dim=1, largest=False)ratio = vals[:, 0] / vals[:, 1]mask = ratio <= th@@ -171,7 +179,6 @@ def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tensif (desc1.shape[0] < 2) or (desc2.shape[0] < 2):return _no_match(desc1)-distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)dists1, idx1 = match_snn(desc1, desc2, th, distance_matrix)@@ -179,7 +186,12 @@ def match_smnn(desc1: Tensor, desc2: Tensor, th: float = 0.95, dm: Optional[Tensif len(dists2) > 0 and len(dists1) > 0:idx2 = idx2.flip(1)- idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1.0)+ if not is_mps_tensor_safe(idx1):+ idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1.0)+ else:+ idxs2_rep = idx2.float().repeat_interleave(idx1.size(0), dim=0)+ idxs_dm = (idx1.float().repeat(idx2.size(0), 1) - idxs2_rep).abs().sum(dim=1)+ idxs_dm = idxs_dm.reshape(idx1.size(0), idx2.size(0))mutual_idxs1 = idxs_dm.min(dim=1)[0] < 1e-8mutual_idxs2 = idxs_dm.min(dim=0)[0] < 1e-8good_idxs1 = idx1[mutual_idxs1.view(-1)]diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 3fa83f754..adf6137b7 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -21,6 +21,11 @@ def xla_is_available() -> bool:return False+def is_mps_tensor_safe(x: Tensor) -> bool:+ """Return whether tensor is on MPS device."""+ return 'mps' in str(x.device)++# TODO: Isn't this function duplicated with eye_like?def create_eye_batch(batch_size, eye_size, device=None, dtype=None):"""Create a batch of identity matrices of shape Bx3x3."""