π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(losses): reduce total_variation over a flattened dim (#4547)
Dipak Chaudhariae38838b32e9
diff --git a/changelog.d/4547.fixed.md b/changelog.d/4547.fixed.mdnew file mode 100644index 000000000..77d3440e2--- /dev/null+++ b/changelog.d/4547.fixed.md@@ -0,0 +1 @@+`kornia.losses.total_variation` reduces over one flattened dimension instead of `dim=(-2, -1)`, which returns identical values and avoids a slow reduction path on MPS.diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex 632346321..0b6e8ce15 100644--- a/kornia/losses/total_variation.py+++ b/kornia/losses/total_variation.py@@ -60,20 +60,21 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:pixel_dif1 = img[..., 1:, :] - img[..., :-1, :]pixel_dif2 = img[..., :, 1:] - img[..., :, :-1]- res1 = pixel_dif1.abs()- res2 = pixel_dif2.abs()+ # Reduce over one flattened dim rather than dim=(-2, -1): the result is identical,+ # and MPS runs a two-trailing-dims reduction several times slower than a one-dim one.+ res1 = pixel_dif1.abs().flatten(-2)+ res2 = pixel_dif2.abs().flatten(-2)- reduce_axes = (-2, -1)if reduction == "mean":if img.is_floating_point():- res1 = res1.to(img).mean(dim=reduce_axes)- res2 = res2.to(img).mean(dim=reduce_axes)+ res1 = res1.to(img).mean(dim=-1)+ res2 = res2.to(img).mean(dim=-1)else:- res1 = res1.float().mean(dim=reduce_axes)- res2 = res2.float().mean(dim=reduce_axes)+ res1 = res1.float().mean(dim=-1)+ res2 = res2.float().mean(dim=-1)elif reduction == "sum":- res1 = res1.sum(dim=reduce_axes)- res2 = res2.sum(dim=reduce_axes)+ res1 = res1.sum(dim=-1)+ res2 = res2.sum(dim=-1)else:raise NotImplementedError("Invalid reduction option.")diff --git a/tests/losses/test_total_variation.py b/tests/losses/test_total_variation.pyindex e7cbea84e..987492db3 100644--- a/tests/losses/test_total_variation.py+++ b/tests/losses/test_total_variation.py@@ -142,6 +142,27 @@ class TestTotalVariation(BaseTester):actual = kornia.losses.total_variation(pred, reduction=reduction)self.assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)+ @pytest.mark.parametrize("layout", ["contiguous", "channels_last", "permuted"])+ @pytest.mark.parametrize("reduction", ["sum", "mean"])+ def test_tv_matches_the_two_dim_reduction(self, device, dtype, layout, reduction):+ # The reduction runs over flatten(-2) rather than dim=(-2, -1); the two must agree+ # for any memory layout the flatten has to copy, not only a contiguous input.+ pred = torch.rand(2, 3, 6, 7, device=device, dtype=dtype)+ if layout == "channels_last":+ pred = pred.contiguous(memory_format=torch.channels_last)+ elif layout == "permuted":+ pred = pred.permute(0, 1, 3, 2)++ dif1 = (pred[..., 1:, :] - pred[..., :-1, :]).abs()+ dif2 = (pred[..., :, 1:] - pred[..., :, :-1]).abs()+ if reduction == "sum":+ expected = dif1.sum(dim=(-2, -1)) + dif2.sum(dim=(-2, -1))+ else:+ expected = dif1.mean(dim=(-2, -1)) + dif2.mean(dim=(-2, -1))++ actual = kornia.losses.total_variation(pred, reduction=reduction)+ self.assert_close(actual, expected)+# Expect TypeError to be raised when non-torch tensors are passed@pytest.mark.parametrize("pred", [1, [1, 2]])def test_tv_on_invalid_types(self, device, dtype, pred):