π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): Prevent integer overflow in total variation (#5439)
A Aswanth Raj8c40568f6cf0
diff --git a/changelog.d/5439.fixed.md b/changelog.d/5439.fixed.mdnew file mode 100644index 000000000..4d09279e8--- /dev/null+++ b/changelog.d/5439.fixed.md@@ -0,0 +1 @@+`total_variation` and `TotalVariation` avoid overflow in adjacent differences for uint8, int8, int16, and int32 images, preserving the output dtypes for both reductions.diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex 0b6e8ce15..cf1c88454 100644--- a/kornia/losses/total_variation.py+++ b/kornia/losses/total_variation.py@@ -45,6 +45,7 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:See a working example `here <https://www.kornia.org/tutorials/nbs/total_variation_denoising.html>`__.Total Variation is formulated with summation, however this is not resolution invariant.Thus, `reduction='mean'` was added as an optional reduction method.+ Narrow integer inputs are promoted before computing differences to avoid overflow.Reference:[1] https://en.wikipedia.org/wiki/Total_variation@@ -57,6 +58,14 @@ def total_variation(img: torch.Tensor, reduction: str = "sum") -> torch.Tensor:KORNIA_CHECK_SHAPE(img, ["*", "H", "W"])KORNIA_CHECK(reduction in ("mean", "sum"), f"Expected reduction to be one of 'mean'/'sum', but got '{reduction}'.")+ # Adjacent differences and their absolute values can exceed the input integer range.+ if img.dtype in (torch.uint8, torch.int8):+ img = img.to(torch.int16)+ elif img.dtype == torch.int16:+ img = img.to(torch.int32)+ elif img.dtype == torch.int32:+ img = img.to(torch.int64)+pixel_dif1 = img[..., 1:, :] - img[..., :-1, :]pixel_dif2 = img[..., :, 1:] - img[..., :, :-1]diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex 2de26fd37..691223eeb 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",- 127,+ 148,"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.pyindex 987492db3..8713b0ec9 100644--- a/tests/losses/test_total_variation.py+++ b/tests/losses/test_total_variation.py@@ -48,6 +48,27 @@ class TestTotalVariation(BaseTester):actual = kornia.losses.total_variation(pred.to(device, dtype=torch.int32), reduction="mean")self.assert_close(actual, expected.to(device))+ @pytest.mark.parametrize("input_dtype", [torch.uint8, torch.int8, torch.int16, torch.int32])+ @pytest.mark.parametrize("shape", [(2, 3), (2, 3, 2, 3)])+ @pytest.mark.parametrize("reduction", ["sum", "mean"])+ def test_tv_integer_extrema(self, device, input_dtype, shape, reduction):+ limits = torch.iinfo(input_dtype)+ pred = torch.tensor(+ [[limits.max, limits.min, 0], [limits.max, limits.min, 0]], device=device, dtype=input_dtype+ ).expand(shape)+ # Four horizontal edges: two span the full range, two have magnitude abs(min).+ expected_sum = 2 * (limits.max - limits.min + abs(limits.min))+ expected = torch.tensor(expected_sum, device=device, dtype=torch.int64)+ if reduction == "mean":+ expected = expected.float() / 4+ expected = expected.expand(shape[:-2])++ self.assert_close(kornia.losses.total_variation(pred, reduction), expected)+ self.assert_close(kornia.losses.total_variation(pred.flip(-1), reduction), expected)+ self.assert_close(kornia.losses.total_variation(pred.transpose(-2, -1), reduction), expected)+ if reduction == "sum":+ self.assert_close(kornia.losses.TotalVariation()(pred), expected)+# Total variation for 3D tensors@pytest.mark.parametrize("pred, expected",@@ -177,6 +198,16 @@ class TestTotalVariation(BaseTester):self.assert_close(op(image), op_optimized(image))+ @pytest.mark.parametrize("input_dtype", [torch.uint8, torch.int8, torch.int16, torch.int32])+ @pytest.mark.parametrize("reduction", ["sum", "mean"])+ def test_dynamo_integer(self, device, input_dtype, reduction, torch_optimizer):+ limits = torch.iinfo(input_dtype)+ image = torch.tensor([[limits.max, limits.min], [limits.max, limits.min]], device=device, dtype=input_dtype)+ op = kornia.losses.total_variation+ op_optimized = torch_optimizer(op)++ self.assert_close(op(image, reduction), op_optimized(image, reduction))+def test_module(self, device, dtype):image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)