Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): homography_warp3d normalizes the voxel grid with normalized_coordinates=False (#6224)

Dmytro Mishkinb131b0c91bf0
diff --git a/changelog.d/6191.fixed.md b/changelog.d/6191.fixed.md
index ac4c4c45e..10c7c96ba 100644
--- a/changelog.d/6191.fixed.md
+++ b/changelog.d/6191.fixed.md
@@ -4,7 +4,7 @@ warped grid of source pixel coordinates is normalized under the call's `align_co
`warp_perspective` does. Previously the pixel grid reached `grid_sample` unnormalized, so almost every sample fell
outside the image and an identity homography returned a nearly blank image instead of the input. The result now
matches `warp_perspective` with the inverse homography; the pixel grid is warped and normalized in at least
-`float32`, also under a half default dtype and in a caller's autocast region, scripted or not, so `float16` and
-`bfloat16` do not lose half or whole pixels to coordinate rounding. Callers that pre-multiplied the homography by
-`normal_transform_pixel` to work around this must drop that factor. The default `normalized_coordinates=True` is
-unchanged. Fixes #6170.
+`float32`, also under a half default dtype and in a caller's autocast region, scripted or not, so pixel coordinates
+are not rounded to half precision before normalization; only the normalized grid takes the half dtype, as on the
+default path. Callers that pre-multiplied the homography by `normal_transform_pixel` to work around this must drop
+that factor. The default `normalized_coordinates=True` is unchanged. Fixes #6170.
diff --git a/changelog.d/6224.fixed.md b/changelog.d/6224.fixed.md
new file mode 100644
index 000000000..244bba4c7
--- /dev/null
+++ b/changelog.d/6224.fixed.md
@@ -0,0 +1,10 @@
+`homography_warp3d(..., normalized_coordinates=False)` now warps by a destination→source **voxel** homography: the
+warped grid of source voxel coordinates is normalized under the call's `align_corners` before `grid_sample`.
+Previously the voxel grid reached `grid_sample` unnormalized, so almost every sample fell outside the volume and an
+identity homography returned a nearly empty volume instead of the input. An identity now returns the input and a
+whole-voxel translation moves the volume by whole voxels under both `align_corners` settings, and at
+`align_corners=True` the result matches `warp_perspective3d` with the inverse homography. The voxel grid is warped
+and normalized in at least `float32`, also under a half default dtype and in a caller's autocast region, scripted or
+not, so voxel coordinates are not rounded to half precision before normalization; only the normalized grid takes the
+half dtype, as on the default path. Callers that pre-multiplied the homography by `normal_transform_pixel3d` to work
+around this must drop that factor. The default `normalized_coordinates=True` is unchanged. Fixes #6187.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 9e19abb35..bf528bbb4 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -39,6 +39,7 @@ from kornia.geometry.conversions import (
convert_affinematrix_to_homography3d,
convert_points_from_homogeneous,
normal_transform_pixel,
+ normal_transform_pixel3d,
normalize_homography,
normalize_homography3d,
normalize_pixel_coordinates,
@@ -725,6 +726,50 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
+def _warp_pixel_grid3d(src_homo_dst: torch.Tensor, depth: int, height: int, width: int) -> torch.Tensor:
+ """Warp the ``(depth, height, width)`` grid of destination voxels by ``src_homo_dst`` into source voxels.
+
+ The 3-D counterpart of :func:`_warp_pixel_grid`: the grid is built and warped in :func:`_pixel_grid_work_dtype`,
+ whatever the default dtype, with the projective gauge and homogeneous division of :func:`warp_grid3d`, as a sum of
+ elementwise column products that a caller's autocast region leaves alone, scripted or not. The result is
+ :math:`(N, D, H, W, 3)` in the ``(x, y, z)`` order the homography and ``grid_sample`` read.
+ """
+ work_dtype = _pixel_grid_work_dtype(src_homo_dst)
+ grid = create_meshgrid3d(
+ depth, height, width, normalized_coordinates=False, device=src_homo_dst.device, dtype=work_dtype
+ )
+ matrix = src_homo_dst.to(work_dtype)
+ matrix = matrix / _unit_projective_scale(matrix)
+ # Broadcasting covers both (N, 4, 4) and (N, 1, 4, 4).
+ matrix = matrix.reshape(src_homo_dst.shape[0], 1, 1, 1, 4, 4)
+ # create_meshgrid3d is (d, x, y); the homography acts on (x, y, z).
+ x, y, z = grid[..., 1:2], grid[..., 2:3], grid[..., 0:1]
+ warped = x * matrix[..., 0] + y * matrix[..., 1] + z * matrix[..., 2] + matrix[..., 3]
+ return convert_points_from_homogeneous(warped)
+
+
+def _normalize_warped_pixel_grid3d(
+ grid: torch.Tensor, depth: int, height: int, width: int, align_corners: bool
+) -> torch.Tensor:
+ """Map a ``(N, D, H, W, 3)`` grid of ``(x, y, z)`` source voxels to the ``[-1, 1]`` coordinates of ``grid_sample``.
+
+ ``depth``, ``height`` and ``width`` are the source's. With ``align_corners=True`` the map is
+ :func:`~kornia.geometry.conversions.normal_transform_pixel3d`, the one :func:`warp_perspective3d` conjugates its
+ voxel homography with, applied per axis. With ``False`` it is the half-voxel map ``(2v + 1) / size - 1``.
+ """
+ if align_corners:
+ norm = normal_transform_pixel3d(depth, height, width, device=grid.device, dtype=grid.dtype)[0]
+ scale = torch.stack((norm[0, 0], norm[1, 1], norm[2, 2]))
+ offset = torch.stack((norm[0, 3], norm[1, 3], norm[2, 3]))
+ return grid * scale + offset
+ # normal_transform_pixel3d has no align_corners yet, so the half-voxel map is written out here; #4503 gives the
+ # helper align_corners, and normal_transform_pixel3d(..., align_corners=False) then replaces these lines.
+ x = (2.0 * grid[..., 0:1] + 1.0) / width - 1.0
+ y = (2.0 * grid[..., 1:2] + 1.0) / height - 1.0
+ z = (2.0 * grid[..., 2:3] + 1.0) / depth - 1.0
+ return torch.cat((x, y, z), -1)
+
+
# TODO: move to kornia.geometry.projective
# TODO: create the nn.Module -- TBD what inputs/outputs etc
# class PerspectiveTransform(nn.Module):
@@ -2008,10 +2053,10 @@ def homography_warp3d(
align_corners: bool = False,
normalized_coordinates: bool = True,
) -> torch.Tensor:
- r"""Warp image patches or tensors by normalized 3D homographies.
+ r"""Warp image patches or tensors by 3D homographies.
Convention:
- - input: :math:`(N, C, D, H, W)`; ``dsize`` is ``(d, h, w)``
+ - input: :math:`(N, C, D, H, W)`; ``dsize`` is the output size ``(d, h, w)``
- ``src_homo_dst`` is the destination→source homography :math:`(N, 4, 4)`, in normalized
:math:`[-1, 1]` coordinates by default (``normalized_coordinates=True``), and acts on
``(x, y, z, 1)`` column vectors: ``x`` indexes ``W``, ``y`` indexes ``H``, ``z`` indexes
@@ -2020,7 +2065,17 @@ def homography_warp3d(
``(d, x, y)`` (see :func:`~kornia.geometry.grid.create_meshgrid3d`), so the sampling grid
is reordered here before the homography is applied; nothing else in the module changes
its order
- - align_corners: ``False`` by default
+ - with ``normalized_coordinates=False`` ``src_homo_dst`` is in **voxel** coordinates, voxel
+ centres at integers, in the same ``(x, y, z)`` order: it maps the voxel ``(x, y, z)`` of the
+ ``dsize`` output to the source voxel it samples, so an identity returns the ``dsize`` window
+ of the input that starts at voxel ``(0, 0, 0)``. The warped voxel grid is normalized with the
+ source size under ``align_corners`` before ``grid_sample``
+ - with ``normalized_coordinates=False`` the voxel grid is warped and normalized in at least
+ float32, also under a half default dtype and in a caller's autocast region, and then cast to
+ the homography's dtype
+ - align_corners: ``False`` by default. With ``normalized_coordinates=False`` and a source axis
+ longer than one voxel, a voxel homography samples the same positions under both settings,
+ which then differ only in ``padding_mode="reflection"``
- padding_mode: ``'zeros'`` by default
- negative output dimensions raise ``ValueError``
@@ -2028,11 +2083,12 @@ def homography_warp3d(
patch_src: The image or torch.Tensor to warp. Should be from source of shape :math:`(N, C, D, H, W)`.
src_homo_dst: The homography or torch.stack of homographies from destination to source of shape
:math:`(N, 4, 4)`.
- dsize: The depth, height and width of the volume to warp.
+ dsize: output size ``(d, h, w)``.
mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.
align_corners: interpolation flag.
- normalized_coordinates: Whether the homography assumes [-1, 1] normalized coordinates or not.
+ normalized_coordinates: whether ``src_homo_dst`` is in normalized :math:`[-1, 1]` coordinates
+ (``True``) or in voxel coordinates (``False``).
Return:
Patch sampled at locations from source to destination.
@@ -2055,20 +2111,28 @@ def homography_warp3d(
if _runs_in_float32(patch_src, src_homo_dst):
patch_src, src_homo_dst = patch_src.float(), src_homo_dst.float()
depth, height, width = dsize
- grid = create_meshgrid3d(
- 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
- # ``grid_sample`` both read the last axis as ``(x, y, z)``, so the depth channel moves last.
- # Stacked rather than indexed with a list, which is copied to the device with a blocking transfer.
- grid = torch.stack((grid[..., 1], grid[..., 2], grid[..., 0]), -1)
- warped_grid = warp_grid3d(grid, src_homo_dst)
+ if normalized_coordinates:
+ grid = create_meshgrid3d(
+ depth,
+ height,
+ width,
+ normalized_coordinates=True,
+ 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
+ # ``grid_sample`` both read the last axis as ``(x, y, z)``, so the depth channel moves last.
+ # Stacked rather than indexed with a list, which is copied to the device with a blocking transfer.
+ grid = torch.stack((grid[..., 1], grid[..., 2], grid[..., 0]), -1)
+ warped_grid = warp_grid3d(grid, src_homo_dst)
+ else:
+ # A voxel homography lands on source voxels, which grid_sample reads normalized. The voxel arithmetic runs
+ # in at least float32, unaffected by autocast, then the grid returns to the homography's dtype.
+ warped_grid = _warp_pixel_grid3d(src_homo_dst, depth, height, width)
+ warped_grid = _normalize_warped_pixel_grid3d(
+ warped_grid, patch_src.shape[-3], patch_src.shape[-2], patch_src.shape[-1], align_corners
+ ).to(src_homo_dst.dtype)
return _torch_grid_sample(
patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index d5f753e0d..933c101e4 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -15,12 +15,14 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
import kornia
import kornia.geometry.transform as proj
-from kornia.core.utils import _torch_inverse_cast
+from kornia.core.utils import _torch_grid_sample, _torch_inverse_cast
from testing.base import BaseTester, assert_close
@@ -381,14 +383,15 @@ class TestWarpPerspective3d(BaseTester):
assert not torch.allclose(out, sample)
def test_homography_warp3d_identity(self, device, dtype):
- # The functional entry point with an already-normalized identity, both grid conventions.
+ # The functional entry point with an identity in normalized and in voxel coordinates; the voxel mode is
+ # covered in TestHomographyWarp3dVoxelCoordinates (#6187).
dsize = (2, 3, 4)
sample = self._arange_volume(dsize, device, dtype)
identity = torch.eye(4, device=device, dtype=dtype)[None]
out = proj.homography_warp3d(sample, identity, dsize, align_corners=True)
self.assert_close(out, sample)
out_pix = proj.homography_warp3d(sample, identity, dsize, align_corners=True, normalized_coordinates=False)
- assert out_pix.shape == sample.shape
+ self.assert_close(out_pix, sample)
def test_gradcheck(self, device):
sample = torch.rand(1, 1, 2, 3, 4, device=device, dtype=torch.float64, requires_grad=True)
@@ -397,6 +400,288 @@ class TestWarpPerspective3d(BaseTester):
self.gradcheck(proj.warp_perspective3d, (sample, M, (2, 3, 4)), requires_grad=(True, False, False))
+class TestHomographyWarp3dVoxelCoordinates(BaseTester):
+ # homography_warp3d(normalized_coordinates=False) handed its warped voxel grid to grid_sample unnormalized, so
+ # almost every sample fell outside the volume: an identity on a (6, 8, 10) volume returned it changed by up to
+ # 0.9998 (#6187). The grid is now normalized with the source size under the call's align_corners.
+
+ # A source->destination voxel homography with a perspective row, and an affine one; their inverses are the
+ # destination->source homographies the voxel mode reads.
+ _DST_TRANS_SRC = (
+ [
+ [0.9, 0.1, 0.05, 1.5],
+ [-0.05, 1.1, 0.02, -0.7],
+ [0.03, -0.02, 0.95, 0.4],
+ [0.01, -0.02, 0.015, 1.0],
+ ],
+ [[1.2, 0.0, 0.0, -2.0], [0.0, 0.8, 0.0, 1.0], [0.0, 0.0, 1.1, -0.5], [0.0, 0.0, 0.0, 1.0]],
+ )
+
+ @staticmethod
+ def _warp(volume, src_homo_dst, dsize, **options):
+ return proj.homography_warp3d(volume, src_homo_dst, dsize, normalized_coordinates=False, **options)
+
+ @staticmethod
+ def _volume(shape, device, dtype):
+ return (torch.arange(math.prod(shape), device=device) % 11 / 11).to(dtype).view(shape)
+
+ def _homographies(self, device, dtype):
+ dst_trans_src = torch.tensor(self._DST_TRANS_SRC, dtype=torch.float64)
+ # inverted in float64 on the CPU, which every device can then take in its own dtype
+ return dst_trans_src.to(device=device, dtype=dtype), torch.linalg.inv(dst_trans_src).to(device, dtype)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("shape", [(4, 5, 6), (1, 5, 3), (3, 1, 4)])
+ def test_identity(self, shape, align_corners, device, dtype):
+ # An identity returns the input, singleton axes included, and a smaller destination is the window that starts
+ # at voxel (0, 0, 0) rather than a resize of the source.
+ volume = self._volume((1, 2, *shape), device, dtype)
+ identity = torch.eye(4, device=device, dtype=dtype)[None]
+ self.assert_close(self._warp(volume, identity, shape, align_corners=align_corners), volume)
+
+ small = (max(shape[0] - 1, 1), max(shape[1] - 2, 1), max(shape[2] - 1, 1))
+ expected = volume[..., : small[0], : small[1], : small[2]]
+ self.assert_close(self._warp(volume, identity, small, align_corners=align_corners), expected)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("axis", [0, 1, 2], ids=["x", "y", "z"])
+ def test_whole_voxel_translation(self, axis, align_corners, device, dtype):
+ # src_homo_dst maps destination voxels to source voxels, so a translation t along x samples
+ # out[..., x] = src[..., x + t], one homography per sample, and zeros where that leaves the source. The three
+ # sizes differ, so a shift along the wrong axis cannot reproduce the expected volume.
+ dsize = (3, 4, 5)
+ volume = self._volume((2, 1, *dsize), device, dtype)
+ src_homo_dst = torch.eye(4, device=device, dtype=dtype).repeat(2, 1, 1)
+ src_homo_dst[0, axis, 3] = 1.0
+ src_homo_dst[1, axis, 3] = -2.0
+ dim = 3 - axis # the per-sample (C, D, H, W) dimension that x, y and z index
+ size = volume.shape[dim + 1]
+ expected = torch.zeros_like(volume)
+ expected[0].narrow(dim, 0, size - 1).copy_(volume[0].narrow(dim, 1, size - 1))
+ expected[1].narrow(dim, 2, size - 2).copy_(volume[1].narrow(dim, 0, size - 2))
+
+ self.assert_close(self._warp(volume, src_homo_dst, dsize, align_corners=align_corners), expected)
+ # the (N, 1, 4, 4) homography shape warp_grid3d accepts reads the same way
+ self.assert_close(self._warp(volume, src_homo_dst[:, None], dsize, align_corners=align_corners), expected)
+
+ @pytest.mark.parametrize("padding_mode", ["zeros", "border", "reflection"])
+ def test_matches_warp_perspective3d(self, padding_mode, device, dtype):
+ # warp_perspective3d takes the source->destination voxel homography; its inverse is the destination->source
+ # voxel homography the voxel mode reads. Both normalize the same way at align_corners=True, so they agree
+ # for every padding mode, with a perspective row and a destination of another size than the source. Only
+ # align_corners=True: at False warp_perspective3d's own normalization is still corner-aligned (#4503).
+ volume = self._volume((2, 3, 5, 7, 9), device, dtype)
+ dst_trans_src, src_homo_dst = self._homographies(device, dtype)
+ dsize = (4, 6, 8)
+
+ expected = proj.warp_perspective3d(volume, dst_trans_src, dsize, border_mode=padding_mode, align_corners=True)
+ actual = self._warp(volume, src_homo_dst, dsize, padding_mode=padding_mode, align_corners=True)
+ # in half precision the two matrices are rounded separately, one before and one after the inversion
+ self.assert_close(actual, expected, low_tolerance=dtype in (torch.float16, torch.bfloat16))
+
+ def test_align_corners_settings_sample_the_same_voxels(self, device, dtype):
+ # Each setting normalizes the voxel grid the way grid_sample then reads it, so along axes longer than one
+ # voxel both sample the same positions, also outside the source: zeros and border padding agree. Reflection
+ # padding mirrors about the outer voxel centres (True) or edges (False), and only it tells them apart.
+ volume = self._volume((2, 3, 5, 7, 9), device, dtype)
+ _, src_homo_dst = self._homographies(device, dtype)
+ dsize = (4, 6, 8)
+
+ def warp(padding_mode, align_corners):
+ return self._warp(volume, src_homo_dst, dsize, padding_mode=padding_mode, align_corners=align_corners)
+
+ # a half grid (off the CPU, which warps in float32) rounds the two normalizations differently
+ low_tolerance = dtype in (torch.float16, torch.bfloat16)
+ self.assert_close(warp("zeros", True), warp("zeros", False), low_tolerance=low_tolerance)
+ self.assert_close(warp("border", True), warp("border", False), low_tolerance=low_tolerance)
+ assert not torch.allclose(warp("reflection", True), warp("reflection", False))
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_wide_identity(self, align_corners, device, dtype):
+ # Voxel coordinates reach the volume width, where float16 rounds them to half voxels from 512 and bfloat16 to
+ # whole voxels from 128. The voxel grid is warped and normalized in float32 and only the normalized grid
+ # returns to the homography's dtype, so a 640 voxel wide identity samples where a normalized identity grid
+ # does, and in float16 within an eighth of a voxel of every column. The volume holds the column index. The
+ # reference is the 2-D homography_warp of a depth slice, whose normalized grid follows align_corners; the
+ # 3-D normalized grid is corner-aligned under both settings (#4503). A CPU half 3-D warp runs in float32
+ # (#5751), so its reference does too.
+ width = 640
+ volume = torch.arange(width, device=device).to(dtype).expand(1, 1, 2, 2, width)
+ identity = torch.eye(4, device=device, dtype=dtype)[None]
+
+ actual = self._warp(volume, identity, (2, 2, width), align_corners=align_corners)
+ reference_dtype = torch.float32 if device.type == "cpu" and dtype in (torch.float16, torch.bfloat16) else dtype
+ normalized = proj.homography_warp(
+ volume[:, :, 0].to(reference_dtype),
+ identity[:, :3, :3].to(reference_dtype),
+ (2, width),
+ align_corners=align_corners,
+ )
+ normalized = normalized.to(dtype)[:, :, None].expand_as(actual)
+
+ # Interior columns only: the outermost ones border the zero padding, where any sub-voxel offset of the last
+ # column (value 639) costs a large value error. Values are column indices, so tolerances are in voxels.
+ actual, normalized, volume = actual[..., 1:-1], normalized[..., 1:-1], volume[..., 1:-1]
+ if dtype in (torch.float16, torch.bfloat16):
+ self.assert_close(actual, normalized, rtol=0, atol=0.125 if dtype == torch.float16 else 1.0)
+ else:
+ self.assert_close(actual, normalized)
+ # bfloat16 stores these column indices only to within 2 to 4, so it is checked against the default path alone
+ if dtype != torch.bfloat16:
+ max_error = 0.125 if dtype == torch.float16 else 1e-3
+ assert (actual.float() - volume.float()).abs().max() <= max_error
+
+ @pytest.mark.parametrize("scale", [1e-7, 1e-8, 1e-12, 1e-30, 1e12, -1e8])
+ def test_homography_scale_is_a_gauge(self, scale, device, dtype):
+ # A homography and any nonzero multiple of it are the same warp: the voxel grid divides by the projective
+ # scale of warp_grid3d before the homogeneous division, whose absolute eps would otherwise leave the points
+ # of a small matrix undivided (#5761).
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("these scales test the float32/float64 arithmetic range")
+ volume = self._volume((2, 3, 5, 7, 9), device, dtype)
+ _, src_homo_dst = self._homographies(device, dtype)
+
+ expected = self._warp(volume, src_homo_dst, (4, 6, 8))
+ actual = self._warp(volume, scale * src_homo_dst, (4, 6, 8))
+ self.assert_close(actual, expected)
+
+ def test_backward_keeps_dtype(self, device, dtype):
+ # The voxel grid is warped in float32 for a half homography and cast back: gradients still reach the volume
+ # and the homography, finite and in their own dtype.
+ volume = self._volume((1, 2, 4, 5, 6), device, dtype).requires_grad_()
+ _, src_homo_dst = self._homographies(device, dtype)
+ src_homo_dst = src_homo_dst[:1].clone().requires_grad_()
+
+ self._warp(volume, src_homo_dst, (3, 4, 5)).float().square().sum().backward()
+
+ for tensor in (volume, src_homo_dst):
+ assert tensor.grad is not None
+ assert tensor.grad.dtype == dtype
+ assert torch.isfinite(tensor.grad).all()
+ assert tensor.grad.abs().sum() > 0
+
+ @pytest.mark.parametrize(("default_dtype", "width"), [(torch.float16, 4096), (torch.bfloat16, 640)])
+ def test_half_default_dtype_keeps_voxel_indices(self, default_dtype, width, device):
+ # The voxel grid is built in the homography's work dtype, not the default dtype, which would round its
+ # integer columns from 2048 (float16) or 256 (bfloat16) on and shift the samples.
+ volume = torch.arange(width, device=device, dtype=torch.float32).expand(1, 1, 1, 2, width)
+ identity = torch.eye(4, device=device, dtype=torch.float32)[None]
+ expected = self._warp(volume, identity, (1, 2, width))
+ previous = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(default_dtype)
+ actual = self._warp(volume, identity, (1, 2, width))
+ finally:
+ torch.set_default_dtype(previous)
+
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ self.assert_close(actual[..., 1:-1], volume[..., 1:-1])
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_autocast_does_not_reach_the_voxel_grid(self, align_corners, device):
+ # A matrix product inside a caller's bfloat16 autocast region would round the voxel columns of a 640 wide
+ # grid to whole voxels; the voxel grid is warped with elementwise products, which autocast leaves alone, in
+ # eager and scripted calls alike.
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("CPU and CUDA autocast")
+ width = 640
+ volume = torch.arange(width, device=device, dtype=torch.float32).expand(2, 1, 1, 2, width)
+ src_homo_dst = torch.eye(4, device=device, dtype=torch.float32).repeat(2, 1, 1)
+ src_homo_dst[1, 0, 3] = -1.0
+ expected = self._warp(volume, src_homo_dst, (1, 2, width), align_corners=align_corners)
+ scripted = torch.jit.script(proj.homography_warp3d)
+
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ actual = self._warp(volume, src_homo_dst, (1, 2, width), align_corners=align_corners)
+ actual_scripted = scripted(
+ volume, src_homo_dst, (1, 2, width), align_corners=align_corners, normalized_coordinates=False
+ )
+
+ assert actual.dtype == actual_scripted.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ self.assert_close(actual_scripted, expected, rtol=0, atol=0)
+ self.assert_close(expected[0, ..., 1:-1], volume[0, ..., 1:-1])
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_torchscript(self, align_corners, device, dtype):
+ # A scripted call computes the eager voxel grid, bit for bit on the CPU. On CUDA, torch.jit.script returns the
+ # cached function, so a second call with the same shapes runs TorchScript's GPU fuser, which rounds the fused
+ # grid arithmetic differently from eager (about 1e-6 in float32).
+ volume = self._volume((2, 2, 5, 7, 9), device, dtype)
+ _, src_homo_dst = self._homographies(device, dtype)
+ scripted = torch.jit.script(proj.homography_warp3d)
+
+ actual = scripted(volume, src_homo_dst, (4, 6, 8), align_corners=align_corners, normalized_coordinates=False)
+ expected = self._warp(volume, src_homo_dst, (4, 6, 8), align_corners=align_corners)
+ if device.type == "cpu":
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ else:
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_normalized_coordinates_path_is_the_plain_grid_warp(self, align_corners, device, dtype):
+ # The default normalized path is grid_sample over warp_grid3d of the reordered normalized meshgrid, bit for
+ # bit; the voxel-mode normalization must not reach it (#6187).
+ volume = self._volume((1, 2, 5, 6, 7), device, dtype)
+ src_homo_dst = torch.tensor(
+ [
+ [
+ [0.95, 0.05, 0.02, 0.1],
+ [-0.03, 1.05, 0.01, -0.08],
+ [0.02, -0.01, 0.9, 0.05],
+ [0.02, -0.01, 0.03, 1.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ # a CPU float16/bfloat16 warp runs in float32 and returns the input dtype (#5751)
+ work = torch.float32 if device.type == "cpu" and dtype in (torch.float16, torch.bfloat16) else dtype
+ grid = kornia.geometry.create_meshgrid3d(4, 3, 6, normalized_coordinates=True, device=device, dtype=work)
+ warped_grid = proj.warp_grid3d(grid[..., [1, 2, 0]], src_homo_dst.to(work))
+ expected = _torch_grid_sample(volume.to(work), warped_grid, align_corners=align_corners).to(dtype)
+
+ actual = proj.homography_warp3d(volume, src_homo_dst, (4, 3, 6), align_corners=align_corners)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_gradcheck(self, align_corners, device):
+ # Gradients reach both the volume and the voxel homography; sub-voxel sample positions keep the trilinear
+ # kinks away from the finite differences.
+ volume = self._volume((1, 2, 4, 5, 6), device, torch.float64)
+ src_homo_dst = torch.tensor(
+ [[[1.05, 0.02, 0.01, 0.3], [0.01, 0.95, 0.03, -0.4], [0.02, -0.01, 1.1, 0.2], [1e-3, -2e-3, 3e-3, 1.0]]],
+ device=device,
+ dtype=torch.float64,
+ )
+
+ def warp(volume, src_homo_dst):
+ return self._warp(volume, src_homo_dst, (3, 4, 5), align_corners=align_corners)
+
+ self.gradcheck(warp, (volume, src_homo_dst), nondet_tol=1e-8)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_dynamo(self, align_corners, device, dtype, torch_optimizer):
+ # Compiled-vs-eager passes on a wrong result too: also check the compiled output against an eager reference
+ # that does not run this code, warp_perspective3d of the source->destination voxel homography in float64 on
+ # the CPU, at align_corners=True with zeros padding, where both settings sample the same voxels (see
+ # test_align_corners_settings_sample_the_same_voxels) and warp_perspective3d is correct (#4503).
+ volume = self._volume((2, 3, 5, 7, 9), device, dtype)
+ _, src_homo_dst = self._homographies(device, dtype)
+ dsize = (4, 6, 8)
+
+ eager = self._warp(volume, src_homo_dst, dsize, align_corners=align_corners)
+ compiled = torch_optimizer(proj.homography_warp3d)(
+ volume, src_homo_dst, dsize, align_corners=align_corners, normalized_coordinates=False
+ )
+ dst_trans_src = torch.tensor(self._DST_TRANS_SRC, dtype=torch.float64)
+ expected = proj.warp_perspective3d(volume.cpu().double(), dst_trans_src, dsize, align_corners=True)
+ expected = expected.to(device=device, dtype=dtype)
+
+ self.assert_close(compiled, eager)
+ self.assert_close(compiled, expected, low_tolerance=dtype in (torch.float16, torch.bfloat16))
+
+
class TestWarpAffine3d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.rand(1, 3, 3, 4, 5, device=device, dtype=dtype)