π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(feature): match_mnn, match_snn and match_smnn wait for the device once (match_smnn 1.4-1.9x on CUDA) (#6501)
Dmytro Mishkinf9f610107c23
diff --git a/changelog.d/6501.fixed.md b/changelog.d/6501.fixed.mdnew file mode 100644index 000000000..7af3737f7--- /dev/null+++ b/changelog.d/6501.fixed.md@@ -0,0 +1,5 @@+`match_mnn`, `match_snn` and `match_smnn` wait for the device once per call, where they waited two, three and nine+times: each selects its matches with one `torch.nonzero` instead of indexing several tensors with a boolean mask, and+`match_smnn` runs both ratio tests and the mutual check on one distance matrix instead of calling `match_snn` both+ways. On CUDA (RTX 4090, 2,048 to 4,096 descriptors per image), `match_smnn` is 1.4-1.9x faster per pair, `match_snn`+1.2-1.3x and `match_mnn` up to 1.1x. Outputs are unchanged.diff --git a/changelog.d/6505.fixed.md b/changelog.d/6505.fixed.mdnew file mode 100644index 000000000..1812470cb--- /dev/null+++ b/changelog.d/6505.fixed.md@@ -0,0 +1 @@+On CPU, `match_mnn`, `match_smnn` and `match_fginn` with `mutual=True` reduce the columns of a distance matrix of more than 1024 rows in blocks of 512 rows. A column reduction over all rows walks each column with the stride of a row, which is slow when the row length is a power of two, as keypoint budgets usually are, and when there are many rows. On an Apple M1 with 2,048 to 4,096 descriptors per image, `match_mnn` is 1.8-2.0x faster and `match_smnn` 1.4-1.55x. Outputs are unchanged. CUDA, MPS and exported graphs keep one reduction.diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex d687cbaa9..e91673532 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -119,6 +119,69 @@ def _no_match(dm: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:return dists, idxs+def _reduces_over_row_blocks(distance_matrix: torch.Tensor, block: int) -> bool:+ """Return whether a reduction over the rows of ``distance_matrix`` runs on blocks of ``block`` rows.++ On CPU, ``torch.min`` and ``torch.topk`` over the rows of a row-major ``(B1, B2)`` matrix walk each column with a+ stride of ``B2`` elements, which is slow when ``B2`` is a power of two, as keypoint budgets usually are, or when+ ``B1`` is large. On an Apple M1, the column minimum of a ``(2048, 2048)`` matrix costs 7 times its row minimum and+ 3 times the distance matrix itself. The same kernels run on blocks of ``block`` rows, then on the few results of+ the blocks: 2.4 times faster there, 2.7 times for ``(4096, 4096)`` and 4 times for ``(8000, 8000)``. A matrix of+ at most ``2 * block`` rows gains little and keeps one reduction. So do CUDA and MPS, which reduce columns as fast+ as rows, and a traced or exported graph, which would record whether the last block is partial.+ """+ if distance_matrix.device.type != "cpu" or distance_matrix.size(0) <= 2 * block:+ return False+ return not (is_exporting() or torch.jit.is_tracing())+++def _min_over_rows(distance_matrix: torch.Tensor, block: int = 512) -> Tuple[torch.Tensor, torch.Tensor]:+ """Return each column's minimum and its row, bitwise as ``torch.min(distance_matrix, dim=0)``.++ On CPU a matrix of more than ``2 * block`` rows is reduced in blocks of rows, see+ :func:`_reduces_over_row_blocks`. ``torch.min`` returns the first of tied minima and the first nan of a column,+ and the minimum over the blocks keeps the first block's, so the values, rows and gradients are those of one+ reduction.+ """+ if not _reduces_over_row_blocks(distance_matrix, block):+ return torch.min(distance_matrix, dim=0)+ rows = distance_matrix.size(0)+ full = rows - rows % block+ vals, idxs = distance_matrix[:full].reshape(full // block, block, -1).min(dim=1)+ idxs = idxs + torch.arange(0, full, block, device=distance_matrix.device)[:, None]+ if full < rows:+ rest_vals, rest_idxs = distance_matrix[full:].min(dim=0)+ vals, idxs = torch.cat([vals, rest_vals[None]]), torch.cat([idxs, rest_idxs[None] + full])+ best, first_block = vals.min(dim=0)+ return best, idxs.gather(0, first_block[None])[0]+++def _nearest_neighbour_ratio_over_rows(+ distance_matrix: torch.Tensor, block: int = 512+) -> Tuple[torch.Tensor, torch.Tensor]:+ """Return :func:`_nearest_neighbour_ratio` of ``distance_matrix.t()``: the ratio test of each column.++ On CPU a matrix of more than ``2 * block`` rows takes the two smallest distances of each block of rows with+ ``torch.topk``, then the two smallest of those, see :func:`_reduces_over_row_blocks`. The two smallest values+ are those of one ``torch.topk``, so the ratios are bitwise the same, apart from the sign of a nan ratio (x86+ bfloat16 division gives ``-nan`` in its vectorised kernel and ``+nan`` in the strided one), and so is a unique+ nearest row. Of tied nearest rows it may return another one: ``torch.topk`` orders no ties. Such a column's ratio+ is 1 or nan, which the ratio test of :func:`match_smnn` rejects for any ``th < 1``.+ """+ if not _reduces_over_row_blocks(distance_matrix, block):+ return _nearest_neighbour_ratio(distance_matrix.t())+ rows, cols = distance_matrix.shape+ full = rows - rows % block+ vals, idxs = distance_matrix[:full].reshape(full // block, block, cols).topk(2, dim=1, largest=False)+ idxs = idxs + torch.arange(0, full, block, device=distance_matrix.device)[:, None, None]+ vals, idxs = vals.reshape(-1, cols), idxs.reshape(-1, cols)+ if full < rows:+ rest_vals, rest_idxs = distance_matrix[full:].topk(min(2, rows - full), dim=0, largest=False)+ vals, idxs = torch.cat([vals, rest_vals]), torch.cat([idxs, rest_idxs + full])+ best, pick = vals.topk(2, dim=0, largest=False)+ return best[0] / best[1], idxs.gather(0, pick[:1])[0]++def match_nn(desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:@@ -204,18 +267,19 @@ def match_mnn(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)+ match_dists2, idxs_in_1 = _min_over_rows(distance_matrix)minsize_idxs = torch.arange(ms, device=distance_matrix.device)+ # One nonzero is the only wait for the device: indexing with the boolean mask would wait once per indexed tensor.if distance_matrix.size(0) <= distance_matrix.size(1):- mutual_nns = minsize_idxs == idxs_in_1[idxs_in_2][:ms]- matches_idxs = torch.cat([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], 1)[mutual_nns]- match_dists = match_dists[mutual_nns]+ mutual = torch.nonzero(minsize_idxs == idxs_in_1[idxs_in_2][:ms])[:, 0] # rows of desc1+ matches_idxs = torch.stack([mutual, idxs_in_2[mutual]], 1)+ match_dists = match_dists[mutual]else:- mutual_nns = minsize_idxs == idxs_in_2[idxs_in_1][:ms]- matches_idxs = torch.cat([idxs_in_1.view(-1, 1), minsize_idxs.view(-1, 1)], 1)[mutual_nns]- match_dists = match_dists2[mutual_nns]- return match_dists.view(-1, 1), matches_idxs.view(-1, 2)+ mutual = torch.nonzero(minsize_idxs == idxs_in_2[idxs_in_1][:ms])[:, 0] # rows of desc2+ matches_idxs = torch.stack([idxs_in_1[mutual], mutual], 1)+ match_dists = match_dists2[mutual]+ return match_dists.view(-1, 1), matches_idxsdef _first_to_second_nearest_ratio(distance_matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:@@ -249,6 +313,18 @@ def _first_to_second_nearest_ratio(distance_matrix: torch.Tensor) -> Tuple[torchreturn torch.where(defined, ratio, (first / second).detach()), first_idx+def _nearest_neighbour_ratio(distance_matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """Return each row's nearest column and its ratio of the nearest to the second-nearest distance.++ The ratio test of :func:`match_snn` and :func:`match_smnn`: :func:`_first_to_second_nearest_ratio` on MPS and+ ``torch.topk`` elsewhere. A row needs at least two columns.+ """+ if is_mps_tensor_safe(distance_matrix):+ return _first_to_second_nearest_ratio(distance_matrix)+ vals, idxs = torch.topk(distance_matrix, 2, dim=1, largest=False)+ return vals[:, 0] / vals[:, 1], idxs[:, 0]++def match_snn(desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:@@ -279,19 +355,13 @@ def match_snn(if desc1.shape[0] == 0 or desc2.shape[0] < 2: # We cannot perform snn check, so output empty matchesreturn _no_match(desc1)distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)- if is_mps_tensor_safe(distance_matrix):- ratio, idxs_in_2 = _first_to_second_nearest_ratio(distance_matrix)- else:- vals, idxs = torch.topk(distance_matrix, 2, dim=1, largest=False)- ratio, idxs_in_2 = vals[:, 0] / vals[:, 1], idxs[:, 0]- mask = ratio <= th- match_dists = ratio[mask]- if len(match_dists) == 0:+ ratio, idxs_in_2 = _nearest_neighbour_ratio(distance_matrix)+ # One nonzero is the only wait for the device: indexing with the boolean mask would wait once per indexed tensor.+ idxs_in1 = torch.nonzero(ratio <= th)[:, 0]+ if idxs_in1.numel() == 0:return _no_match(distance_matrix)- idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask]- idxs_in_2 = idxs_in_2[mask]- matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)- return match_dists.view(-1, 1), matches_idxs.view(-1, 2)+ matches_idxs = torch.stack([idxs_in1, idxs_in_2[idxs_in1]], 1)+ return ratio[idxs_in1].view(-1, 1), matches_idxsdef match_smnn(@@ -326,23 +396,18 @@ def match_smnn(if (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)- dists2, idx2 = match_snn(desc2, desc1, th, distance_matrix.t())-- if len(dists2) > 0 and len(dists1) > 0:- # Each target occurs at most once in idx2. Join on its integer index instead of- # comparing every pair of matches in floating point (quadratic memory and inexact in half).- reverse_lookup = torch.full((desc2.size(0),), -1, dtype=torch.long, device=idx2.device)- reverse_lookup[idx2[:, 0]] = torch.arange(idx2.size(0), device=idx2.device)- reverse_positions = reverse_lookup[idx1[:, 1]]- mutual = (reverse_positions >= 0) & (idx2[reverse_positions, 1] == idx1[:, 0])- # match_snn already returns source indices in ascending order.- matches_idxs = idx1[mutual]- match_dists = torch.maximum(dists1[mutual], dists2[reverse_positions[mutual]])- else:- match_dists, matches_idxs = _no_match(distance_matrix)- return match_dists, matches_idxs+ ratio1, nearest2 = _nearest_neighbour_ratio(distance_matrix)+ ratio2, nearest1 = _nearest_neighbour_ratio_over_rows(distance_matrix)+ # Join the two directions on integer indices: i and nearest2[i] are mutual when nearest1[nearest2[i]] == i. Both+ # ratio tests and the mutual check form one mask, so one nonzero is the only wait for the device.+ reverse_ratio = ratio2[nearest2]+ mutual = nearest1[nearest2] == torch.arange(distance_matrix.size(0), device=distance_matrix.device)+ idxs_in1 = torch.nonzero(mutual & (ratio1 <= th) & (reverse_ratio <= th))[:, 0]+ if idxs_in1.numel() == 0:+ return _no_match(distance_matrix)+ matches_idxs = torch.stack([idxs_in1, nearest2[idxs_in1]], 1)+ match_dists = torch.maximum(ratio1[idxs_in1], reverse_ratio[idxs_in1])+ return match_dists.view(-1, 1), matches_idxsdef match_smnn_batched(@@ -559,7 +624,7 @@ def match_fginn(if not mutual: # returning 1-way matchesreturn match_dists, matches_idxs- _, idxs_in_1_mut = torch.min(distance_matrix, dim=0)+ _, idxs_in_1_mut = _min_over_rows(distance_matrix)good_mask = matches_idxs[:, 0] == idxs_in_1_mut[matches_idxs[:, 1]]return match_dists[good_mask], matches_idxs[good_mask]diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.pyindex 70b322499..5039c9134 100644--- a/tests/feature/test_matching.py+++ b/tests/feature/test_matching.py@@ -16,6 +16,7 @@#import math+import warningsimport pytestimport torch@@ -32,6 +33,9 @@ from kornia.feature.matching import (GeometryAwareDescriptorMatcher,_cdist,_first_to_second_nearest_ratio,+ _min_over_rows,+ _nearest_neighbour_ratio,+ _nearest_neighbour_ratio_over_rows,match_adalam,match_fginn,match_mnn,@@ -45,6 +49,30 @@ from testing.base import BaseTester, supports_matmulfrom testing.casts import dict_to+def _host_synchronizations(match, *args):+ """Count the CUDA host synchronizations of one call to ``match``, after a warm-up call."""+ match(*args)+ torch.cuda.synchronize()+ previous = torch.cuda.get_sync_debug_mode()+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ torch.cuda.set_sync_debug_mode("warn")+ try:+ match(*args)+ finally:+ torch.cuda.set_sync_debug_mode(previous)+ return sum("called a synchronizing CUDA operation" in str(warning.message) for warning in caught)+++def _descriptors_with_planted_matches(device, swap):+ """300 and 280 unit descriptors whose first 200 are noisy copies of each other, in either order."""+ gen = torch.Generator().manual_seed(0)+ desc1 = torch.randn(300, 32, generator=gen)+ desc2 = torch.cat([desc1[:200] + 0.05 * torch.randn(200, 32, generator=gen), torch.randn(80, 32, generator=gen)])+ desc1, desc2 = (torch.nn.functional.normalize(d, dim=1).to(device) for d in (desc1, desc2))+ return (desc2, desc1) if swap else (desc1, desc2)++class TestMatchNN(BaseTester):@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32)])def test_shape(self, num_desc1, num_desc2, dim, device):@@ -106,6 +134,20 @@ class TestMatchMNN(BaseTester):desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)self.gradcheck(match_mnn, (desc1, desc2), nondet_tol=1e-4)+ def test_larger_desc1_lists_matches_in_desc2_order(self, device):+ # With more descriptors in desc1 than in desc2, the matches come in the order of desc2: 2 -> 0, then 1 -> 1.+ desc1 = torch.tensor([[0.0], [1.0], [5.0]], device=device)+ desc2 = torch.tensor([[4.8], [1.1]], device=device)+ dists, idxs = match_mnn(desc1, desc2)+ self.assert_close(idxs, torch.tensor([[2, 0], [1, 1]], device=device))+ self.assert_close(dists, torch.tensor([[0.2], [0.1]], device=device))++ @pytest.mark.parametrize("swap", [False, True])+ def test_waits_for_the_device_once(self, device, swap):+ if device.type != "cuda":+ pytest.skip("Host synchronization is observable on CUDA only.")+ assert _host_synchronizations(match_mnn, *_descriptors_with_planted_matches(device, swap)) == 1+class TestMatchSNN(BaseTester):@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])@@ -174,6 +216,12 @@ class TestMatchSNN(BaseTester):else:match_snn(desc1, desc2, 0.8)+ @pytest.mark.parametrize("swap", [False, True])+ def test_waits_for_the_device_once(self, device, swap):+ if device.type != "cuda":+ pytest.skip("Host synchronization is observable on CUDA only.")+ assert _host_synchronizations(match_snn, *_descriptors_with_planted_matches(device, swap), 0.9) == 1+class TestFirstToSecondNearestRatio(BaseTester):"""The ratio that match_snn and match_smnn take from two row reductions on MPS, checked on every device."""@@ -274,6 +322,122 @@ class TestFirstToSecondNearestRatio(BaseTester):self.assert_close(column[number], expected_column[number])+def _assert_bitwise_equal(actual, expected):+ """Assert two tensors hold the same values bit for bit: nan where nan, and the sign of every zero."""+ assert actual.dtype == expected.dtype+ assert actual.shape == expected.shape+ nan = torch.isnan(expected)+ assert torch.equal(torch.isnan(actual), nan)+ assert torch.equal(actual.nan_to_num(0.0), expected.nan_to_num(0.0))+ # The sign of a nan is not part of its value: x86 bfloat16 division returns -nan from its vectorised kernel and+ # +nan from the strided one.+ assert torch.equal(torch.signbit(actual)[~nan], torch.signbit(expected)[~nan])+++def _distances_with_ties_and_nonfinite(rows, cols, device, dtype, levels=7):+ """A ``(rows, cols)`` matrix of integers below ``levels`` with -0, +inf and nan, a column of +inf and one of nan."""+ flat = torch.arange(rows * cols, device=device)+ dm = (flat * 7919 % levels).to(dtype)+ dm = torch.where(flat % 23 == 0, -0.0, dm)+ dm = torch.where(flat % 17 == 0, float("inf"), dm)+ dm = torch.where(flat % 29 == 0, float("nan"), dm).reshape(rows, cols)+ dm[:, 3] = float("inf") # a column without a number+ dm[:, 5] = float("nan") # a column of nan+ return dm+++class TestReductionsOverRowBlocks(BaseTester):+ """The column reductions of match_mnn, match_smnn and match_fginn, which run on blocks of rows on CPU."""++ # Blocks of 4 rows: no partial block, a partial block of one row, one of three rows, and too few rows to block.+ @pytest.mark.parametrize("rows", [16, 17, 19, 8])+ def test_min_over_rows_is_torch_min_bitwise(self, device, dtype, rows):+ dm = _distances_with_ties_and_nonfinite(rows, 9, device, dtype)+ values, idxs = _min_over_rows(dm, block=4)+ expected_values, expected_idxs = torch.min(dm, dim=0)+ _assert_bitwise_equal(values, expected_values)+ assert torch.equal(idxs, expected_idxs)++ @pytest.mark.parametrize("rows", [16, 17, 19, 8])+ def test_ratio_over_rows_is_the_ratio_of_the_transpose(self, device, dtype, rows):+ # 41 levels leave most columns a unique nearest row, and some tied ones.+ dm = _distances_with_ties_and_nonfinite(rows, 40, device, dtype, levels=41)+ ratio, nearest = _nearest_neighbour_ratio_over_rows(dm, block=4)+ expected_ratio, expected_nearest = _nearest_neighbour_ratio(dm.t())+ _assert_bitwise_equal(ratio, expected_ratio)+ # torch.topk orders no ties, so a tied nearest row may be another one of the tied rows. Such a column's ratio+ # is 1 or nan, which a ratio test with th < 1 rejects; a ratio below 1 has a unique nearest row.+ unique = expected_ratio < 1+ assert unique.sum() > 10+ assert (~unique).sum() >= 2+ assert torch.equal(nearest[unique], expected_nearest[unique])++ def test_blocks_run_on_cpu_only(self, device):+ dm = torch.rand(9, 3, device=device)+ assert matching._reduces_over_row_blocks(dm, 4) == (device.type == "cpu")+ assert not matching._reduces_over_row_blocks(dm[:8], 4)++ def test_gradcheck(self, device):+ dm = torch.rand(11, 5, device=device, dtype=torch.float64)+ self.gradcheck(lambda x: _min_over_rows(x, block=4)[0], (dm,))+ self.gradcheck(lambda x: _nearest_neighbour_ratio_over_rows(x, block=4)[0], (dm,))++ @pytest.mark.parametrize("traced_rows, rows", [(12, 13), (13, 12)])+ def test_traced_graph_keeps_one_reduction(self, device, traced_rows, rows):+ # A trace records whether the last block is partial: traced with 12 rows, blocks of 4 would drop the 13th+ # row of a later input, and traced with 13, they would reduce an empty 13th row of 12. Tracing takes one+ # reduction instead.+ def column_min(dm):+ return _min_over_rows(dm, block=4)++ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ traced = torch.jit.trace(column_min, torch.rand(traced_rows, 3, device=device))+ dm = torch.rand(rows, 3, device=device)+ dm[-1] = -1.0 # the minimum of every column is in the last row+ values, idxs = traced(dm)+ expected_values, expected_idxs = torch.min(dm, dim=0)+ self.assert_close(values, expected_values)+ assert torch.equal(idxs, expected_idxs)++ @pytest.mark.parametrize("matcher", ["mnn", "smnn", "fginn"])+ @pytest.mark.parametrize("swap", [False, True])+ def test_matchers_return_what_one_reduction_returns(self, device, matcher, swap, monkeypatch):+ # 1300 and 1100 descriptors: more than two blocks of 512 rows either way round, and a partial block.+ gen = torch.Generator().manual_seed(0)+ desc1 = torch.randn(1300, 32, generator=gen)+ desc2 = torch.cat(+ [desc1[:900] + 0.1 * torch.randn(900, 32, generator=gen), torch.randn(200, 32, generator=gen)]+ )+ desc1, desc2 = (torch.nn.functional.normalize(d, dim=1).to(device) for d in (desc1, desc2))+ desc1, desc2 = (desc2, desc1) if swap else (desc1, desc2)++ def run():+ if matcher == "mnn":+ return match_mnn(desc1, desc2)+ if matcher == "smnn":+ return match_smnn(desc1, desc2, 0.95)+ lafs1, lafs2 = (laf_from_center_scale_ori(10 * d[None, :, :2]) for d in (desc1, desc2))+ return match_fginn(desc1, desc2, lafs1, lafs2, 0.95, 0.1, mutual=True)++ blocked = []+ reduces_over_row_blocks = matching._reduces_over_row_blocks++ def recording(dm, block):+ blocked.append(reduces_over_row_blocks(dm, block))+ return blocked[-1]++ monkeypatch.setattr(matching, "_reduces_over_row_blocks", recording)+ dists, idxs = run()+ assert blocked+ assert all(blocked) == (device.type == "cpu")+ monkeypatch.setattr(matching, "_reduces_over_row_blocks", lambda dm, block: False)+ expected_dists, expected_idxs = run()+ assert idxs.shape[0] > 100+ _assert_bitwise_equal(dists, expected_dists)+ assert torch.equal(idxs, expected_idxs)++class TestMatchSMNN(BaseTester):@pytest.mark.parametrize("mps_fallback", [False, True])def test_mutual_matches_keep_integer_indices(self, device, dtype, monkeypatch, mps_fallback):@@ -419,6 +583,36 @@ class TestMatchSMNN(BaseTester):self.assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2)[0])self.assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2)[1])+ @pytest.mark.parametrize("swap", [False, True])+ def test_waits_for_the_device_once(self, device, swap):+ if device.type != "cuda":+ pytest.skip("Host synchronization is observable on CUDA only.")+ assert _host_synchronizations(match_smnn, *_descriptors_with_planted_matches(device, swap), 0.9) == 1++ @pytest.mark.parametrize("swap", [False, True])+ def test_matches_the_definition_on_random_descriptors(self, device, dtype, swap):+ # Reference: (i, j) is a match when j is the nearest neighbour of i and i that of j, and both ratios of the+ # nearest to the second-nearest distance are <= th; its ratio is the larger one. Sorted by i. The reference+ # reads the matcher's own distance matrix, and divides and compares in its dtype on its device, so it pins the+ # join rather than how another device or dtype rounds near ties and near th.+ desc1, desc2 = (d.to(dtype) for d in _descriptors_with_planted_matches(device, swap))+ th = 0.9+ dm = _cdist(desc1, desc2)+ dists, idxs = match_smnn(desc1, desc2, th, dm=dm)+ rows, cols = dm.sort(dim=1), dm.t().sort(dim=1)+ ratios1 = rows.values[:, 0] / rows.values[:, 1]+ ratios2 = cols.values[:, 0] / cols.values[:, 1]+ passes1, passes2 = (ratios1 <= th).tolist(), (ratios2 <= th).tolist()+ nearest2, nearest1 = rows.indices[:, 0].tolist(), cols.indices[:, 0].tolist()+ expected_idxs, expected_dists = [], []+ for i, j in enumerate(nearest2):+ if nearest1[j] == i and passes1[i] and passes2[j]:+ expected_idxs.append([i, j])+ expected_dists.append(torch.maximum(ratios1[i], ratios2[j]))+ assert len(expected_idxs) > 100+ assert torch.equal(idxs, torch.tensor(expected_idxs, device=device))+ assert torch.equal(dists, torch.stack(expected_dists).view(-1, 1))+class TestMatchFGINN(BaseTester):@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)])