π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(feature): match_snn/match_smnn ratio test with two row reductions instead of topk on MPS (M1 ~2.3x snn) (#6465)
Dmytro Mishkine30fb1026af5
diff --git a/changelog.d/6465.added.md b/changelog.d/6465.added.mdnew file mode 100644index 000000000..41209973c--- /dev/null+++ b/changelog.d/6465.added.md@@ -0,0 +1 @@+On MPS, `match_snn` and `match_smnn` find the nearest and second-nearest distance of each descriptor with two row reductions instead of `torch.topk`, with the same matches and ratios, nan and infinite distances included. On an Apple M1, given 2048 x 2048 to 8000 x 8000 distance matrices, `match_snn` is 2.3x faster and `match_smnn` 1.5-1.8x faster; with the distance computation, both are 1.2-1.7x faster. The reductions take a transient copy of the distance matrix, 2.25 times its size for `match_smnn`. CPU and CUDA keep `torch.topk`, which is faster there: the reductions were 2-5x slower on an x86 CPU and no faster on CUDA.diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex 23c983691..d687cbaa9 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -218,6 +218,37 @@ def match_mnn(return match_dists.view(-1, 1), matches_idxs.view(-1, 2)+def _first_to_second_nearest_ratio(distance_matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """Return each row's ratio of the smallest to the second-smallest distance, and the column of the smallest.++ :func:`match_snn` calls this on MPS in place of ``torch.topk(distance_matrix, 2, dim=1, largest=False)``, which+ is two to three times slower there. Elsewhere ``torch.topk`` is at least as fast: as fast on CUDA, and two to five+ times faster on an x86 CPU, where it reads the matrix about once and these reductions several times. The ratios+ are those of ``torch.topk``, which orders nan after ``+inf``. Where a ratio is a number, its column is that of the+ smallest distance, the first of tied ones. A row without a finite smallest and a finite, non-zero second-smallest+ distance gets no gradient. A row needs at least two columns.+ """+ inf = float("inf")+ # A row-major copy of the transposed matrix that match_smnn passes; the MPS timings of #6465 were taken with it.+ dm = distance_matrix.contiguous()+ is_nan = torch.isnan(dm)+ remaining = torch.nan_to_num(dm, nan=inf, posinf=inf, neginf=-inf)+ first, first_idx = remaining.min(dim=1)+ idx = first_idx[:, None]+ # Overwrite the smallest with another distance of its row, which keeps the minimum of the others. It is read from+ # `dm`, not from `remaining`: autograd must not save a tensor that is then modified in place.+ other = dm.gather(1, (idx == 0).long())+ remaining.scatter_(1, idx, torch.nan_to_num(other, nan=inf, posinf=inf, neginf=-inf))+ # Ordered after +inf, a nan is the second-smallest distance only when every other distance of the row is nan.+ no_second = is_nan.scatter_(1, idx, True).all(dim=1)+ second = torch.where(no_second, float("nan"), remaining.amin(dim=1))+ # Without such a pair the quotient's gradient is nan or infinite, and amin's backward would spread it over every+ # distance of the row. Those rows keep the quotient as their ratio, but detached.+ defined = torch.isfinite(first) & torch.isfinite(second) & (second != 0)+ ratio = torch.where(defined, first, 0) / torch.where(defined, second, 1)+ return torch.where(defined, ratio, (first / second).detach()), first_idx++def match_snn(desc1: torch.Tensor, desc2: torch.Tensor, th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:@@ -248,14 +279,17 @@ 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)- vals, idxs_in_2 = torch.topk(distance_matrix, 2, dim=1, largest=False)- ratio = vals[:, 0] / vals[:, 1]+ 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 <= thmatch_dists = ratio[mask]if len(match_dists) == 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[:, 0][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)diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.pyindex 35699135a..70b322499 100644--- a/tests/feature/test_matching.py+++ b/tests/feature/test_matching.py@@ -31,6 +31,7 @@ from kornia.feature.matching import (DescriptorMatcherWithSteerer,GeometryAwareDescriptorMatcher,_cdist,+ _first_to_second_nearest_ratio,match_adalam,match_fginn,match_mnn,@@ -159,6 +160,119 @@ class TestMatchSNN(BaseTester):desc2 = torch.rand(7, 8, device=device, dtype=torch.float64)self.gradcheck(match_snn, (desc1, desc2, 0.8), nondet_tol=1e-4)+ def test_mps_alone_uses_two_row_reductions(self, device, monkeypatch):+ # torch.topk is two to five times faster than the two row reductions on x86 CPUs, and as fast on CUDA (#6465)+ def two_row_reductions(*args):+ raise AssertionError("two row reductions")++ monkeypatch.setattr(matching, "_first_to_second_nearest_ratio", two_row_reductions)+ desc1 = torch.rand(4, 8, device=device)+ desc2 = torch.rand(5, 8, device=device)+ if device.type == "mps":+ with pytest.raises(AssertionError, match="two row reductions"):+ match_snn(desc1, desc2, 0.8)+ else:+ match_snn(desc1, desc2, 0.8)+++class TestFirstToSecondNearestRatio(BaseTester):+ """The ratio that match_snn and match_smnn take from two row reductions on MPS, checked on every device."""++ def test_nonfinite_distances_and_ties(self, device, dtype):+ # nan is ordered after +inf, as by torch.topk: it is a neighbour only when no number is left in the row+ nan, inf = float("nan"), float("inf")+ dm = torch.tensor(+ [+ [1.0, nan, 2.0], # 1 / 2+ [nan, 3.0, 1.0], # 1 / 3+ [1.0, nan, nan], # no second neighbour: nan+ [1.0, nan, inf], # an infinitely far second neighbour: 0+ [nan, nan, nan], # nan+ [2.0, 2.0, 5.0], # a tie: 1, at the first tied column+ [4.0, 1.0, inf], # 1 / 4+ ],+ device=device,+ dtype=dtype,+ )+ expected = torch.tensor([1 / 2, 1 / 3, nan, 0.0, nan, 1.0, 1 / 4], device=device, dtype=dtype)++ ratio, column = _first_to_second_nearest_ratio(dm)++ number = ~torch.isnan(expected)+ assert torch.equal(torch.isnan(ratio), ~number)+ self.assert_close(ratio[number], expected[number])+ self.assert_close(column[number], torch.tensor([0, 2, 0, 0, 1], device=device))++ def test_tied_nearest_neighbours_take_the_first_column(self, device, dtype):+ # torch.topk returns the last of these tied columns on CPU and the first on MPS+ dm = torch.full((2, 3000), 2.0, device=device, dtype=dtype)+ dm[:, [2000, 2500]] = 1.0+ ratio, column = _first_to_second_nearest_ratio(dm)+ self.assert_close(ratio, torch.ones(2, device=device, dtype=dtype))+ self.assert_close(column, torch.tensor([2000, 2000], device=device))++ @pytest.mark.parametrize("transposed", [False, True])+ def test_matches_topk(self, device, dtype, transposed):+ # Small integers make many ties; every 11th distance is nan and every 17th +inf. match_smnn passes the+ # transposed matrix for its second direction.+ flat = torch.arange(40 * 30, device=device)+ dm = (flat * 7919 % 13).to(dtype)+ dm = torch.where(flat % 17 == 0, float("inf"), dm)+ dm = torch.where(flat % 11 == 0, float("nan"), dm).reshape(40, 30)+ dm = dm.t() if transposed else dm++ ratio, column = _first_to_second_nearest_ratio(dm)++ values, columns = torch.topk(dm, 2, dim=1, largest=False)+ expected = values[:, 0] / values[:, 1]+ number = ~torch.isnan(expected)+ assert torch.equal(torch.isnan(ratio), ~number)+ self.assert_close(ratio[number], expected[number])+ # A ratio below 1, the only kind a ratio test with th < 1 accepts, has a unique nearest neighbour.+ unique = expected < 1+ assert unique.any()+ self.assert_close(column[unique], columns[unique, 0])++ @pytest.mark.parametrize("int_dtype", [torch.int32, torch.int64])+ def test_integer_distance_matrix(self, device, int_dtype):+ # an integer dm, such as Hamming distances between binary descriptors+ dm = torch.tensor([[2, 3, 5], [4, 4, 1], [7, 1, 9]], device=device, dtype=int_dtype)+ ratio, column = _first_to_second_nearest_ratio(dm)+ # promoted to the default floating dtype, as an integer division is+ assert ratio.dtype == torch.get_default_dtype()+ self.assert_close(ratio, torch.tensor([2 / 3, 1 / 4, 1 / 7], device=device))+ self.assert_close(column, torch.tensor([0, 2, 1], device=device))+ desc = torch.zeros(3, 2, device=device)+ dists, idxs = match_snn(desc, desc, 0.8, dm)+ self.assert_close(dists, torch.tensor([[2 / 3], [1 / 4], [1 / 7]], device=device))+ self.assert_close(idxs, torch.tensor([[0, 0], [1, 2], [2, 1]], device=device))++ def test_undefined_ratio_gets_no_gradient(self, device):+ # The first row's ratio is 0 / 0. Its quotient's nan gradient would reach every distance of the row through+ # amin's backward, and from there every descriptor of desc2.+ dm = torch.tensor([[0.0, 0.0, 3.0], [2.0, 4.0, 1.0]], device=device, requires_grad=True)+ ratio, _ = _first_to_second_nearest_ratio(dm)+ assert torch.isnan(ratio[0])+ ratio[1].backward()+ self.assert_close(dm.grad, torch.tensor([[0.0, 0.0, 0.0], [-0.25, 0.0, 0.5]], device=device))++ def test_gradcheck(self, device):+ dm = torch.rand(6, 7, device=device, dtype=torch.float64)+ self.gradcheck(lambda dm: _first_to_second_nearest_ratio(dm)[0], (dm,))++ def test_dynamo(self, device, dtype, torch_optimizer):+ flat = torch.arange(40 * 30, device=device)+ dm = (flat * 7919 % 13).to(dtype)+ dm = torch.where(flat % 11 == 0, float("nan"), dm).reshape(40, 30)+ op = torch_optimizer(_first_to_second_nearest_ratio)+ for x in (dm, dm.t()):+ expected_ratio, expected_column = _first_to_second_nearest_ratio(x)+ ratio, column = op(x)+ number = ~torch.isnan(expected_ratio)+ assert torch.equal(torch.isnan(ratio), ~number)+ self.assert_close(ratio[number], expected_ratio[number])+ self.assert_close(column[number], expected_column[number])+class TestMatchSMNN(BaseTester):@pytest.mark.parametrize("mps_fallback", [False, True])