🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep perspective warps finite at extreme scales (#5752)
NIKHIL6e855f646f65
diff --git a/changelog.d/5752.fixed.md b/changelog.d/5752.fixed.mdnew file mode 100644index 000000000..7e15d29a9--- /dev/null+++ b/changelog.d/5752.fixed.md@@ -0,0 +1,7 @@+`warp_perspective` gives the same image for `s * M` as for `M`, and a finite homography gradient (`1/s` times the+gradient for `M`), when `s` is very large or very small. For a homography with entries between 0.01 and 1,+`1e15 * M` returned NaN images and `1e-12 * M` NaN gradients in float32, and `1e110 * M` and `1e-110 * M` returned NaN+images in float64. Under `torch.jit.trace` (float32 and float64) and the legacy ONNX exporter, `1e8 * M` already+sampled the wrong pixels without any NaN. A matrix whose nonzero entries all have magnitude above 1, or all have+magnitude below 1, is now divided by a detached scale before the warp, which changes its results at rounding level;+any other matrix, such as one with `M[2, 2] = 1`, gives bit-identical results.diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 264ee5cd5..17898dc30 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -229,6 +229,8 @@ def warp_perspective(- input: :math:`(B, C, H, W)`; ``dsize`` is ``(h, w)``- ``M`` is the source→destination **pixel** homography :math:`(B, 3, 3)`(contrast :func:`homography_warp`, which by default consumes destination→source normalized)+ - a nonzero scalar multiple of ``M`` describes the same warp; uniformly small or large+ nonzero entries are rescaled toward unit magnitude before the coordinate change and inversion- a zero output dimension returns an autograd-connected empty tensor;negative output dimensions raise ``ValueError``@@ -287,7 +289,19 @@ def warp_perspective(src, M, dsize, mode, padding_mode, align_corners, _matrix_warp_grid_dtype(src, M), fill_value)- # we F.normalize the 3x3 transformation matrix and convert to 3x4+ # H and s*H represent the same projective map. Remove that arbitrary scale before+ # the coordinate change and inverse: the cubic determinant can overflow/underflow+ # even when every entry, the sampling positions and their gradients are finite.+ # The scale is a projective gauge, so detaching it leaves the warp's derivative unchanged.+ if M.is_floating_point():+ magnitude = M.detach().abs()+ largest = magnitude.amax(dim=(-2, -1), keepdim=True)+ smallest = magnitude.masked_fill(magnitude == 0, float("inf")).amin(dim=(-2, -1), keepdim=True)+ # Choose the scale closest to 1 between the nonzero magnitudes. Dividing a large+ # translation by its maximum would instead shrink the unit diagonal toward zero.+ scale = torch.minimum(largest, torch.ones_like(largest)).clamp_min(smallest)+ M = M / torch.where(scale > 0, scale, torch.ones_like(scale))+dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M, (H, W), (h_out, w_out), align_corners=align_corners) # Bx3x3diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.pyindex 145270c36..074c92819 100644--- a/tests/geometry/transform/test_imgwarp.py+++ b/tests/geometry/transform/test_imgwarp.py@@ -654,6 +654,70 @@ class TestWarpAffine(BaseTester):class TestWarpPerspective(BaseTester):+ @pytest.mark.parametrize("align_corners", [False, True])+ @pytest.mark.parametrize("scale", [1e-15, -1e-15, 1e15, -1e15])+ def test_projective_scale_invariance(self, device, dtype, align_corners, scale):+ _skip_if_mps_lacks_grid_sample_backward(device)+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("these scales test the float32/float64 arithmetic range")+ if dtype == torch.float64:+ scale = (1e-110 if abs(scale) < 1 else 1e110) * (1 if scale > 0 else -1)+ image = torch.arange(36, device=device, dtype=dtype).reshape(1, 1, 6, 6) / 36+ matrix = torch.tensor([[[1.0, 0.1, 0.3], [0.05, 1.0, 0.2], [0.01, 0.02, 1.0]]], device=device, dtype=dtype)+ reference_matrix = matrix.clone().requires_grad_()+ scaled_matrix = (matrix * scale).requires_grad_()++ reference = kornia.geometry.warp_perspective(image, reference_matrix, (5, 7), align_corners=align_corners)+ actual = kornia.geometry.warp_perspective(image, scaled_matrix, (5, 7), align_corners=align_corners)+ reference_grad = torch.autograd.grad(reference.square().sum(), reference_matrix)[0]+ actual_grad = torch.autograd.grad(actual.square().sum(), scaled_matrix)[0]++ assert torch.isfinite(actual).all()+ assert torch.isfinite(actual_grad).all()+ self.assert_close(actual, reference)+ # H and s*H describe the same projective map: dL/d(s*H) = (dL/dH)/s.+ self.assert_close(actual_grad * scale, reference_grad)++ @pytest.mark.parametrize("align_corners", [False, True])+ def test_projective_scale_invariance_under_trace(self, device, dtype, align_corners):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("these scales test the float32/float64 arithmetic range")+ image = torch.arange(36, device=device, dtype=dtype).reshape(1, 1, 6, 6) / 36+ # A zero bottom-right entry is valid: scale normalization must use the whole matrix.+ matrix = torch.tensor([[[1.0, 0.1, 0.3], [0.05, 1.0, 0.2], [0.3, 0.2, 0.0]]], device=device, dtype=dtype)++ def warp(image, matrix):+ return kornia.geometry.warp_perspective(image, matrix, (5, 7), align_corners=align_corners)++ traced = torch.jit.trace(warp, (image, matrix))+ expected = warp(image, matrix)+ assert expected.count_nonzero() > 0 # samples inside the image, not only padding+ # 1e8 overflows nothing: the traced grid goes through transform_points, which leaves |w| <= 1e-8 undivided.+ scales = [1.0, 1e8, 1e-15, -1e15] if dtype == torch.float32 else [1.0, 1e8, 1e-110, -1e110]+ batched_matrix = matrix * torch.tensor(scales, device=device, dtype=dtype).reshape(-1, 1, 1)+ actual = traced(image.expand(len(scales), -1, -1, -1), batched_matrix)+ assert torch.isfinite(actual).all()+ self.assert_close(actual, expected.expand_as(actual))++ def test_homography_gradcheck(self, device):+ _skip_if_mps_lacks_grid_sample_backward(device)+ image = torch.arange(36, device=device, dtype=torch.float64).reshape(1, 1, 6, 6) / 36+ matrix = torch.tensor(+ [[[1.0, 0.1, 0.37], [0.05, 1.0, 0.23], [0.01, 0.02, 1.0]]], device=device, dtype=torch.float64+ )+ self.gradcheck(kornia.geometry.warp_perspective, (image, matrix, (5, 7)), requires_grad=(False, True, False))++ def test_large_translation_preserves_unit_diagonal(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("this translation tests the float32/float64 arithmetic range")+ image = torch.ones(1, 1, 3, 3, device=device, dtype=dtype)+ matrix = torch.eye(3, device=device, dtype=dtype)[None]+ matrix[..., 0, 2] = 1e20+ # Dividing by the maximum entry makes the determinant underflow in float32.+ # These output pixels all sample outside the image and should contain zero padding.+ actual = kornia.geometry.warp_perspective(image, matrix, (3, 3))+ self.assert_close(actual, torch.zeros_like(image), atol=0.0, rtol=0.0)+def test_smoke(self, device, dtype):batch_size, channels, height, width = 1, 2, 3, 4img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)