π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add batched SMNN descriptor matching (#5558)
Dmytro Mishkin8f683d3f7243
diff --git a/benchmarks/feature/smnn_batching.py b/benchmarks/feature/smnn_batching.pynew file mode 100644index 000000000..c6e9dd7ad--- /dev/null+++ b/benchmarks/feature/smnn_batching.py@@ -0,0 +1,138 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Public SMNN APIs: independent pair calls versus batched descriptor matching.++Inputs stay on the measured device; no extraction, transfers, HDF5, or model+loading is included. Both APIs use identical descriptor pairs, thresholds,+float32 precision, and threads. Synthetic descriptors have 25% noisy positives.+Run this same harness in both the base checkout and the changed worktree;+the base records the unavailable additive API rather than a replacement.+"""++from __future__ import annotations++# Imports follow path setup so direct execution always measures this checkout.+# ruff: noqa: E402+import argparse+import hashlib+import sys+from functools import partial+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(REPO))+sys.path.insert(0, str(REPO / "benchmarks"))++import torch+from common import kornia_provenance, run_metadata, save_json, setup_run, time_us++import kornia+from kornia import feature+++def independent_matches(a: torch.Tensor, b: torch.Tensor):+ return [feature.match_smnn(x, y, 0.95) for x, y in zip(a, b)]+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--device", default="cuda")+ parser.add_argument("--dtype", default="float32", choices=["float32", "float64"])+ parser.add_argument("--threads", type=int, default=1)+ parser.add_argument("--batches", default="1,2,4,8,16")+ parser.add_argument("--counts", default="512,2048,4096")+ parser.add_argument("--min-run-time", type=float, default=0.2)+ parser.add_argument("--json", type=Path, required=True)+ args = parser.parse_args()+ device, dtype, sync = setup_run(args, opencv=False)+ torch.set_float32_matmul_precision("highest")+ source, module = kornia_provenance(kornia.__file__)+ print(f"Kornia source: {source}\nInterpreter: {sys.executable}", flush=True)+ if module == "outside-checkout":+ raise RuntimeError("Kornia imported from a different checkout")+ metadata = {+ **run_metadata(device),+ "kornia_module": module,+ "float32_matmul_precision": torch.get_float32_matmul_precision(),+ "matmul_allow_tf32": torch.backends.cuda.matmul.allow_tf32,+ "benchmark_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),+ "matching_sha256": hashlib.sha256((REPO / "kornia/feature/matching.py").read_bytes()).hexdigest(),+ "units": "pairs/s",+ "regime": __doc__,+ }+ rows = []+ with torch.inference_mode():+ for count in [int(n) for n in args.counts.split(",")]:+ for batch in [int(n) for n in args.batches.split(",")]:+ a = torch.nn.functional.normalize(torch.randn(batch, count, 64, device=device, dtype=dtype), dim=-1)+ b = torch.randn_like(a)+ b[:, : count // 4] = a[:, : count // 4] + 0.01 * torch.randn_like(a[:, : count // 4])+ b = torch.nn.functional.normalize(b, dim=-1)++ independent = partial(independent_matches, a, b)+ expected = independent()+ batched = getattr(feature, "match_smnn_batched", None)+ for label, fn in [+ ("independent", independent),+ ("batched", partial(batched, a, b, 0.95) if batched else None),+ ]:+ if label == "batched" and batched is None:+ rows.append(+ {+ "backend": label,+ "batch": batch,+ "count": count,+ "median_us": None,+ "error": "unavailable",+ }+ )+ continue+ if label == "batched":+ ratios, indices = fn()+ for i, (reference_ratio, reference_indices) in enumerate(expected):+ selected = indices[:, 0] == i+ torch.testing.assert_close(indices[selected, 1:], reference_indices)+ torch.testing.assert_close(ratios[selected], reference_ratio, rtol=2e-5, atol=2e-5)+ median, iqr = time_us(fn, min_run_time=args.min_run_time, sync=sync)+ peak = None+ if device.type == "cuda":+ torch.cuda.reset_peak_memory_stats()+ fn()+ torch.cuda.synchronize()+ peak = torch.cuda.max_memory_allocated()+ rows.append(+ {+ "backend": label,+ "batch": batch,+ "count": count,+ "dtype": args.dtype,+ "median_us": median,+ "iqr_us": iqr,+ "throughput_per_s": batch * 1e6 / median,+ "peak_allocated_bytes": peak,+ "equivalent_matches": True,+ }+ )+ print(+ f"N={count} B={batch} {label}: {median / batch:.1f} us/pair (IQR batch {iqr:.1f})", flush=True+ )+ save_json(args.json, metadata, rows)+ save_json(args.json, metadata, rows)+++if __name__ == "__main__":+ main()diff --git a/changelog.d/5558.added.md b/changelog.d/5558.added.mdnew file mode 100644index 000000000..0f20e7541--- /dev/null+++ b/changelog.d/5558.added.md@@ -0,0 +1 @@+`kornia.feature.match_smnn_batched` matches independent descriptor pairs with batched distance computation, packed match indices, and optional validity masks for padded inputs.diff --git a/docs/source/feature.matching.rst b/docs/source/feature.matching.rstindex ea3aa1ff4..7e37b9f5a 100644--- a/docs/source/feature.matching.rst+++ b/docs/source/feature.matching.rst@@ -10,6 +10,7 @@ Descriptor matching.. autofunction:: match_mnn.. autofunction:: match_snn.. autofunction:: match_smnn+.. autofunction:: match_smnn_batched.. autofunction:: match_fginn.. autofunction:: match_adalamdiff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex d3dfd2936..2ce225096 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -75,6 +75,7 @@ from .matching import (match_mnn,match_nn,match_smnn,+ match_smnn_batched,match_snn,)from .mkd import MKDDescriptor@@ -181,6 +182,7 @@ __all__ = ["match_mnn","match_nn","match_smnn",+ "match_smnn_batched","match_snn","normalize_laf","perspective_transform_lafs",diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex 307abee08..05ad1998a 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -257,6 +257,130 @@ def match_smnn(return match_dists, matches_idxs+def match_smnn_batched(+ desc1: torch.Tensor,+ desc2: torch.Tensor,+ th: float = 0.95,+ dm: Optional[torch.Tensor] = None,+ mask1: Optional[torch.Tensor] = None,+ mask2: Optional[torch.Tensor] = None,+) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Match independent descriptor pairs with a batched symmetric nearest-neighbor ratio test.++ Like :func:`match_smnn`, each match must pass Lowe's first/second L2 distance+ ratio test in both directions and have mutual nearest neighbors. The returned+ quality is the larger of the two ratios. Pairs are processed together with+ batched distance computation and top-k reductions, without a per-pair loop.++ Args:+ desc1: First descriptors, shape :math:`(B, N, D)`.+ desc2: Second descriptors, shape :math:`(B, M, D)`.+ th: Inclusive distance-ratio threshold.+ dm: Optional precomputed L2 distances, shape :math:`(B, N, M)`.+ mask1: Optional boolean mask of valid first descriptors, shape :math:`(B, N)`.+ mask2: Optional boolean mask of valid second descriptors, shape :math:`(B, M)`.+ Masks allow padding variable-length pairs; padding never becomes a neighbor.++ Returns:+ - Ratios, shape :math:`(K, 1)`, with the input device and dtype.+ - Long indices, shape :math:`(K, 3)`: ``(batch_index, index_in_desc1, index_in_desc2)``.+ Indices refer to the original padded tensors, sorted by batch and first-descriptor index.+ A pair with fewer than two valid descriptors on either side contributes no matches.++ Note:+ Memory for the distance matrix scales as :math:`B N M`. Bucket pairs by+ descriptor counts and limit batch size when matching large collections.+ Half-precision descriptors use float32 distance computation before ratios+ are converted back to the input dtype.+ Masked inputs use ``torch.cdist``'s direct Euclidean path to avoid the+ cancellation possible in its matrix-multiplication implementation. This+ can be slower for large masked descriptor sets; unmasked inputs retain+ the default small-input direct path and large-input matrix implementation.+ As in :func:`match_smnn`, a zero second-neighbor distance produces an+ undefined ratio and that ambiguous match is rejected. Ties follow+ :func:`torch.topk` and do not have a guaranteed cross-device ordering.++ Example:+ >>> a = torch.tensor([[[0., 0.], [1., 1.], [2., 2.]]])+ >>> ratios, indices = match_smnn_batched(a, a.flip(1))+ >>> indices+ tensor([[0, 0, 2],+ [0, 1, 1],+ [0, 2, 0]])++ """+ KORNIA_CHECK_SHAPE(desc1, ["B", "N", "D"])+ KORNIA_CHECK_SHAPE(desc2, ["B", "M", "D"])+ batch, n, dim = desc1.shape+ if desc2.shape[0] != batch or desc2.shape[2] != dim:+ raise ValueError("Descriptor batch sizes and dimensions must match")+ if desc1.device != desc2.device or desc1.dtype != desc2.dtype or not desc1.is_floating_point():+ raise ValueError("Descriptors must have the same floating dtype and device")+ m = desc2.shape[1]+ if dm is not None and (dm.shape != (batch, n, m) or dm.device != desc1.device or dm.dtype != desc1.dtype):+ raise ValueError("Distance matrix must have shape (B, N, M) and the descriptor dtype/device")+ for mask, shape in ((mask1, (batch, n)), (mask2, (batch, m))):+ if mask is not None and (mask.shape != shape or mask.dtype != torch.bool or mask.device != desc1.device):+ raise ValueError("Validity masks must be boolean tensors with shape (B, N)/(B, M) on the input device")+ if batch == 0 or n < 2 or m < 2:+ return desc1.new_empty((0, 1)), torch.empty((0, 3), dtype=torch.long, device=desc1.device)++ valid1 = torch.ones((batch, n), dtype=torch.bool, device=desc1.device) if mask1 is None else mask1+ valid2 = torch.ones((batch, m), dtype=torch.bool, device=desc1.device) if mask2 is None else mask2+ masked = mask1 is not None or mask2 is not None+ if dm is None:+ # Exclude padded values from the calculation itself. Masking the resulting+ # distances is too late for NaN/Inf padding, which can poison gradients.+ work1 = desc1.masked_fill(~valid1.unsqueeze(-1), 0.0) if mask1 is not None else desc1+ 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):+ 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.+ 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)+ else:+ distances = dm+ if mask1 is not None or mask2 is not None:+ distances = distances.masked_fill(~(valid1.unsqueeze(2) & valid2.unsqueeze(1)), float("inf"))+ values1, neighbors1 = distances.topk(2, dim=2, largest=False)+ values2, neighbors2 = distances.transpose(1, 2).topk(2, dim=2, largest=False)+ defined1 = torch.isfinite(values1).all(-1) & (values1[..., 1] > 0)+ defined2 = torch.isfinite(values2).all(-1) & (values2[..., 1] > 0)+ # Substitute finite operands before division: rejecting a 0/0 ratio only+ # after division would still leave NaNs in the backward pass for dm.+ ratios1 = torch.where(defined1, values1[..., 0], 0.0) / torch.where(defined1, values1[..., 1], 1.0)+ ratios2 = torch.where(defined2, values2[..., 0], 0.0) / torch.where(defined2, values2[..., 1], 1.0)+ nearest2 = neighbors1[..., 0]+ reverse_ratio = ratios2.gather(1, nearest2)+ mutual = neighbors2[..., 0].gather(1, nearest2) == torch.arange(n, device=desc1.device)+ enough = (valid1.sum(1) >= 2) & (valid2.sum(1) >= 2)+ keep = (+ valid1+ & enough.unsqueeze(1)+ & defined1+ & defined2.gather(1, nearest2)+ & mutual+ & (ratios1 <= th)+ & (reverse_ratio <= th)+ )+ batch_index, index1 = keep.nonzero(as_tuple=True)+ indices = torch.stack((batch_index, index1, nearest2[batch_index, index1]), dim=1)+ ratios = torch.maximum(ratios1, reverse_ratio)[batch_index, index1].unsqueeze(1).to(desc1.dtype)+ return ratios, indices++def match_fginn(desc1: torch.Tensor,desc2: torch.Tensor,diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.pyindex d420adb32..736264b63 100644--- a/tests/feature/test_matching.py+++ b/tests/feature/test_matching.py@@ -19,6 +19,7 @@ import pytestimport torchfrom kornia.core._compat import torch_version_le+from kornia.feature import matchingfrom kornia.feature.integrated import LightGlueMatcherfrom kornia.feature.laf import laf_from_center_scale_orifrom kornia.feature.matching import (@@ -757,3 +758,212 @@ class TestCDist(BaseTester):assert torch.isfinite(d1.grad).all()assert d2.grad is not Noneassert torch.isfinite(d2.grad).all()+++class TestMatchSMNNBatched(BaseTester):+ def test_large_common_descriptor_offset(self, device):+ a = torch.tensor([[[10000.0, 10000.0], [10001.0, 10000.0], [10000.0, 10002.0]]], device=device)+ b = a.flip(1)+ ratios, indices = matching.match_smnn_batched(a, b)+ reference_ratio = torch.zeros(3, 1, device=device)+ reference_index = torch.tensor([[0, 2], [1, 1], [2, 0]], device=device)+ self.assert_close(indices[:, 1:], reference_index)+ self.assert_close(ratios, reference_ratio)++ def test_undefined_provided_distance_ratios_have_finite_gradients(self, device, dtype):+ a = torch.zeros(1, 3, 4, device=device, dtype=dtype)+ b = torch.zeros(1, 4, 4, device=device, dtype=dtype)+ dm = torch.tensor(+ [[[0.0, 0.0, 2.0, 3.0], [0.0, 0.0, 2.0, 3.0], [2.0, 3.0, 0.1, 4.0]]],+ device=device,+ dtype=dtype,+ requires_grad=True,+ )+ ratios, indices = matching.match_smnn_batched(a, b, 1.0, dm=dm)+ assert indices.tolist() == [[0, 2, 2]]+ ratios.sum().backward()+ assert torch.isfinite(dm.grad).all()++ def test_ambiguous_zero_distance_gradients(self, device, dtype):+ a = torch.tensor([[[0.0, 0.0], [0.0, 0.0], [1.0, 2.0]]], device=device, dtype=dtype, requires_grad=True)+ b = torch.tensor([[[0.0, 0.0], [0.0, 0.0], [2.0, 1.0]]], device=device, dtype=dtype, requires_grad=True)+ ratios, indices = matching.match_smnn_batched(a, b)+ assert indices.tolist() == [[0, 2, 2]]+ ratios.sum().backward()+ assert torch.isfinite(a.grad).all()+ assert torch.isfinite(b.grad).all()++ @pytest.mark.parametrize("masked", [False, True])+ def test_dynamo(self, device, dtype, torch_optimizer, masked):+ a = torch.rand(2, 3, 4, device=device, dtype=dtype)+ b = torch.rand(2, 4, 4, device=device, dtype=dtype)+ kwargs = {"mask1": torch.tensor([[True, True, False], [True, True, True]], device=device)} if masked else {}+ expected = matching.match_smnn_batched(a, b, **kwargs)+ actual = torch_optimizer(matching.match_smnn_batched)(a, b, **kwargs)+ self.assert_close(actual[0], expected[0])+ self.assert_close(actual[1], expected[1])++ 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)+ mask = torch.tensor([[True, True, False], [True, True, False]], device=device)+ ratios, _ = matching.match_smnn_batched(a, b, 1.0, mask1=mask)+ ratios.sum().backward()+ assert torch.isfinite(a.grad).all()+ assert torch.isfinite(b.grad).all()+ self.assert_close(a.grad[:, 2], torch.zeros_like(a.grad[:, 2]))++ @pytest.mark.parametrize("batch,n,m", [(1, 5, 7), (3, 5, 7), (2, 8, 3)])+ def test_matches_independent_pairs(self, device, dtype, batch, n, m):+ a = torch.rand(batch, n, 8, device=device, dtype=dtype)+ b = torch.rand(batch, m, 8, device=device, dtype=dtype)+ ratios, indices = matching.match_smnn_batched(a, b, 0.95)+ assert ratios.shape == (len(indices), 1)+ assert indices.shape[1] == 3+ assert indices.dtype == torch.long+ assert ratios.device == a.device+ assert ratios.dtype == a.dtype+ for i in range(batch):+ # The new API accumulates half-precision L2 distances in float32;+ # compare to that reference rather than legacy half norm cancellation.+ if dtype in (torch.float16, torch.bfloat16):+ expected_ratio, expected_index = match_smnn(a[i].float(), b[i].float(), 0.95)+ expected_ratio = expected_ratio.to(dtype)+ else:+ expected_ratio, expected_index = match_smnn(a[i], b[i], 0.95)+ self.assert_close(indices[indices[:, 0] == i, 1:], expected_index)+ self.assert_close(ratios[indices[:, 0] == i], expected_ratio)++ def test_masks_preserve_original_indices(self, device, dtype):+ a = torch.tensor(+ [[[0.0, 0.0], [10.0, 10.0], [1.0, 2.0], [2.0, 1.0]], [[0.0, 0.0], [0.0, 0.0], [3.0, 3.0], [4.0, 4.0]]],+ device=device,+ dtype=dtype,+ )+ b = torch.tensor(+ [+ [[2.0, 1.0], [0.0, 0.0], [1.0, 2.0], [10.0, 10.0], [0.0, 0.0]],+ [[0.0, 0.0], [3.0, 3.0], [4.0, 4.0], [0.0, 0.0], [0.0, 0.0]],+ ],+ device=device,+ dtype=dtype,+ )+ mask_a = torch.tensor([[True, False, True, True], [False, False, True, True]], device=device)+ mask_b = torch.tensor([[True, True, True, False, False], [False, True, True, False, False]], device=device)+ ratios, indices = matching.match_smnn_batched(a, b, 0.95, mask1=mask_a, mask2=mask_b)+ for i in range(2):+ valid_a, valid_b = mask_a[i].nonzero().flatten(), mask_b[i].nonzero().flatten()+ r, ix = match_smnn(a[i, valid_a], b[i, valid_b], 0.95)+ original = torch.stack((valid_a[ix[:, 0]], valid_b[ix[:, 1]]), dim=1)+ self.assert_close(indices[indices[:, 0] == i, 1:], original)+ self.assert_close(ratios[indices[:, 0] == i], r)++ @pytest.mark.parametrize("mask_first, mask_second", [(True, False), (False, True), (True, True)])+ def test_masks_large_offset_padded_descriptors(self, device, mask_first, mask_second):+ a = torch.full((1, 30, 2), -1e4, device=device)+ b = torch.full((1, 31, 2), -2e4, device=device)+ a[0, [1, 8, 29]] = torch.tensor([[10000.0, 10000.0], [10001.0, 10000.0], [10000.0, 10002.0]], device=device)+ b[0, [3, 15, 30]] = a[0, [1, 8, 29]]+ mask1 = torch.zeros(1, 30, dtype=torch.bool, device=device) if mask_first else None+ mask2 = torch.zeros(1, 31, dtype=torch.bool, device=device) if mask_second else None+ if mask1 is not None:+ mask1[0, [1, 8, 29]] = True+ if mask2 is not None:+ mask2[0, [3, 15, 30]] = True+ ratios, indices = matching.match_smnn_batched(a, b, mask1=mask1, mask2=mask2)+ expected = torch.tensor([[0, 1, 3], [0, 8, 15], [0, 29, 30]], device=device)+ self.assert_close(indices, expected)+ self.assert_close(ratios, torch.zeros(3, 1, device=device))++ @pytest.mark.parametrize("mask_first, mask_second", [(True, False), (False, True), (True, True)])+ def test_nonfinite_padding_matches_compact_gradients(self, device, dtype, mask_first, mask_second):+ a_padding = [float("nan"), float("inf")] if mask_first else [4.0, 0.0]+ b_padding = [float("-inf"), float("nan")] if mask_second else [4.0, 0.0]+ a = torch.tensor(+ [[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], a_padding]], device=device, dtype=dtype, requires_grad=True+ )+ b = torch.tensor(+ [[[0.1, 0.0], [1.2, 0.0], [3.0, 0.0], b_padding]], device=device, dtype=dtype, requires_grad=True+ )+ mask1 = torch.tensor([[True, True, True, False]], device=device) if mask_first else None+ mask2 = torch.tensor([[True, True, True, False]], device=device) if mask_second else None+ ratios, indices = matching.match_smnn_batched(a, b, 1.0, mask1=mask1, mask2=mask2)+ ratios.sum().backward()++ valid_a = mask1[0].nonzero().flatten() if mask1 is not None else torch.arange(4, device=device)+ valid_b = mask2[0].nonzero().flatten() if mask2 is not None else torch.arange(4, device=device)+ compact_a = a.detach()[:, valid_a].clone().requires_grad_()+ compact_b = b.detach()[:, valid_b].clone().requires_grad_()+ reference_ratios, reference_indices = matching.match_smnn_batched(compact_a, compact_b, 1.0)+ reference_ratios.sum().backward()++ self.assert_close(ratios, reference_ratios)+ self.assert_close(indices, reference_indices)+ self.assert_close(a.grad[:, valid_a], compact_a.grad)+ self.assert_close(b.grad[:, valid_b], compact_b.grad)+ assert torch.isfinite(a.grad).all()+ assert torch.isfinite(b.grad).all()+ assert a.grad[:, valid_a].abs().sum() > 0+ assert b.grad[:, valid_b].abs().sum() > 0+ if mask_first:+ self.assert_close(a.grad[:, 3], torch.zeros_like(a.grad[:, 3]))+ if mask_second:+ self.assert_close(b.grad[:, 3], torch.zeros_like(b.grad[:, 3]))++ def test_provided_distance_matrix_and_ties(self, device, dtype):+ a = torch.zeros(2, 3, 4, device=device, dtype=dtype)+ b = torch.zeros(2, 4, 4, device=device, dtype=dtype)+ dm = torch.tensor(+ [+ [[0.0, 1.0, 2.0, 3.0], [2.0, 0.1, 3.0, 4.0], [3.0, 4.0, 0.2, 5.0]],+ [[0.0, 0.0, 2.0, 3.0], [0.0, 0.0, 2.0, 3.0], [2.0, 3.0, 0.1, 4.0]],+ ],+ device=device,+ dtype=dtype,+ )+ ratios, indices = matching.match_smnn_batched(a, b, 0.95, dm)+ for i in range(2):+ r, ix = match_smnn(a[i], b[i], 0.95, dm[i])+ self.assert_close(indices[indices[:, 0] == i, 1:], ix)+ self.assert_close(ratios[indices[:, 0] == i], r)++ @pytest.mark.parametrize("batch,n,m", [(0, 3, 4), (2, 0, 4), (2, 3, 0), (2, 1, 4), (2, 4, 1)])+ def test_empty_and_short(self, device, dtype, batch, n, m):+ a = torch.empty(batch, n, 4, device=device, dtype=dtype)+ b = torch.empty(batch, m, 4, device=device, dtype=dtype)+ r, ix = matching.match_smnn_batched(a, b)+ assert r.shape == (0, 1)+ assert ix.shape == (0, 3)+ assert r.dtype == dtype+ assert ix.device == a.device++ def test_short_valid_rows_return_no_matches(self, device, dtype):+ a = torch.rand(2, 3, 4, device=device, dtype=dtype)+ b = torch.rand(2, 4, 4, device=device, dtype=dtype)+ mask = torch.tensor([[True, False, False], [False, False, False]], device=device)+ r, ix = matching.match_smnn_batched(a, b, mask1=mask)+ assert r.shape == (0, 1)+ assert ix.shape == (0, 3)++ @pytest.mark.parametrize("problem", ["batch", "dim", "mask_shape", "mask_dtype", "dm_shape"])+ def test_invalid_inputs(self, device, dtype, problem):+ a = torch.rand(2, 3, 4, device=device, dtype=dtype)+ b = torch.rand(2, 5, 4, device=device, dtype=dtype)+ kwargs = {}+ if problem == "batch":+ b = b[:1]+ elif problem == "dim":+ b = b[..., :3]+ elif problem == "mask_shape":+ kwargs["mask1"] = torch.ones(2, 2, dtype=torch.bool, device=device)+ elif problem == "mask_dtype":+ kwargs["mask2"] = torch.ones(2, 5, dtype=dtype, device=device)+ else:+ kwargs["dm"] = torch.rand(2, 3, 4, dtype=dtype, device=device)+ with pytest.raises(ValueError):+ matching.match_smnn_batched(a, b, **kwargs)++ def test_gradcheck(self, device):+ a = torch.rand(2, 3, 4, device=device, dtype=torch.float64)+ b = torch.rand(2, 4, 4, device=device, dtype=torch.float64)+ self.gradcheck(matching.match_smnn_batched, (a, b, 1.0))