Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): stabilize CPU half precision warps (#5758)

Puttala Jeevan Kumard99074c438c9
diff --git a/README.md b/README.md
index 0b9cdb398..042528df4 100644
--- a/README.md
+++ b/README.md
@@ -97,7 +97,7 @@ covers CUDA or MPS half precision.
| `kornia.enhance` | ✅ | ⚠️ | 0 / 2 | bfloat16: `DiffJPEG` and ZCA accuracy |
| `kornia.morphology` | ✅ | ✅ | 0 / 0 | |
| `kornia.augmentation` | ⚠️ | ⚠️ | 200 / 56 | float16: 108 entries are `CutmixGenerator`, whose Dirichlet sampling rejects float16 parameters; bfloat16: mostly 3D-augmentation gradient checks (28 of 56 entries are `RandomMotionBlur3D`/`RandomRotation3D` backward) |
-| `kornia.geometry.transform` | ⚠️ | ⚠️ | 43 / 58 | Accuracy misses in rotation matrices, affine/perspective warps, the homography warper and 3D crops |
+| `kornia.geometry.transform` | ⚠️ | ⚠️ | 31 / 32 | Accuracy misses in rotation matrices, affine/perspective warps and the homography warper |
| `kornia.geometry.camera` | ⚠️ | ⚠️ | 13 / 23 | Pinhole `cam2pixel`/`pixel2cam` consistency, distortion round trips, `StereoCamera` reprojection; 12 bfloat16 entries are a test-side dtype assertion |
| `kornia.geometry.calibration` | ⚠️ | ⚠️ | 13 / 12 | `solve_pnp_dlt` rejects half inputs (float32/float64 only); `undistort_points` misses its OpenCV reference values |
| `kornia.geometry.epipolar` | ⚠️ | ⚠️ | 58 / 56 | `find_fundamental`, `find_essential`, `decompose_essential_matrix`, `motion_from_essential*` and `KRt_from_projection` raise `NotImplementedError`: CPU `lu`, `eigh` and QR have no half kernels |
diff --git a/changelog.d/5758.fixed.md b/changelog.d/5758.fixed.md
new file mode 100644
index 000000000..b0bd95523
--- /dev/null
+++ b/changelog.d/5758.fixed.md
@@ -0,0 +1 @@
+On CPU, float16 and bfloat16 warps no longer return corrupted values (NaN, values up to 3.4e38, and in bfloat16 a sampling grid off by more than half a pixel) on images of about 128 px and more. `warp_affine`, `warp_perspective`, `remap`, `warp_affine3d`, `warp_perspective3d`, `homography_warp3d`, `homography_warp` with a pixel homography, and the augmentations and crops built on them now build their sampling grid and sample in float32 and return the input dtype; `homography_warp` with a normalized homography, `HomographyWarper` and the depth, elastic and thin-plate-spline warps sample in float32. On torch 2.5.1, which has no CPU half-precision `grid_sample`, these warps now run instead of raising. Other devices and dtypes are unchanged.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index e38d4b4f8..760547dc4 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -55,9 +55,9 @@ precision, so the table says nothing about those backends.
* - ``kornia.geometry.transform``
- ⚠️ Partial
- ⚠️ Partial
- - 43 / 58
+ - 31 / 32
- Linalg steps go through ``_torch_inverse_cast`` / ``_torch_solve_cast``, but rotation matrices,
- affine/perspective warps, the homography warper and 3D crops miss their accuracy checks.
+ affine/perspective warps and the homography warper miss their accuracy checks.
* - ``kornia.geometry.camera``
- ⚠️ Partial
- ⚠️ Partial
diff --git a/kornia/augmentation/_3d/geometric/base.py b/kornia/augmentation/_3d/geometric/base.py
index b882f02d2..583979c10 100644
--- a/kornia/augmentation/_3d/geometric/base.py
+++ b/kornia/augmentation/_3d/geometric/base.py
@@ -41,7 +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``. In half precision the sampling grid is itself rounded, so the
- error grows with the volume size.
+ 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.
"""
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 443957277..244469e1f 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -40,6 +40,25 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK
from kornia.core.exceptions import DeviceError, TypeCheckError
+def _torch_grid_sample(
+ input: torch.Tensor,
+ grid: torch.Tensor,
+ mode: str = "bilinear",
+ 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.
+
+ 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.
+ """
+ if input.device.type == "cpu" and input.dtype in (torch.float16, torch.bfloat16) 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)
+ return F.grid_sample(input, grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
+
+
def xla_is_available() -> bool:
"""Return whether `torch_xla` is available in the system."""
return importlib.util.find_spec("torch_xla") is not None
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 59b1d8d30..28b13a7a6 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -27,6 +27,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.core.exceptions import ShapeError
+from kornia.core.utils import _torch_grid_sample
from kornia.filters.sobel import spatial_gradient
from kornia.geometry.grid import create_meshgrid
@@ -433,7 +434,7 @@ def warp_frame_depth(
height, width = depth_dst.shape[-2:]
points_2d_src_norm: torch.Tensor = normalize_pixel_coordinates(points_2d_src, height, width) # BxHxWx2
- return F.grid_sample(image_src, points_2d_src_norm, align_corners=True)
+ return _torch_grid_sample(image_src, points_2d_src_norm, align_corners=True)
class DepthWarper(nn.Module):
@@ -683,7 +684,7 @@ class DepthWarper(nn.Module):
>>> image_src = warper(depth_src, image_dst) # NxCxHxW
"""
- return F.grid_sample(
+ return _torch_grid_sample(
patch_dst,
self.warp_grid(depth_src),
mode=self.mode,
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 8c7d697da..121167a0f 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -21,6 +21,7 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.utils import _torch_grid_sample
from kornia.filters import filter2d_separable
from kornia.filters.kernels import get_gaussian_kernel1d
@@ -134,6 +135,6 @@ def elastic_transform2d(
identity = torch.eye(2, 3, device=image.device, dtype=grid_dtype).unsqueeze(0)
grid = F.affine_grid(identity, [1, 1, h, w], align_corners=align_corners)
grid = grid.to(image.dtype)
- return F.grid_sample(
+ return _torch_grid_sample(
image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode, padding_mode=padding_mode
)
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 19756276e..466e01654 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -21,9 +21,9 @@ from abc import abstractmethod
from typing import Any, Optional
import torch
-import torch.nn.functional as F
from torch import nn
+from kornia.core.utils import _torch_grid_sample
from kornia.geometry.grid import create_meshgrid
from .imgwarp import homography_warp, warp_grid
@@ -184,7 +184,7 @@ class HomographyWarper(BaseWarper):
" precompute_warp_grid() with the correct device for the homograhy"
" or change the patch device."
)
- warped_patch = F.grid_sample(
+ warped_patch = _torch_grid_sample(
patch_src,
_warped_grid,
mode=self.mode,
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index b463d9cfd..750fdc8d4 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -27,6 +27,7 @@ from kornia.core.ops import eye_like
from kornia.core.utils import (
_inverse_3x3_closed_form,
_normalize_to_float32_or_float64,
+ _torch_grid_sample,
_torch_inverse_cast,
_torch_solve_cast,
)
@@ -94,6 +95,19 @@ def _remap_grid_dtype(map_xy: torch.Tensor, normalized_coordinates: bool) -> tor
return (map_xy.reshape(-1)[:0] * 1.0).dtype
+def _runs_in_float32(src: torch.Tensor, other: torch.Tensor) -> bool:
+ """Return whether a warp of ``src`` builds its sampling grid and samples in float32.
+
+ 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.
+ """
+ return src.device.type == "cpu" and src.dtype in (torch.float16, torch.bfloat16) and other.dtype == src.dtype
+
+
def _empty_warp_output_2d(
src: torch.Tensor,
transform: torch.Tensor,
@@ -170,7 +184,9 @@ def _empty_warp_output_2d(
fill_value = torch.zeros(sample_channels, device=src.device, dtype=src.dtype)
sampled = _fill_and_warp(sample_src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)
else:
- sampled = F.grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+ sampled = _torch_grid_sample(
+ sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode
+ )
out_zero = sampled.reshape(-1)[:1].sum() * 0.0
return out_zero.reshape(1, 1, 1, 1).expand(src_batch, src.shape[1], dsize[0], dsize[1])
@@ -199,7 +215,7 @@ def _empty_warp_output_3d(
if src.shape[-3] == 0 or src.shape[-2] == 0 or src.shape[-1] == 0:
src_zero = src.reshape(-1)[:1].sum() * 0.0
sample_src = src_zero.reshape(1, 1, 1, 1, 1).expand(src.shape[0], src.shape[1], 1, 1, 1)
- return F.grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+ return _torch_grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
def warp_perspective(
@@ -288,6 +304,9 @@ def warp_perspective(
return _empty_warp_output_2d(
src, M, dsize, mode, padding_mode, align_corners, _matrix_warp_grid_dtype(src, M), fill_value
)
+ out_dtype = src.dtype
+ if _runs_in_float32(src, M):
+ src, M = src.float(), M.float()
# 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
@@ -332,8 +351,10 @@ def warp_perspective(
grid = torch.stack([gx, gy], dim=-1) # (B, H, W, 2)
if padding_mode == "fill":
- return _fill_and_warp(src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)
- return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+ return _fill_and_warp(src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value).to(out_dtype)
+ return _torch_grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode).to(
+ out_dtype
+ )
def warp_affine(
@@ -423,6 +444,9 @@ def warp_affine(
fill_value,
transform_batch_broadcast="src_when_larger",
)
+ out_dtype = src.dtype
+ if _runs_in_float32(src, M):
+ src, M = src.float(), M.float()
M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M_3x3, (H, W), dsize, align_corners=align_corners)
@@ -471,9 +495,11 @@ def warp_affine(
if padding_mode == "fill":
if fill_value is None:
fill_value = torch.zeros(src.shape[1], device=src.device, dtype=src.dtype)
- return _fill_and_warp(src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)
+ return _fill_and_warp(src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value).to(out_dtype)
- return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+ return _torch_grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode).to(
+ out_dtype
+ )
def _fill_and_warp(
@@ -499,11 +525,13 @@ def _fill_and_warp(
elif fill_value.ndim == 1:
fill_value = fill_value.view(1, -1, 1, 1)
- inv_ones_mask = 1 - F.grid_sample(ones_mask, grid, align_corners=align_corners, mode=mode, padding_mode="zeros")
+ inv_ones_mask = 1 - _torch_grid_sample(
+ ones_mask, grid, align_corners=align_corners, mode=mode, padding_mode="zeros"
+ )
inv_color_mask = inv_ones_mask * fill_value
- return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode="zeros") + inv_color_mask
+ return _torch_grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode="zeros") + inv_color_mask
def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
@@ -902,6 +930,9 @@ def remap(
allow_fill=False,
operand="map",
)
+ out_dtype = image.dtype
+ if _runs_in_float32(image, map_xy):
+ image, map_xy = image.float(), map_xy.float()
# F.normalize coordinates if not already normalized
if not normalized_coordinates:
@@ -911,7 +942,9 @@ def remap(
map_xy = map_xy.expand(batch_size, -1, -1, -1)
# warp the image tensor and return
- return F.grid_sample(image, map_xy, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
+ return _torch_grid_sample(image, map_xy, mode=mode, padding_mode=padding_mode, align_corners=align_corners).to(
+ out_dtype
+ )
def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
@@ -1307,6 +1340,9 @@ def warp_affine3d(
raise ValueError(f"Output size must be non-negative. Got {dsize}.")
if dsize[0] == 0 or dsize[1] == 0 or dsize[2] == 0:
return _empty_warp_output_3d(src, M, dsize, flags, padding_mode, align_corners)
+ out_dtype = src.dtype
+ if _runs_in_float32(src, M):
+ src, M = src.float(), M.float()
size_src: tuple[int, int, int] = (D, H, W)
size_out: tuple[int, int, int] = dsize
@@ -1322,7 +1358,9 @@ def warp_affine3d(
# compute meshgrid and apply to input
dsize_out: list[int] = [B, C, *list(size_out)]
grid = F.affine_grid(P_norm, dsize_out, align_corners=align_corners)
- return F.grid_sample(src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode)
+ return _torch_grid_sample(src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode).to(
+ out_dtype
+ )
def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
@@ -1700,10 +1738,13 @@ def warp_perspective3d(
raise ValueError(f"Output size must be non-negative. Got {dsize}.")
if dsize[0] == 0 or dsize[1] == 0 or dsize[2] == 0:
return _empty_warp_output_3d(src, M, dsize, flags, border_mode, align_corners)
+ out_dtype = src.dtype
+ if _runs_in_float32(src, M):
+ src, M = src.float(), M.float()
# launches the warper
d, h, w = src.shape[-3:]
- return _transform_warp_impl3d(src, M, (d, h, w), dsize, flags, border_mode, align_corners)
+ return _transform_warp_impl3d(src, M, (d, h, w), dsize, flags, border_mode, align_corners).to(out_dtype)
def homography_warp(
@@ -1784,7 +1825,9 @@ def homography_warp(
)
warped_grid = warp_grid(grid, src_homo_dst)
- return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
+ return _torch_grid_sample(
+ patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners
+ )
return warp_perspective(
patch_src, src_homo_dst, dsize, mode=mode, padding_mode=padding_mode, align_corners=align_corners
)
@@ -1858,6 +1901,9 @@ def homography_warp3d(
f"src_H_dst.device: {src_homo_dst.device}."
)
+ out_dtype = patch_src.dtype
+ 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,
@@ -1873,4 +1919,6 @@ def homography_warp3d(
grid = grid[..., [1, 2, 0]]
warped_grid = warp_grid3d(grid, src_homo_dst)
- return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
+ return _torch_grid_sample(
+ patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners
+ ).to(out_dtype)
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 6f9e1943b..9165aaf80 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -18,9 +18,8 @@
from __future__ import annotations
import torch
-from torch import nn
-from kornia.core.utils import _torch_solve_cast
+from kornia.core.utils import _torch_grid_sample, _torch_solve_cast
from kornia.geometry.grid import create_meshgrid
__all__ = ["get_tps_transform", "warp_image_tps", "warp_points_tps"]
@@ -289,7 +288,7 @@ def warp_image_tps(
coords = coords.reshape(-1, 2).expand(batch_size, -1, -1)
warped: torch.Tensor = warp_points_tps(coords, kernel_centers, kernel_weights, affine_weights)
warped = warped.view(-1, h, w, 2)
- warped_image: torch.Tensor = nn.functional.grid_sample(
+ warped_image: torch.Tensor = _torch_grid_sample(
image, warped, padding_mode=padding_mode, align_corners=align_corners
)
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 21d21e723..1d132f7dd 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -10,13 +10,11 @@
# pillow: 12.3.0
# generated-by: pytest tests/ --record-known-failures=<candidate> --known-failure-profile=cpu-bfloat16
-call builtins.NotImplementedError tests/augmentation/_3d/test_random_affine_3d.py::TestRandomAffine3D::test_batch_random_affine_3d[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/_3d/test_random_rotation_3d.py::TestRandomRotation3D::test_batch_random_rotation[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/_3d/test_random_rotation_3d.py::TestRandomRotation3D::test_random_rotation[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/container/test_augmentation_sequential.py::TestAugmentationSequential::test_random_crops[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/container/test_augmentation_sequential.py::TestAugmentationSequential::test_random_erasing[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomClahe::test_smoke[cpu-bfloat16]
-call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomCrop::test_pad_if_needed_both[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomGaussianIllumination::test_smoke[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomHue::test_sequential[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomRGBShift::test_random_rgb_shift[cpu-bfloat16]
@@ -355,33 +353,13 @@ call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRescal
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2_broadcast[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy_batch[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy_batch_broadcast[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCenterCrop::test_center_crop_h2_w4[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCenterCrop::test_center_crop_h4_w2[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCenterCrop::test_center_crop_h4_w2_batch[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_align_corners_true[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_crop_batch[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_crop_batch_broadcast[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_crop_non_parallel_box[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropByBoxes::test_crop_by_boxes_resizing[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropByTransform::test_crop_by_boxes_resizing[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357[cpu-bfloat16-crop_size0]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357[cpu-bfloat16-crop_size1]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357[cpu-bfloat16-crop_size2]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357_batch[cpu-bfloat16-crop_size0]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357_batch[cpu-bfloat16-crop_size1]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357_batch[cpu-bfloat16-crop_size2]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCropByBoxes3D::test_crop_by_boxes_no_resizing[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCropByBoxes3D::test_crop_by_boxes_resizing[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-bfloat16-1]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-bfloat16-3]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-bfloat16-1]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-bfloat16-3]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape0]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape1]
-call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape2]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-bfloat16-shape3]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestGetPerspectiveTransform::test_back_and_forth[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestInvertAffineTransform::test_rot90[cpu-bfloat16]
@@ -392,16 +370,16 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotat
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-bfloat16-1]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-bfloat16-2]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-bfloat16-5]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_rotation_inverse[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_convention_normalize_invert_equivalence[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_crop_center_resize[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_rotation_inverse[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation_align_corners[cpu-bfloat16-True]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90x[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90y[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90z[cpu-bfloat16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestPerspectiveTransform3D::test_get_perspective_transform3d_2[cpu-bfloat16-1]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_x[cpu-bfloat16]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y[cpu-bfloat16]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y_large[cpu-bfloat16]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_z[cpu-bfloat16]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_circle[cpu-bfloat16]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_ellipse[cpu-bfloat16]
call builtins.AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_axis_angle[cpu-bfloat16--45.0-x]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index ca81f06b5..112fd99ab 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -10,7 +10,6 @@
# pillow: 12.3.0
# generated-by: pytest tests/ --record-known-failures=<candidate> --known-failure-profile=cpu-float16
-call builtins.NotImplementedError tests/augmentation/_3d/test_random_affine_3d.py::TestRandomAffine3D::test_batch_random_affine_3d[cpu-float16]
call builtins.AssertionError tests/augmentation/_3d/test_random_equalize_3d.py::TestRandomEqualize3D::test_batch_random_equalize[cpu-float16]
call builtins.AssertionError tests/augmentation/_3d/test_random_equalize_3d.py::TestRandomEqualize3D::test_random_equalize[cpu-float16]
call builtins.AssertionError tests/augmentation/_3d/test_random_rotation_3d.py::TestRandomRotation3D::test_batch_random_rotation[cpu-float16]
@@ -237,15 +236,13 @@ call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssen
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2_broadcast[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_affine.py::TestTranslate::test_dxdy_batch[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_crop2d.py::TestCropAndResize::test_crop_non_parallel_box[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357[cpu-float16-crop_size2]
-call builtins.AssertionError tests/geometry/transform/test_crop3d.py::TestCenterCrop3D::test_center_crop_357_batch[cpu-float16-crop_size2]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyNormalTransform::test_normalize_denormalize_round_trip_align_corners_false[cpu-float16-2-5]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-float16-1]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper3D::test_normalize_homography_identity[cpu-float16-3]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-float16-1]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_normalize_homography_identity[cpu-float16-3]
+call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-float16-shape1]
call builtins.AssertionError tests/geometry/transform/test_homography_warper.py::TestHomographyWarper::test_translation[cpu-float16-shape3]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestInvertAffineTransform::test_rot90[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestInvertAffineTransform::test_rot90_batch[cpu-float16]
@@ -258,15 +255,8 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotat
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-float16-1]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-float16-2]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-float16-5]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_fill_padding_translation[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_translation[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_translation_align_corners[cpu-float16-True]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_convention_normalize_invert_equivalence[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_fill_padding_translation[cpu-float16]
+call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_rotation_inverse[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_rotation_inverse[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation[cpu-float16]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation_align_corners[cpu-float16-True]
-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_translation_normalized[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90x[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90y[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGetRotationMatrix3d::test_rot90z[cpu-float16]
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index f835b1a85..b2a7b7bfe 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -720,14 +720,14 @@ class Test3DAugmentationConventions(BaseTester):
K.RandomMotionBlur3D(1, 35.0, 0.5, p=1.0)(torch.rand(1, 1, 5, 5, 5))
@pytest.mark.device_agnostic
- def test_convention_identity_warp_is_roundoff_exact_only_in_full_precision(self):
- # In half precision the sampling grid is itself rounded, so a large volume moves far beyond roundoff.
+ def test_convention_identity_warp_is_roundoff_exact_on_cpu_5751(self):
+ # A CPU half-precision warp runs in float32 (#5751), so a large volume comes back up to the output rounding.
large = torch.rand(1, 1, 32, 48, 96)
assert float((K.RandomRotation3D(0.0, p=1.0)(large) - large).abs().max()) < 1e-3
- if supports_bilinear_3d_grid_sample(torch.device("cpu"), torch.bfloat16):
- half = large.to(torch.bfloat16)
+ for dtype in (torch.float16, torch.bfloat16):
+ half = large.to(dtype)
for aug in (K.RandomRotation3D(0.0, p=1.0), K.RandomAffine3D(0.0, p=1.0)):
- assert float((aug(half) - half).abs().max()) > 0.1
+ assert float((aug(half) - half).abs().max()) < torch.finfo(dtype).eps
@pytest.mark.device_agnostic
def test_convention_center_crop3d_centres_each_axis_with_its_own_offset(self):
diff --git a/tests/geometry/transform/test_cpu_half_sampling.py b/tests/geometry/transform/test_cpu_half_sampling.py
new file mode 100644
index 000000000..f6f0cfb98
--- /dev/null
+++ b/tests/geometry/transform/test_cpu_half_sampling.py
@@ -0,0 +1,293 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+
+import math
+from unittest.mock import patch
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+from kornia.augmentation import RandomAffine
+from kornia.core.utils import _torch_grid_sample
+from kornia.geometry import DepthWarper, PinholeCamera, warp_frame_depth
+from kornia.geometry.grid import create_meshgrid
+from kornia.geometry.transform import (
+ HomographyWarper,
+ elastic_transform2d,
+ homography_warp,
+ homography_warp3d,
+ remap,
+ rotate,
+ warp_affine,
+ warp_affine3d,
+ warp_image_tps,
+ warp_perspective,
+ warp_perspective3d,
+)
+from kornia.geometry.transform.imgwarp import _runs_in_float32
+
+from testing.base import BaseTester
+
+
+class TestCPUHalfSampling(BaseTester):
+ @staticmethod
+ def _warp(image, operation, align_corners):
+ batch, _, height, width = image.shape
+ matrix = torch.eye(3, device=image.device, dtype=image.dtype)[None].expand(batch, -1, -1)
+ options = {"align_corners": align_corners}
+ if operation == "identity":
+ return warp_affine(image, matrix[:, :2], (height, width), **options)
+ if operation == "rotate":
+ return rotate(image, image.new_tensor([25.0]), **options)
+ if operation == "fill":
+ matrix = matrix.clone()
+ matrix[:, 0, 2] = 13.5
+ return warp_affine(
+ image,
+ matrix[:, :2],
+ (height, width),
+ padding_mode="fill",
+ fill_value=image.new_tensor([0.25, 0.5, 0.75]),
+ **options,
+ )
+ if operation == "perspective":
+ return warp_perspective(image, matrix, (height, width), **options)
+ if operation == "remap":
+ grid = create_meshgrid(height, width, device=image.device, dtype=image.dtype)
+ return remap(
+ image,
+ grid[..., 0],
+ grid[..., 1],
+ normalized_coordinates=True,
+ mode="nearest",
+ padding_mode="reflection",
+ **options,
+ )
+ if operation == "homography":
+ return homography_warp(image, matrix, (height, width), padding_mode="border", **options)
+ if operation == "cached_homography":
+ warper = HomographyWarper(height, width, **options)
+ warper.precompute_warp_grid(matrix)
+ return warper(image)
+ if operation == "elastic":
+ noise = image.new_zeros(batch, 2, height, width)
+ return elastic_transform2d(image, noise, kernel_size=(3, 3), sigma=(1.0, 1.0), **options)
+ if operation == "tps":
+ centers = image.new_tensor([[[-0.5, -0.5], [0.5, -0.5], [0.0, 0.5]]])
+ weights = torch.zeros_like(centers)
+ affine = image.new_tensor([[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]])
+ return warp_image_tps(image, centers, weights, affine, **options)
+ if operation == "depth":
+ return warp_frame_depth(
+ image, torch.ones_like(image[:, :1]), torch.eye(4, device=image.device, dtype=image.dtype)[None], matrix
+ )
+ if operation == "depth_warper":
+ identity = torch.eye(4, device=image.device, dtype=image.dtype)[None]
+ camera = PinholeCamera(identity, identity.clone(), image.new_tensor([height]), image.new_tensor([width]))
+ warper = DepthWarper(camera, height, width, **options)
+ warper.compute_projection_matrix(camera)
+ return warper(torch.ones_like(image[:, :1]), image)
+ if operation == "augmentation":
+ aug = RandomAffine(degrees=(25.0, 25.0), p=1.0, **options)
+ return aug(image)
+ raise AssertionError(operation)
+
+ # These operations hand grid_sample a grid they built in the image dtype; only the sampling moves to float32.
+ @pytest.mark.parametrize(
+ "operation", ["homography", "cached_homography", "elastic", "tps", "depth", "depth_warper"]
+ )
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_float32_sampling_reference(self, device, dtype, operation, align_corners):
+ if device.type != "cpu":
+ pytest.skip("CPU sampling regression")
+ image = ((torch.arange(3 * 256 * 256, device=device) % 251).float() / 251).reshape(1, 3, 256, 256).to(dtype)
+ sample = F.grid_sample
+
+ def reference(src, grid, **kwargs):
+ work_dtype = torch.float64 if src.dtype == torch.float64 else torch.float32
+ return sample(src.to(work_dtype), grid.to(work_dtype), **kwargs).to(src.dtype)
+
+ with patch.object(F, "grid_sample", side_effect=reference):
+ expected = self._warp(image, operation, align_corners)
+ actual = self._warp(image, operation, align_corners)
+ assert actual.dtype == dtype
+ assert torch.isfinite(actual).all()
+ self.assert_close(actual, expected, atol=0, rtol=0)
+
+ @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.
+ batch, _, height, width = image.shape
+ c = math.cos(math.radians(25.0))
+ s = math.sin(math.radians(25.0))
+ cx, cy = (width - 1) / 2, (height - 1) / 2
+ rotation = (
+ torch.tensor([[[c, -s, cx - c * cx + s * cy], [s, c, cy - s * cx - c * cy]]], dtype=torch.float64)
+ .to(param_dtype)
+ .to(image)
+ )
+ homography = torch.tensor([[[0.9, 0.05, 7.0], [-0.04, 1.1, -3.0], [1e-4, -2e-4, 1.0]]], dtype=torch.float64)
+ homography = homography.to(param_dtype).to(image)
+ options = {"align_corners": align_corners}
+ if operation == "affine":
+ return warp_affine(image, rotation, (height, width), **options)
+ if operation == "affine_fill":
+ fill = torch.tensor([0.25, 0.5, 0.75], dtype=torch.float64).to(param_dtype).to(image)
+ return warp_affine(image, rotation, (height, width), padding_mode="fill", fill_value=fill, **options)
+ if operation == "perspective":
+ return warp_perspective(image, homography, (height, width), **options)
+ if operation == "homography_pixel":
+ 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 = points.to(param_dtype).to(image)
+ return remap(image, points[..., 0], points[..., 1], **options)
+ if operation == "affine3d":
+ volume = image[:, :1].reshape(batch, 1, 64, 32, 32)
+ matrix = torch.tensor([[[c, -s, 0.0, 9.0], [s, c, 0.0, -6.0], [0.0, 0.0, 1.0, 1.5]]], dtype=torch.float64)
+ return warp_affine3d(volume, matrix.to(param_dtype).to(image), (64, 32, 32), align_corners=align_corners)
+ if operation == "perspective3d":
+ volume = image[:, :1].reshape(batch, 1, 64, 32, 32)
+ matrix = torch.eye(4, dtype=torch.float64)[None]
+ matrix[:, :3, :3] = torch.tensor([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]], dtype=torch.float64)
+ matrix[:, :3, 3] = torch.tensor([9.0, -6.0, 1.5], dtype=torch.float64)
+ return warp_perspective3d(
+ volume, matrix.to(param_dtype).to(image), (64, 32, 32), align_corners=align_corners
+ )
+ if operation == "homography3d":
+ volume = image[:, :1].reshape(batch, 1, 64, 32, 32)
+ matrix = torch.eye(4, dtype=torch.float64)[None]
+ matrix[:, :3, :3] = torch.tensor([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]], dtype=torch.float64)
+ matrix[:, :3, 3] = torch.tensor([0.1, -0.05, 0.02], dtype=torch.float64)
+ return homography_warp3d(
+ volume, matrix.to(param_dtype).to(image), (64, 32, 32), align_corners=align_corners
+ )
+ raise AssertionError(operation)
+
+ @pytest.mark.parametrize(
+ "operation",
+ [
+ "affine",
+ "affine_fill",
+ "perspective",
+ "homography_pixel",
+ "remap_pixel",
+ "affine3d",
+ "perspective3d",
+ "homography3d",
+ ],
+ )
+ @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")
+ 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)
+ assert actual.dtype == dtype
+ self.assert_close(actual.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")
+ 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)
+
+ @pytest.mark.parametrize("operation", ["affine", "perspective", "remap_pixel"])
+ def test_cpu_half_warp_gradients_run_in_float32(self, device, dtype, operation):
+ # Forward and backward both run in float32: the half gradients are the float32 ones, rounded.
+ if device.type != "cpu" or dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("CPU float16/bfloat16 warps run in float32")
+ image = torch.linspace(0, 1, 3 * 160 * 144, device=device).reshape(1, 3, 160, 144).to(dtype)
+ half_image = image.clone().requires_grad_()
+ float_image = image.float().requires_grad_()
+ actual = self._float32_warp(half_image, operation, True, dtype)
+ expected = self._float32_warp(float_image, operation, True, dtype).to(dtype)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ (actual_grad,) = torch.autograd.grad(actual.float().square().sum(), half_image)
+ (expected_grad,) = torch.autograd.grad(expected.float().square().sum(), float_image)
+ assert actual_grad.dtype == dtype
+ self.assert_close(actual_grad, expected_grad.to(dtype), rtol=0, atol=0)
+
+ @pytest.mark.parametrize("mode", ["bilinear", "nearest"])
+ @pytest.mark.parametrize("padding_mode", ["zeros", "border", "reflection"])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_sampling_gradients(self, device, dtype, mode, padding_mode, align_corners):
+ if device.type != "cpu":
+ pytest.skip("CPU sampling regression")
+ image = torch.linspace(0, 1, 17 * 19, device=device, dtype=dtype).reshape(1, 1, 17, 19)
+ image.requires_grad_()
+ grid = create_meshgrid(13, 11, device=device, dtype=dtype).mul(1.2).add(0.03).requires_grad_()
+ options = {"mode": mode, "padding_mode": padding_mode, "align_corners": align_corners}
+ actual = remap(image, grid[..., 0], grid[..., 1], normalized_coordinates=True, **options)
+ work_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ expected = F.grid_sample(image.to(work_dtype), grid.to(work_dtype).contiguous(), **options).to(dtype)
+ actual_grads = torch.autograd.grad(actual.sum(), (image, grid))
+ expected_grads = torch.autograd.grad(expected.sum(), (image, grid))
+ self.assert_close(actual, expected, atol=0, rtol=0)
+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):
+ assert actual_grad.dtype == dtype
+ assert torch.isfinite(actual_grad).all()
+ self.assert_close(actual_grad, expected_grad, atol=0, rtol=0)
+
+ @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")
+ 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)"):
+ 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")
+ 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)"):
+ warp_affine(image, matrix[:, :2], (4, 4))
+ with pytest.raises(RuntimeError, match=r"(dtype|scalar 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.
+ 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])
+ seen = []
+
+ def record(src, *args, **kwargs):
+ seen.append(src.dtype)
+ return src
+
+ with patch.object(F, "grid_sample", side_effect=record):
+ _torch_grid_sample(image, grid)
+ assert seen == [half]