Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): run float16 and bfloat16 warps in float32 on every device (#6563)

Dmytro Mishkin02d3a70d178a
diff --git a/changelog.d/6563.fixed.md b/changelog.d/6563.fixed.md
new file mode 100644
index 000000000..d44759435
--- /dev/null
+++ b/changelog.d/6563.fixed.md
@@ -0,0 +1,9 @@
+float16 and bfloat16 geometry warps now build their sampling grid and sample in float32 and return the input dtype on
+every device, not only on CPU (#5814): `warp_affine`, `warp_perspective`, `remap`, `homography_warp` with
+`normalized_homography=False` and the 3D warps, and the crops and augmentations built on them. On CUDA and MPS they used
+to compute in the half dtype: a bfloat16 `warp_affine` of a 256 px `[0, 1]` image was off by up to 0.98 on CUDA and on
+MPS, `warp_affine3d` raised for a half CUDA or MPS output with a size-1 axis, and a bfloat16 warp inside a float16
+`torch.autocast` raised. `HomographyWarper`, `homography_warp` with `normalized_homography=True` (in normalized or pixel
+coordinates), `elastic_transform2d`, `warp_image_tps` and the depth warps also sample in float32 now, but they still
+build their grid in the half dtype, so their float16 and bfloat16 accuracy is not fixed yet; that part of #5814 remains
+open.
diff --git a/kornia/augmentation/_3d/geometric/base.py b/kornia/augmentation/_3d/geometric/base.py
index 4364dd4c7..914d8da55 100644
--- a/kornia/augmentation/_3d/geometric/base.py
+++ b/kornia/augmentation/_3d/geometric/base.py
@@ -41,8 +41,8 @@ class GeometricAugmentationBase3D(RigidAffineAugmentationBase3D):
Matrices use the input dtype, so integer voxel translations are rounded when that dtype cannot represent
them exactly.
- a zero-parameter :class:`RandomAffine3D` or :class:`RandomRotation3D` warp reproduces its input up to
- roundoff in ``float32`` and ``float64``, and in CPU ``float16``/``bfloat16``, where the warp runs in
- ``float32`` (`#5751 <https://github.com/kornia/kornia/issues/5751>`_). On other devices the half-precision
- sampling grid is itself rounded, so the error grows with the volume size.
+ roundoff in every floating dtype: a ``float16``/``bfloat16`` warp builds its grid and samples in
+ ``float32`` on every device (`#5751 <https://github.com/kornia/kornia/issues/5751>`_,
+ `#5814 <https://github.com/kornia/kornia/issues/5814>`_).
"""
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index b4fc2f9f3..acd0f342c 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -44,6 +44,19 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK
from kornia.core.exceptions import DeviceError, TypeCheckError
+def _samples_half_in_float32(input: torch.Tensor) -> bool:
+ """Return whether ``input`` is resampled in float32 and returned in its own dtype: true for float16/bfloat16.
+
+ The policy holds on every device. The CPU half ``grid_sample`` kernels are corrupt or missing (#5751). The CUDA
+ bicubic one is off by more than 1 on a ``[0, 1]`` image, the CUDA and MPS half gradients differ from the float32
+ ones, and under an autocast of the other half dtype a half ``grid_sample`` raises (#5814). Bilinear and nearest
+ sampling of a given grid is as accurate in half precision as in float32 on CUDA and MPS, so most of the error of
+ a half warp came from a sampling grid built in the half dtype, up to 0.98 in bfloat16 on both; the warps that
+ build their own grid therefore build it in float32 too (``kornia.geometry.transform.imgwarp._runs_in_float32``).
+ """
+ return input.dtype in (torch.float16, torch.bfloat16)
+
+
def _torch_grid_sample(
input: torch.Tensor,
grid: torch.Tensor,
@@ -51,12 +64,16 @@ def _torch_grid_sample(
padding_mode: str = "zeros",
align_corners: Optional[bool] = None,
) -> torch.Tensor:
- """Run :func:`torch.nn.functional.grid_sample` on 4-D or 5-D input, CPU float16/bfloat16 in float32.
+ """Run :func:`torch.nn.functional.grid_sample` on 4-D or 5-D input, float16/bfloat16 in float32.
torch's CPU half ``grid_sample`` returns corrupt values on sources of about 128 px and more, and
- torch 2.5.1 has no such kernel (#5751). Other devices and dtypes call ``grid_sample`` unchanged.
+ torch 2.5.1 has no such kernel (#5751). On CUDA the half bicubic kernel is off by more than 1 on a ``[0, 1]``
+ image, the CUDA and MPS half gradients differ from the float32 ones, and under a float16 ``torch.autocast`` a
+ bfloat16 input raises (#5814). A half input with a grid of its own dtype is therefore sampled in float32 on every
+ device and returned in its dtype. A grid of another dtype, and every other input dtype, reach ``grid_sample``
+ unchanged, which rejects a mismatch as before.
"""
- if input.device.type == "cpu" and input.dtype in (torch.float16, torch.bfloat16) and grid.dtype == input.dtype:
+ if _samples_half_in_float32(input) and grid.dtype == input.dtype:
return F.grid_sample(
input.float(), grid.float(), mode=mode, padding_mode=padding_mode, align_corners=align_corners
).to(input.dtype)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 7873afedd..cec8b7c2f 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -59,6 +59,7 @@ from kornia.core.utils import (
_autocast_disabled,
_inverse_3x3_closed_form,
_normalize_to_float32_or_float64,
+ _samples_half_in_float32,
_torch_grid_sample,
_torch_inverse_cast,
_torch_solve_cast,
@@ -136,11 +137,15 @@ def _runs_in_float32(src: torch.Tensor, other: torch.Tensor) -> bool:
torch's CPU float16/bfloat16 ``grid_sample`` returns wrong values, NaN and up to 3.4e38 once
the source is about 128 px or larger (torch 2.9.1 and 2.14), and torch 2.5.1 has no such kernel
at all; a half-precision sampling grid is also off by more than half a pixel at 256 px in
- bfloat16 (#5751). A CPU half warp therefore runs in float32 and returns the input dtype, as the LAF
- patch extractors already do. A mismatched ``other`` (transform or map) keeps the half path, so
- it is rejected exactly as before. Other devices and dtypes are unaffected.
+ bfloat16 (#5751). That grid error does not depend on the device: a bfloat16 ``warp_affine`` of a
+ 256 px ``[0, 1]`` image was off by up to 0.98 on CUDA and on MPS, whose half bilinear kernels
+ sample a given grid as float32 does, and torch's half 3D ``affine_grid`` raises for a size-1
+ output axis on every device (#5814). A half warp therefore builds its grid and samples in float32
+ on every device and returns the input dtype, as the LAF patch extractors already do. A mismatched
+ ``other`` (transform or map) keeps the half path, so it is rejected exactly as before. Other dtypes
+ are unaffected.
"""
- return src.device.type == "cpu" and src.dtype in (torch.float16, torch.bfloat16) and other.dtype == src.dtype
+ return _samples_half_in_float32(src) and other.dtype == src.dtype
def _unit_projective_scale(matrix: torch.Tensor) -> torch.Tensor:
diff --git a/testing/base.py b/testing/base.py
index 3b5c67e50..d34041c17 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -322,20 +322,6 @@ def supports_nearest_3d_grid_sample(device: torch.device, dtype: torch.dtype) ->
return _supports_kernel_probe(_nearest_3d_grid_sample_op, device.type, dtype)
-def _unit_size_3d_affine_grid_op(device_type: str, dtype: torch.dtype) -> None:
- theta = _probe_zeros(device_type, dtype, 1, 3, 4)
- F.affine_grid(theta, [1, 1, 1, 2, 2], align_corners=True)
-
-
-def supports_unit_size_3d_affine_grid(device: torch.device, dtype: torch.dtype) -> bool:
- """Whether 3D ``affine_grid`` with ``align_corners=True`` can build a grid with a size-1 axis for ``dtype``.
-
- PyTorch builds a size-1 axis through ``torch.tensor``, which has no CPU kernel for half precision.
- Probed at runtime and cached per (device type, dtype).
- """
- return _supports_kernel_probe(_unit_size_3d_affine_grid_op, device.type, dtype)
-
-
def _reflect_padding_op(device_type: str, dtype: torch.dtype) -> None:
F.pad(_probe_zeros(device_type, dtype, 1, 1, 2, 2), (1, 1, 1, 1), mode="reflect")
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index 3eb734df4..1bc7c17bc 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -32,7 +32,6 @@ from testing.base import (
supports_bilinear_3d_grid_sample,
supports_nearest_3d_grid_sample,
supports_replicate_padding_3d,
- supports_unit_size_3d_affine_grid,
)
@@ -136,8 +135,6 @@ class Test3DAugmentationConventions(BaseTester):
# _LinAlgError here, because a size-1 axis makes the vertices coplanar.
if not supports_bilinear_3d_grid_sample(device, dtype):
pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
- if not supports_unit_size_3d_affine_grid(device, dtype):
- pytest.skip("3D affine_grid cannot build a size-1 axis for this device and dtype")
volume = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6)
for augmentation in (K.CenterCrop3D(size, p=1.0), K.RandomCrop3D(size, p=1.0)):
output = augmentation(volume)
diff --git a/tests/geometry/transform/test_cpu_half_sampling.py b/tests/geometry/transform/test_cpu_half_sampling.py
index f6f0cfb98..e94145069 100644
--- a/tests/geometry/transform/test_cpu_half_sampling.py
+++ b/tests/geometry/transform/test_cpu_half_sampling.py
@@ -42,10 +42,10 @@ from kornia.geometry.transform import (
)
from kornia.geometry.transform.imgwarp import _runs_in_float32
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_bilinear_3d_grid_sample
-class TestCPUHalfSampling(BaseTester):
+class TestHalfSampling(BaseTester):
@staticmethod
def _warp(image, operation, align_corners):
batch, _, height, width = image.shape
@@ -133,6 +133,7 @@ class TestCPUHalfSampling(BaseTester):
@staticmethod
def _float32_warp(image, operation, align_corners, param_dtype):
# The transform is rounded to ``param_dtype`` first, so a float64 run of the same inputs is the reference.
+ # Transforms and maps are built on the CPU in float64 and then moved, as MPS has no float64.
batch, _, height, width = image.shape
c = math.cos(math.radians(25.0))
s = math.sin(math.radians(25.0))
@@ -156,7 +157,7 @@ class TestCPUHalfSampling(BaseTester):
return homography_warp(image, homography, (height, width), normalized_homography=False, **options)
if operation == "remap_pixel":
grid = create_meshgrid(height, width, False, dtype=torch.float64)
- points = torch.cat([grid, torch.ones_like(grid[..., :1])], -1) @ rotation.double()[0].T
+ points = torch.cat([grid, torch.ones_like(grid[..., :1])], -1) @ rotation.cpu().double()[0].T
points = points.to(param_dtype).to(image)
return remap(image, points[..., 0], points[..., 1], **options)
if operation == "affine3d":
@@ -195,27 +196,32 @@ class TestCPUHalfSampling(BaseTester):
],
)
@pytest.mark.parametrize("align_corners", [True, False])
- def test_cpu_half_warp_matches_float64(self, device, dtype, operation, align_corners):
- # torch's CPU half grid_sample is corrupt from about 128 px, and a half grid is off by more than half a
- # pixel at 256 px in bfloat16 (#5751): the matrix warps and remap run in float32, so they agree with a
- # float64 run of the same half inputs to the output rounding.
- if device.type != "cpu" or dtype not in (torch.float16, torch.bfloat16):
- pytest.skip("CPU float16/bfloat16 warps run in float32")
+ def test_half_warp_matches_float64(self, device, dtype, operation, align_corners):
+ # torch's CPU half grid_sample is corrupt from about 128 px, and on every device a half grid is off by more
+ # than half a pixel at 256 px in bfloat16 (#5751, #5814): the matrix warps and remap build their grid and
+ # sample in float32, so they agree with a float64 run of the same half inputs to the output rounding. The
+ # float64 reference runs on the CPU, as MPS has no float64.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float16/bfloat16 warps run in float32")
+ if operation.endswith("3d") and not supports_bilinear_3d_grid_sample(device, torch.float32):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device")
image = ((torch.arange(3 * 256 * 256, device=device) % 251).float() / 251).reshape(1, 3, 256, 256).to(dtype)
actual = self._float32_warp(image, operation, align_corners, dtype)
- expected = self._float32_warp(image.double(), operation, align_corners, dtype)
+ expected = self._float32_warp(image.cpu().double(), operation, align_corners, dtype)
assert actual.dtype == dtype
- self.assert_close(actual.double(), expected, rtol=0, atol=torch.finfo(dtype).eps)
+ self.assert_close(actual.cpu().double(), expected, rtol=0, atol=torch.finfo(dtype).eps)
- def test_cpu_half_augmentation_matches_float64(self, device, dtype):
- if device.type != "cpu" or dtype not in (torch.float16, torch.bfloat16):
- pytest.skip("CPU float16/bfloat16 warps run in float32")
+ def test_half_augmentation_matches_float64(self, device, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float16/bfloat16 warps run in float32")
image = ((torch.arange(3 * 256 * 256, device=device) % 251).float() / 251).reshape(1, 3, 256, 256).to(dtype)
aug = RandomAffine(degrees=(25.0, 25.0), p=1.0)
actual = aug(image)
- matrix = aug.transform_matrix[:, :2].double()
- expected = warp_affine(image.double(), matrix, (256, 256), align_corners=False)
- self.assert_close(actual.double(), expected, rtol=0, atol=torch.finfo(dtype).eps)
+ # The float64 reference runs on the CPU, as MPS has no float64.
+ matrix = aug.transform_matrix[:, :2].cpu().double()
+ expected = warp_affine(image.cpu().double(), matrix, (256, 256), align_corners=False)
+ assert actual.dtype == dtype
+ self.assert_close(actual.cpu().double(), expected, rtol=0, atol=torch.finfo(dtype).eps)
@pytest.mark.parametrize("operation", ["affine", "perspective", "remap_pixel"])
def test_cpu_half_warp_gradients_run_in_float32(self, device, dtype, operation):
@@ -254,34 +260,47 @@ class TestCPUHalfSampling(BaseTester):
assert torch.isfinite(actual_grad).all()
self.assert_close(actual_grad, expected_grad, atol=0, rtol=0)
+ @staticmethod
+ def _rejects_mismatched_grid(device, dtype):
+ # torch 2.5.1's MPS grid_sample samples a half input with a float32 grid instead of rejecting it.
+ try:
+ F.grid_sample(torch.zeros(1, 1, 2, 2, device=device, dtype=dtype), torch.zeros(1, 1, 1, 2, device=device))
+ except RuntimeError:
+ return True
+ return False
+
@pytest.mark.parametrize("size", [0, 4])
@pytest.mark.parametrize("map_dtype", [torch.float32, torch.int64])
def test_mismatched_grid_dtype(self, device, dtype, size, map_dtype):
- if device.type != "cpu" or dtype not in (torch.float16, torch.bfloat16):
- pytest.skip("CPU half sampling dtype validation")
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half sampling dtype validation")
+ if not self._rejects_mismatched_grid(device, dtype):
+ pytest.skip("torch's grid_sample accepts a grid of another dtype on this device")
image = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
coords = torch.zeros(1, size, 4, device=device, dtype=map_dtype)
- with pytest.raises(RuntimeError, match=r"(dtype|scalar type|grid_sampler_2d_cpu not implemented)"):
+ with pytest.raises(RuntimeError, match=r"(dtype|scalar type|same type|grid_sampler_2d_cpu not implemented)"):
remap(image, coords, coords, normalized_coordinates=True)
def test_mismatched_matrix_dtype(self, device, dtype):
# A float32 matrix next to a half image is rejected as before; only matching dtypes move to float32.
- if device.type != "cpu" or dtype not in (torch.float16, torch.bfloat16):
- pytest.skip("CPU half sampling dtype validation")
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half sampling dtype validation")
+ if not self._rejects_mismatched_grid(device, dtype):
+ pytest.skip("torch's grid_sample accepts a grid of another dtype on this device")
image = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
matrix = torch.eye(3, device=device)[None]
- with pytest.raises(RuntimeError, match=r"(dtype|scalar type|grid_sampler_2d_cpu not implemented)"):
+ with pytest.raises(RuntimeError, match=r"(dtype|scalar type|same type|grid_sampler_2d_cpu not implemented)"):
warp_affine(image, matrix[:, :2], (4, 4))
- with pytest.raises(RuntimeError, match=r"(dtype|scalar type|grid_sampler_2d_cpu not implemented)"):
+ with pytest.raises(RuntimeError, match=r"(dtype|scalar type|same type|grid_sampler_2d_cpu not implemented)"):
warp_perspective(image, matrix, (4, 4))
@pytest.mark.parametrize("half", [torch.float16, torch.bfloat16], ids=["float16", "bfloat16"])
- def test_non_cpu_half_keeps_its_own_dtype(self, half):
- # Only CPU half warps move to float32 (#5751); other devices keep their own half kernels. The meta
- # device stands in for them, so every CI leg checks the device gate.
+ def test_every_device_samples_half_in_float32(self, half):
+ # Half warps move to float32 on every device, not only on the CPU and CUDA legs CI runs (#5751, #5814).
+ # The meta device stands in for the others, so every CI leg checks that the policy has no device gate.
image = torch.zeros(1, 1, 4, 4, device="meta", dtype=half)
grid = torch.zeros(1, 4, 4, 2, device="meta", dtype=half)
- assert not _runs_in_float32(image, image[:, 0])
+ assert _runs_in_float32(image, image[:, 0])
seen = []
def record(src, *args, **kwargs):
@@ -289,5 +308,6 @@ class TestCPUHalfSampling(BaseTester):
return src
with patch.object(F, "grid_sample", side_effect=record):
- _torch_grid_sample(image, grid)
- assert seen == [half]
+ output = _torch_grid_sample(image, grid)
+ assert seen == [torch.float32]
+ assert output.dtype == half
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index a41d01ff3..647145143 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -504,14 +504,15 @@ class TestHomographyWarp3dVoxelCoordinates(BaseTester):
# 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.
+ # 3-D normalized grid is corner-aligned under both settings (#4503). A half 3-D warp runs in float32 on
+ # every device (#5751, #5814), 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
+ half_in_float32 = dtype in (torch.float16, torch.bfloat16)
+ reference_dtype = torch.float32 if half_in_float32 else dtype
normalized = proj.homography_warp(
volume[:, :, 0].to(reference_dtype),
identity[:, :3, :3].to(reference_dtype),
@@ -636,8 +637,9 @@ class TestHomographyWarp3dVoxelCoordinates(BaseTester):
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
+ # a float16/bfloat16 warp runs in float32 on every device and returns the input dtype (#5751, #5814)
+ half_in_float32 = dtype in (torch.float16, torch.bfloat16)
+ work = torch.float32 if half_in_float32 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)