Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): build the perspective warp grid in the input dtype (#4795)

RitiGrover0b96b6beda72
diff --git a/changelog.d/4795.fixed.md b/changelog.d/4795.fixed.md
new file mode 100644
index 000000000..e374d6f5e
--- /dev/null
+++ b/changelog.d/4795.fixed.md
@@ -0,0 +1,6 @@
+`warp_perspective`, `warp_perspective3d` and `homography_warp3d` build their sampling grid in the input dtype
+instead of `float32`. A `float64` identity warp, including `RandomPerspective` and `RandomPerspective3D` with
+`distortion_scale=0`, now reproduces its input to `float64` roundoff, as `warp_affine` does. `float32` and
+half-precision grids are unchanged at the default `float32` default dtype; under
+`torch.set_default_dtype(torch.float64)` they are no longer built in `float64` and rounded, so they now match
+the result at the default.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 7200d12fc..2a9c44ce5 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -204,8 +204,7 @@ covers a slightly different extent of the source image.
convention whatever flag they pass to ``grid_sample``, and have the same mismatch at
``align_corners=False``: an identity ``warp_perspective3d`` changes a 4x4x4 ``arange``
volume by up to ``55.1`` there, against roundoff at ``align_corners=True``: exactly
- ``0`` in ``float32`` on torch 2.14 and about ``2e-6`` on torch 2.5.1. The grid is built
- in ``float32``, so a ``float64`` volume is reproduced only to about ``1e-6`` even there. Pass
+ ``0`` in ``float32`` on torch 2.14 and about ``2e-6`` on torch 2.5.1. Pass
``align_corners=True`` to the 3-D warps until this is fixed. Tracked in
`#4503 <https://github.com/kornia/kornia/issues/4503>`_.
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 99450d982..934da75f0 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -54,10 +54,8 @@ class RandomPerspective(GeometricAugmentationBase2D):
- ``basic`` samples each corner inward by at most ``distortion_scale * (W, H) / 2``. ``area_preserving``
samples each coordinate in both directions over the same extent.
- with ``distortion_scale=0`` and ``H > 1``, ``W > 1``, the warp is an identity up to numerical precision
- for either ``align_corners``. A ``float64`` image is warped through a ``float32`` grid, so it is
- reproduced only to float32 precision (`#4776 <https://github.com/kornia/kornia/issues/4776>`_). If either
- spatial dimension is 1, the coincident source corners give a NaN matrix and output even at zero
- distortion (`#4787 <https://github.com/kornia/kornia/issues/4787>`_).
+ for either ``align_corners``. If either spatial dimension is 1, the coincident source corners give a NaN
+ matrix and output even at zero distortion (`#4787 <https://github.com/kornia/kornia/issues/4787>`_).
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_perspective`.
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index 40abb2fbf..fe0e6fcc9 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -49,14 +49,10 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
- ``distortion_scale=0`` generates identical source and destination corners. The default bilinear,
``align_corners=False`` perspective warp nevertheless does not reproduce its input, even a constant one;
- use ``align_corners=True`` for an identity warp up to float32 grid precision: the sampling grid is
- built by :func:`kornia.geometry.grid.create_meshgrid3d` in float32, so a ``float64`` volume is
- reproduced only to that precision -- about ``1e-7`` for a small volume in ``[0, 1]``, growing with
- its size -- while the affine and rotation paths are exact to ``float64`` roundoff. The false-setting
- normalization defect is tracked in `#4503 <https://github.com/kornia/kornia/issues/4503>`_.
+ use ``align_corners=True`` for an identity warp up to floating-point roundoff in ``float32`` and
+ ``float64``. The false-setting normalization defect is tracked in
+ `#4503 <https://github.com/kornia/kornia/issues/4503>`_.
- the default interpolation is bilinear and the default ``align_corners`` is ``False``.
- - a ``float64`` volume is warped through a float32 sampling grid, so it keeps only float32 precision
- (`#4776 <https://github.com/kornia/kornia/issues/4776>`_).
Examples:
>>> import torch
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index f9a1af849..0ea578b35 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -229,8 +229,6 @@ 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 ``float64`` input is sampled through a ``float32`` grid, so it is warped only to float32
- precision (`#4776 <https://github.com/kornia/kornia/issues/4776>`_)
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
@@ -303,8 +301,8 @@ def warp_perspective(
# Substitutes F.affine_grid (which only handles the affine 2x3 case) by applying the full 3x3
# projective transform to every grid point directly.
grid = create_meshgrid(
- h_out, w_out, normalized_coordinates=True, device=src.device, align_corners=align_corners
- ).to(src.dtype)
+ h_out, w_out, normalized_coordinates=True, device=src.device, dtype=src.dtype, align_corners=align_corners
+ )
if torch.jit.is_tracing():
# Under tracing/ONNX use the reference transform_points path (its op set exports cleanly).
grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid.expand(B, h_out, w_out, 2))
@@ -1633,8 +1631,6 @@ def warp_perspective3d(
- border_mode: ``'zeros'`` by default
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
- - a ``float64`` input is sampled through a ``float32`` grid, so it is warped only to float32
- precision (`#4776 <https://github.com/kornia/kornia/issues/4776>`_)
Args:
src: input image with shape :math:`(B, C, D, H, W)`.
@@ -1837,7 +1833,12 @@ def homography_warp3d(
depth, height, width = dsize
grid = create_meshgrid3d(
- depth, height, width, normalized_coordinates=normalized_coordinates, device=patch_src.device
+ depth,
+ height,
+ width,
+ normalized_coordinates=normalized_coordinates,
+ device=patch_src.device,
+ dtype=torch.promote_types(patch_src.dtype, src_homo_dst.dtype),
)
# ``create_meshgrid3d`` follows kornia's ``(d, x, y)`` convention, which
# ``normalize_pixel_coordinates3d`` and ``conv_soft_argmax3d`` rely on. ``warp_grid3d`` and
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index cb325c7bd..615c7c7e5 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -429,17 +429,15 @@ class Test3DAugmentationConventions(BaseTester):
self.assert_close(K.RandomCrop3D((4, 5, 6), p=1.0)(volume), volume)
@pytest.mark.device_agnostic
- def test_wart_perspective3d_float64_identity_uses_a_float32_grid_4776(self):
- # #4776: flips to `residual < 1e-12` once the grid is built in float64; the rotation path already is.
- volume = torch.rand(1, 1, 4, 5, 6, dtype=torch.float64)
- rotation = float((K.RandomRotation3D(0.0, p=1.0, align_corners=True)(volume) - volume).abs().max())
- residual = float((K.RandomPerspective3D(0.0, p=1.0, align_corners=True)(volume) - volume).abs().max())
- assert rotation < 1e-12
- assert 1e-9 < residual < 1e-5
- # The float32-grid error grows with the volume size.
- large = torch.rand(1, 1, 8, 16, 32, dtype=torch.float64)
- large_residual = float((K.RandomPerspective3D(0.0, p=1.0, align_corners=True)(large) - large).abs().max())
- assert residual < large_residual < 1e-4
+ def test_perspective3d_float64_identity_is_exact_4776(self):
+ # #4776: the perspective sampling grid is built in float64, so the identity warp is exact to float64
+ # roundoff like the rotation path, at any size.
+ for shape in ((1, 1, 4, 5, 6), (1, 1, 8, 16, 32)):
+ volume = torch.rand(*shape, dtype=torch.float64)
+ rotation = float((K.RandomRotation3D(0.0, p=1.0, align_corners=True)(volume) - volume).abs().max())
+ residual = float((K.RandomPerspective3D(0.0, p=1.0, align_corners=True)(volume) - volume).abs().max())
+ assert rotation < 1e-12
+ assert residual < 1e-12
@pytest.mark.device_agnostic
def test_convention_random_crop3d_offset_reaches_both_ends(self):
diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.py
index eb87f43d6..87cafd622 100644
--- a/tests/augmentation/test_conventions_geometric_matrix.py
+++ b/tests/augmentation/test_conventions_geometric_matrix.py
@@ -135,14 +135,15 @@ class TestConventionGeometricMatrices(BaseTester):
)
@pytest.mark.parametrize("align_corners", [False, True])
- def test_wart_random_perspective_float64_identity_goes_through_a_float32_grid_4776(self, device, align_corners):
- # #4776: warp_perspective builds its grid in float32, so a float64 identity warp keeps only float32
- # precision (RandomAffine's warp_affine is exact on the same input). Flips when the grid follows the dtype.
+ def test_random_perspective_float64_identity_is_exact_4776(self, device, align_corners):
+ # #4776: warp_perspective builds its grid in the input dtype, so a float64 identity warp is exact to
+ # float64 roundoff, like RandomAffine's warp_affine on the same input.
if device.type == "mps":
pytest.skip("MPS has no float64")
image = torch.arange(35, device=device, dtype=torch.float64).reshape(1, 1, 5, 7) / 35
output = K.RandomPerspective(0.0, align_corners=align_corners, p=1.0)(image)
- assert (output - image).abs().max() > 1e-12
+ assert output.dtype == torch.float64
+ assert (output - image).abs().max() < 1e-12
@pytest.mark.parametrize("size", [(1, 7), (5, 1), (1, 1)])
@pytest.mark.parametrize("align_corners", [False, True])
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 25196ddb1..e59fb0228 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -666,6 +666,18 @@ class TestWarpPerspective(BaseTester):
img_a = kornia.geometry.warp_perspective(img_b, H_ab, (h_out, w_out))
assert img_a.shape == (batch_size, channels, h_out, w_out)
+ @pytest.mark.parametrize("size", [8, 64])
+ def test_identity_float64_precision(self, device, size):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ # the sampling grid is built in the input dtype, so a float64 identity warp is exact to
+ # float64 roundoff like warp_affine, not to float32 grid precision
+ img = torch.rand(1, 1, size, size, device=device, dtype=torch.float64)
+ homo = torch.eye(3, device=device, dtype=torch.float64)[None]
+ out = kornia.geometry.warp_perspective(img, homo, (size, size), align_corners=True)
+ assert out.dtype == torch.float64
+ self.assert_close(out, img, rtol=0.0, atol=1e-12)
+
def test_exception(self, device, dtype):
img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
homo = torch.eye(3, device=device, dtype=dtype)[None]
@@ -741,18 +753,6 @@ class TestWarpPerspective(BaseTester):
hw = kornia.geometry.transform.homography_warp(x, _torch_inverse_cast(Hn), (3, 5), align_corners=True)
self.assert_close(hw, expected, atol=1e-4, rtol=1e-4)
- def test_wart_float64_identity_goes_through_a_float32_grid_4776(self, device):
- # warp_perspective builds its sampling grid in float32 and casts it, so a float64 identity warp
- # is exact only to float32 precision, while warp_affine is exact (#4776). Flips once the grid
- # is built in the input dtype.
- if device.type == "mps":
- pytest.skip("MPS has no float64")
- x = torch.arange(64.0, device=device, dtype=torch.float64).view(1, 1, 8, 8) / 7.0
- eye = torch.eye(3, device=device, dtype=torch.float64)[None]
- affine = kornia.geometry.transform.warp_affine(x, eye[:, :2], (8, 8))
- assert (affine - x).abs().max() < 1e-12
- assert (kornia.geometry.transform.warp_perspective(x, eye, (8, 8)) - x).abs().max() > 1e-9
-
def test_wart_homography_warp_pixel_path_ignores_mode_and_align_corners_4772(self, device, dtype):
# With normalized_homography=False, homography_warp calls warp_perspective with mode="bilinear"
# and align_corners=True whatever it was given (#4772). Reflection padding makes align_corners
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index 7fa99df47..753d5d70c 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -161,6 +161,19 @@ class TestWarpPerspective3d(BaseTester):
out = proj.warp_perspective3d(sample, identity, dsize, align_corners=True)
self.assert_close(out, sample)
+ @pytest.mark.parametrize("size", [8, 32])
+ def test_identity_float64_precision(self, device, size):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ # the sampling grid is built in the input dtype, so a float64 identity warp is exact to
+ # float64 roundoff like warp_affine3d, not to float32 grid precision
+ dsize = (size // 2, size, size)
+ sample = torch.rand(1, 1, *dsize, device=device, dtype=torch.float64)
+ identity = torch.eye(4, device=device, dtype=torch.float64)[None]
+ out = proj.warp_perspective3d(sample, identity, dsize, align_corners=True)
+ assert out.dtype == torch.float64
+ self.assert_close(out, sample, rtol=0.0, atol=1e-12)
+
@pytest.mark.parametrize("dsize", [(4, 4, 4), (2, 3, 4)])
@pytest.mark.xfail(strict=True, raises=AssertionError, reason="3D normalization ignores align_corners, #4503")
def test_convention_identity_reproduces_input_align_corners_false(self, dsize, device, dtype):