Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): keep mean total variation finite on singleton axes (#5891)

Devulapalli Naga Sri Vaishnavi97e4f9cb3ddb
diff --git a/changelog.d/5891.fixed.md b/changelog.d/5891.fixed.md
new file mode 100644
index 000000000..55fe51d09
--- /dev/null
+++ b/changelog.d/5891.fixed.md
@@ -0,0 +1 @@
+`total_variation` with `reduction="mean"` now returns finite values for one-row and one-column images, with axes that have no adjacent pixels contributing zero.
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index ccf89245b..0ad533cb3 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -32,7 +32,7 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:
summed.
- The default ``reduction='sum'`` adds the differences. ``'mean'`` averages each term over its own count,
:math:`(H - 1) W` vertical and :math:`H (W - 1)` horizontal differences, and adds the two means; it is not
- the sum divided by :math:`H W`. There is no ``'none'``.
+ the sum divided by :math:`H W`. An axis with no adjacent pixels contributes zero. There is no ``'none'``.
:ref:`Losses and metrics <losses-metrics-conventions>` compares both with torchmetrics.
Args:
@@ -84,12 +84,12 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:
res2 = pixel_dif2.abs().flatten(-2)
if reduction == "mean":
- if img.is_floating_point():
- res1 = res1.to(img).mean(dim=-1)
- res2 = res2.to(img).mean(dim=-1)
- else:
- res1 = res1.float().mean(dim=-1)
- res2 = res2.float().mean(dim=-1)
+ if not img.is_floating_point():
+ res1 = res1.float()
+ res2 = res2.float()
+ # A singleton spatial axis has no differences: sum the empty term to zero instead of averaging it to NaN.
+ res1 = res1.mean(dim=-1) if res1.shape[-1] > 0 else res1.sum(dim=-1)
+ res2 = res2.mean(dim=-1) if res2.shape[-1] > 0 else res2.sum(dim=-1)
elif reduction == "sum":
res1 = res1.sum(dim=-1)
res2 = res2.sum(dim=-1)
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index 8d3a38adc..85158d284 100644
--- a/testing/half_precision_eager_rng.py
+++ b/testing/half_precision_eager_rng.py
@@ -207,7 +207,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(
),
*_audited(
"tests/losses/test_total_variation.py",
- 149,
+ 190,
"torch.rand",
3,
("tests/losses/test_total_variation.py::TestTotalVariation::test_tv_shapes",),
diff --git a/tests/losses/test_total_variation.py b/tests/losses/test_total_variation.py
index b11ea00a3..faffa5d16 100644
--- a/tests/losses/test_total_variation.py
+++ b/tests/losses/test_total_variation.py
@@ -25,6 +25,47 @@ from testing.base import BaseTester
class TestTotalVariation(BaseTester):
+ @pytest.mark.parametrize("shape", [(1, 1), (1, 4), (4, 1), (2, 3, 1, 4), (2, 3, 4, 1)])
+ @pytest.mark.parametrize("reduction", ["sum", "mean"])
+ def test_singleton_spatial_axis(self, device, dtype, shape, reduction):
+ height, width = shape[-2:]
+ image = torch.arange(height * width, device=device, dtype=dtype).reshape(height, width).expand(shape)
+ expected_value = 0.0 if height == width == 1 else 1.0 if reduction == "mean" else 3.0
+ expected = torch.full(shape[:-2], expected_value, device=device, dtype=dtype)
+
+ self.assert_close(kornia.losses.total_variation(image, reduction), expected)
+
+ @pytest.mark.parametrize("shape", [(1, 1), (1, 4), (4, 1)])
+ @pytest.mark.parametrize("input_dtype", [torch.uint8, torch.int8, torch.int16, torch.int32])
+ def test_singleton_spatial_axis_integer(self, device, input_dtype, shape):
+ height, width = shape
+ image = torch.arange(height * width, device=device, dtype=input_dtype).reshape(shape)
+ expected = torch.tensor(0.0 if height == width == 1 else 1.0, device=device)
+
+ self.assert_close(kornia.losses.total_variation(image, reduction="mean"), expected)
+
+ @pytest.mark.parametrize("shape", [(1, 1), (1, 4), (4, 1)])
+ def test_singleton_spatial_axis_gradient(self, device, dtype, shape):
+ height, width = shape
+ image = torch.arange(height * width, device=device, dtype=dtype).reshape(shape).requires_grad_()
+ loss = kornia.losses.total_variation(image, reduction="mean")
+ loss.backward()
+ expected = torch.zeros_like(image).flatten()
+ if height * width > 1:
+ expected[0], expected[-1] = -1 / 3, 1 / 3
+
+ self.assert_close(loss, image.new_tensor(0.0 if height == width == 1 else 1.0))
+ self.assert_close(image.grad, expected.reshape(shape))
+
+ @pytest.mark.parametrize("shape", [(1, 1), (1, 4), (4, 1)])
+ def test_dynamo_singleton_spatial_axis(self, device, dtype, shape, torch_optimizer):
+ height, width = shape
+ image = torch.arange(height * width, device=device, dtype=dtype).reshape(shape)
+ expected = image.new_tensor(0.0 if height == width == 1 else 1.0)
+ op_optimized = torch_optimizer(kornia.losses.total_variation)
+
+ self.assert_close(op_optimized(image, reduction="mean"), expected)
+
# Total variation of constant vectors is 0
@pytest.mark.parametrize(
"pred, expected",