Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): build the warps' matrices and sampling grids outside a caller's autocast (#6596)

Dmytro Mishkin4dd7f9435e82
diff --git a/changelog.d/6596.breaking.md b/changelog.d/6596.breaking.md
new file mode 100644
index 000000000..4096986f7
--- /dev/null
+++ b/changelog.d/6596.breaking.md
@@ -0,0 +1 @@
+`get_rotation_matrix2d`, `get_affine_matrix2d`, `get_affine_matrix3d` and `get_projective_transform` now return float32 for float32 inputs inside a `torch.autocast` region; they used to return the autocast dtype there. A matrix built in the region and used with a half-precision operand outside it now needs an explicit cast: outside the region, `warp_affine(half_image, matrix, dsize)` and `matrix @ half_matrix` used to run and now raise `RuntimeError`. Pass `matrix.to(half_image.dtype)` instead.
diff --git a/changelog.d/6596.fixed.md b/changelog.d/6596.fixed.md
new file mode 100644
index 000000000..39a8b69fb
--- /dev/null
+++ b/changelog.d/6596.fixed.md
@@ -0,0 +1 @@
+`warp_affine`, `warp_perspective`, `warp_affine3d`, `warp_perspective3d`, `warp_grid`, `warp_grid3d`, `homography_warp`, `homography_warp3d`, the thin plate spline functions for float32 points and the builders `get_rotation_matrix2d`, `get_affine_matrix2d`, `get_affine_matrix3d` and `get_projective_transform` now run their matrix products outside a caller's `torch.autocast` region, except in a scripted call, so these functions, `rotate`, `scale`, the crops and the output images of the geometric augmentations built on them give the same result in and out of it, and mixed float32 and half-precision inputs, such as a half-precision matrix a model predicts under AMP with a float32 image, run in float32 there. Under `autocast(bfloat16)` a float32 warp of a `[0, 1]` image was up to 0.97 off and still returned float32, and the builders returned a bfloat16 matrix for float32 inputs.
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 42575fc2a..dd609be10 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -849,6 +849,19 @@ def is_autocast_enabled(both: bool = True) -> bool:
return torch.is_autocast_enabled()
+def _caller_autocast_on(device_type: str) -> bool:
+ """Return whether a caller's autocast region is on for ``device_type``; a device type without autocast has none."""
+ # ``torch.amp.is_autocast_available`` would ask first, but Dynamo cannot trace it on torch 2.5.1. ``meta`` is
+ # answered before asking: under torch.compile, Dynamo turns the RuntimeError below into its own internal error
+ # instead of passing it to the ``except``.
+ if device_type == "meta":
+ return False
+ try:
+ return torch.is_autocast_enabled(device_type)
+ except RuntimeError: # a device type without autocast, such as ``meta``
+ return False
+
+
def _autocast_disabled(device_type: str) -> AbstractContextManager[Any]:
"""Return a context that turns off the caller's autocast region for ``device_type``, if one is on.
@@ -857,20 +870,36 @@ def _autocast_disabled(device_type: str) -> AbstractContextManager[Any]:
``meta``. Every device type torch has an autocast region for is covered, ``xla``, ``hpu`` and a PrivateUse1 backend
too.
"""
- # ``torch.amp.is_autocast_available`` would ask first, but Dynamo cannot trace it on torch 2.5.1. ``meta`` is
- # answered before asking: under torch.compile, Dynamo turns the RuntimeError below into its own internal error
- # instead of passing it to the ``except``.
- if device_type == "meta":
- return nullcontext()
- try:
- enabled = torch.is_autocast_enabled(device_type)
- except RuntimeError: # a device type without autocast, such as ``meta``
- enabled = False
- if enabled:
+ if _caller_autocast_on(device_type):
return torch.autocast(device_type=device_type, enabled=False)
return nullcontext()
+def _reconcile_under_autocast(*tensors: Optional[torch.Tensor]) -> Tuple[Any, ...]:
+ """Return ``tensors`` in float32 if a caller's autocast region would have cast them to one dtype, else unchanged.
+
+ A matrix product in an autocast region casts its float16, bfloat16 and float32 operands to the autocast dtype, so a
+ half-precision matrix from a model under AMP multiplies with a float32 one there, and raises under
+ :func:`_autocast_disabled`. Call this before leaving the region: such operands then meet in float32, which also
+ keeps the arithmetic accurate. Autocast does not cast float64 or integer operands, so a mismatch with those, a
+ mismatch outside autocast, and operands of one dtype all return unchanged and behave as they did. ``None`` entries
+ pass through. TorchScript cannot compile this; a scripted call stays in the caller's region.
+ """
+ first = None
+ mismatched = False
+ for tensor in tensors:
+ if tensor is None:
+ continue
+ if tensor.dtype not in (torch.float32, torch.float16, torch.bfloat16):
+ return tensors
+ if first is None:
+ first = tensor
+ mismatched = mismatched or tensor.dtype != first.dtype
+ if first is None or not (mismatched and _caller_autocast_on(first.device.type)):
+ return tensors
+ return tuple(None if tensor is None else tensor.float() for tensor in tensors)
+
+
# These helpers moved into ``torch.compiler`` over time; resolve them once at import.
_torch_is_compiling = getattr(torch.compiler, "is_compiling", None) or getattr(torch._dynamo, "is_compiling", None)
_torch_is_exporting = getattr(torch.compiler, "is_exporting", None)
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index b98c033f6..508bf0531 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -45,7 +45,7 @@ from typing import Tuple
import torch
-from kornia.core.utils import is_compiling
+from kornia.core.utils import _autocast_disabled, is_compiling
from kornia.geometry.bbox import _validate_bbox3d, infer_bbox_shape3d
from .imgwarp import get_perspective_transform3d, warp_affine3d
@@ -488,8 +488,10 @@ def _check_boxes_related_by_affine(src_box: torch.Tensor, dst_box: torch.Tensor,
mat = dst_trans_src[:, :3].detach().to(work_dtype)
src, dst = src_box.detach().to(work_dtype), dst_box.detach().to(work_dtype)
linear, translation = mat[..., :3].transpose(-1, -2), mat[..., 3:].transpose(-1, -2)
- miss = (src @ linear + translation - dst).abs().amax((-2, -1))
- scale = (src.abs() @ linear.abs() + translation.abs() + dst.abs()).amax((-2, -1))
+ # The products stay out of a caller's autocast region: in bfloat16 their rounding alone exceeds the tolerance.
+ with _autocast_disabled(src.device.type):
+ miss = (src @ linear + translation - dst).abs().amax((-2, -1))
+ scale = (src.abs() @ linear.abs() + translation.abs() + dst.abs()).amax((-2, -1))
tolerance = max(torch.finfo(dst_trans_src.dtype).eps, torch.finfo(torch.float32).eps) ** 0.5 * scale
if bool((miss > tolerance).any()):
raise AssertionError(
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index cec8b7c2f..69a7a5208 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,
+ _reconcile_under_autocast,
_samples_half_in_float32,
_torch_grid_sample,
_torch_inverse_cast,
@@ -287,6 +288,48 @@ def _empty_warp_output_3d(
return _torch_grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+def _warp_perspective_grid(
+ src: torch.Tensor, M: torch.Tensor, dsize: tuple[int, int], align_corners: bool
+) -> torch.Tensor:
+ """Build the ``(B, h, w, 2)`` sampling grid of :func:`warp_perspective` from its pixel homography."""
+ B, _, H, W = src.size()
+ h_out, w_out = dsize
+
+ # H and s*H represent the same projective map. Remove that arbitrary scale before
+ # the coordinate change and inverse: the cubic determinant can overflow/underflow
+ # even when every entry, the sampling positions and their gradients are finite.
+ if M.is_floating_point():
+ M = M / _unit_projective_scale(M)
+
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
+ M, (H, W), (h_out, w_out), align_corners=align_corners
+ ) # Bx3x3
+
+ # Closed-form 3x3 inverse (pure arithmetic) instead of ``torch.linalg.inv``: numerically
+ # equivalent for these well-conditioned transforms, and it runs where the LAPACK/cusolver
+ # backend is unavailable (e.g. the Jetson wheel, where ``linalg.inv`` dlopen-fails and would
+ # otherwise crash every warp on GPU).
+ src_norm_trans_dst_norm = _inverse_3x3_closed_form(dst_norm_trans_src_norm) # Bx3x3
+
+ # Substitutes F.affine_grid (which only handles the affine 2x3 case) by applying the full 3x3
+ # projective transform to every grid point directly.
+ grid = create_meshgrid(
+ h_out, w_out, normalized_coordinates=True, device=src.device, dtype=src.dtype, align_corners=align_corners
+ )
+ if torch.jit.is_tracing():
+ # Under tracing/ONNX use the reference transform_points path (its op set exports cleanly).
+ return transform_points(src_norm_trans_dst_norm[:, None, None], grid.expand(B, h_out, w_out, 2))
+ # Eager fast path: inline the per-point projective map (three broadcasts and a divide),
+ # avoiding transform_points' repeat_interleave of the matrix to B*H copies + homogeneous
+ # round-trip.
+ gx0, gy0 = grid[..., 0], grid[..., 1] # (1, H, W)
+ m = src_norm_trans_dst_norm # (B, 3, 3)
+ denom = m[:, 2, 0, None, None] * gx0 + m[:, 2, 1, None, None] * gy0 + m[:, 2, 2, None, None]
+ gx = (m[:, 0, 0, None, None] * gx0 + m[:, 0, 1, None, None] * gy0 + m[:, 0, 2, None, None]) / denom
+ gy = (m[:, 1, 0, None, None] * gx0 + m[:, 1, 1, None, None] * gy0 + m[:, 1, 2, None, None]) / denom
+ return torch.stack([gx, gy], dim=-1) # (B, H, W, 2)
+
+
def warp_perspective(
src: torch.Tensor,
M: torch.Tensor,
@@ -326,6 +369,8 @@ def warp_perspective(
nonzero entries are rescaled toward unit magnitude before the coordinate change and inversion
- ``src`` sets the dtype: a float32 ``M`` with a float64 ``src`` samples in float64, and a float64 ``M`` with a
float32 ``src`` raises ``RuntimeError``
+ - a caller's autocast region does not change the matrix arithmetic or the sampling grid, outside TorchScript
+ (in the region, a ``src`` and ``M`` that mix float32 and half dtypes run in float32)
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
@@ -378,7 +423,6 @@ def warp_perspective(
if not (len(M.shape) == 3 and M.shape[-2:] == (3, 3)):
raise ValueError(f"Input M must be a Bx3x3 torch.Tensor. Got {M.shape}")
- B, _, H, W = src.size()
h_out, w_out = dsize
if h_out < 0 or w_out < 0:
raise ValueError(f"Output size must be non-negative. Got {dsize}.")
@@ -389,41 +433,18 @@ def warp_perspective(
out_dtype = src.dtype
if _runs_in_float32(src, M):
src, M = src.float(), M.float()
+ if not torch.jit.is_scripting():
+ src, M = _reconcile_under_autocast(src, M)
- # H and s*H represent the same projective map. Remove that arbitrary scale before
- # the coordinate change and inverse: the cubic determinant can overflow/underflow
- # even when every entry, the sampling positions and their gradients are finite.
- if M.is_floating_point():
- M = M / _unit_projective_scale(M)
-
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
- M, (H, W), (h_out, w_out), align_corners=align_corners
- ) # Bx3x3
-
- # Closed-form 3x3 inverse (pure arithmetic) instead of ``torch.linalg.inv``: numerically
- # equivalent for these well-conditioned transforms, and it runs where the LAPACK/cusolver
- # backend is unavailable (e.g. the Jetson wheel, where ``linalg.inv`` dlopen-fails and would
- # otherwise crash every warp on GPU).
- src_norm_trans_dst_norm = _inverse_3x3_closed_form(dst_norm_trans_src_norm) # Bx3x3
-
- # Substitutes F.affine_grid (which only handles the affine 2x3 case) by applying the full 3x3
- # projective transform to every grid point directly.
- grid = create_meshgrid(
- h_out, w_out, normalized_coordinates=True, device=src.device, dtype=src.dtype, align_corners=align_corners
- )
- if torch.jit.is_tracing():
- # Under tracing/ONNX use the reference transform_points path (its op set exports cleanly).
- grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid.expand(B, h_out, w_out, 2))
+ # A caller's autocast region would run the matrix products in half precision and the grid would inherit them: a
+ # float32 warp of a 256 px [0, 1] image was up to 0.5 off in bfloat16, and still returned float32. Only the grid
+ # leaves the region: sampling stays in it, where autocast reconciles the dtypes of the image and the grid as
+ # before. TorchScript has no context managers; a scripted call keeps the caller's precision.
+ if torch.jit.is_scripting():
+ grid = _warp_perspective_grid(src, M, (h_out, w_out), align_corners)
else:
- # Eager fast path: inline the per-point projective map (three broadcasts and a divide),
- # avoiding transform_points' repeat_interleave of the matrix to B*H copies + homogeneous
- # round-trip.
- gx0, gy0 = grid[..., 0], grid[..., 1] # (1, H, W)
- m = src_norm_trans_dst_norm # (B, 3, 3)
- denom = m[:, 2, 0, None, None] * gx0 + m[:, 2, 1, None, None] * gy0 + m[:, 2, 2, None, None]
- gx = (m[:, 0, 0, None, None] * gx0 + m[:, 0, 1, None, None] * gy0 + m[:, 0, 2, None, None]) / denom
- gy = (m[:, 1, 0, None, None] * gx0 + m[:, 1, 1, None, None] * gy0 + m[:, 1, 2, None, None]) / denom
- grid = torch.stack([gx, gy], dim=-1) # (B, H, W, 2)
+ with _autocast_disabled(src.device.type):
+ grid = _warp_perspective_grid(src, M, (h_out, w_out), align_corners)
if padding_mode == "fill":
# One zero per channel, as in warp_affine. It is built here, not before the empty-destination return, whose
@@ -436,6 +457,53 @@ def warp_perspective(
)
+def _warp_affine_grid(src: torch.Tensor, M: torch.Tensor, dsize: tuple[int, int], align_corners: bool) -> torch.Tensor:
+ """Build the ``(B_M, h, w, 2)`` sampling grid of :func:`warp_affine` from its pixel affine matrix."""
+ _, C, H, W = src.size()
+ B_M = M.shape[0]
+
+ 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)
+
+ # Closed-form 3x3 inverse (see warp_perspective) — cusolver-free, so affine warps run on the
+ # Jetson wheel where ``torch.linalg.inv`` dlopen-fails.
+ src_norm_trans_dst_norm = _inverse_3x3_closed_form(dst_norm_trans_src_norm)
+
+ # Generate the grid from the matrix batch. When a single shared transform is passed for a
+ # batch of images (``M`` is ``1x2x3`` with ``src`` ``BxCxHxW``), build one grid and expand it
+ # (a stride-0 view, no copy) instead of materializing B identical grids — this is what makes a
+ # batch-shared warp as cheap as torchvision's. When ``B_M == B`` (per-sample) nothing changes.
+ if torch.jit.is_tracing():
+ # Under tracing/ONNX use F.affine_grid (a single op the exporter lowers cleanly).
+ return F.affine_grid(
+ src_norm_trans_dst_norm[:, :2, :], [B_M, C, dsize[0], dsize[1]], align_corners=align_corners
+ )
+ # Eager fast path: apply the affine matrix to a base grid directly instead of F.affine_grid
+ # — three broadcast multiply-adds per axis, markedly cheaper on launch-bound hardware. The
+ # base grid reproduces F.affine_grid's convention for the requested ``align_corners`` (pixel
+ # corners at +/-1 vs pixel centers). A shared (1x2x3) matrix broadcasts across the batch.
+ h_out, w_out = dsize
+ if align_corners:
+ xs = (
+ torch.zeros(1, device=src.device, dtype=src.dtype)
+ if w_out == 1
+ else torch.linspace(-1.0, 1.0, w_out, device=src.device, dtype=src.dtype)
+ )
+ ys = (
+ torch.zeros(1, device=src.device, dtype=src.dtype)
+ if h_out == 1
+ else torch.linspace(-1.0, 1.0, h_out, device=src.device, dtype=src.dtype)
+ )
+ else:
+ xs = torch.linspace(-1.0 + 1.0 / w_out, 1.0 - 1.0 / w_out, w_out, device=src.device, dtype=src.dtype)
+ ys = torch.linspace(-1.0 + 1.0 / h_out, 1.0 - 1.0 / h_out, h_out, device=src.device, dtype=src.dtype)
+ base_y, base_x = torch.meshgrid(ys, xs, indexing="ij") # (H, W)
+ m = src_norm_trans_dst_norm # (B_M, 3, 3); affine, so the bottom row is [0, 0, 1]
+ gx = m[:, 0, 0, None, None] * base_x + m[:, 0, 1, None, None] * base_y + m[:, 0, 2, None, None]
+ gy = m[:, 1, 0, None, None] * base_x + m[:, 1, 1, None, None] * base_y + m[:, 1, 2, None, None]
+ return torch.stack([gx, gy], dim=-1) # (B_M, H, W, 2)
+
+
def warp_affine(
src: torch.Tensor,
M: torch.Tensor,
@@ -472,6 +540,8 @@ def warp_affine(
- ``M`` is the source→destination **pixel** affine matrix ``(B, 2, 3)``
- ``src`` sets the dtype: a float32 ``M`` with a float64 ``src`` samples in float64, and a float64 ``M`` with a
float32 ``src`` raises ``RuntimeError``
+ - a caller's autocast region does not change the matrix arithmetic or the sampling grid, outside TorchScript
+ (in the region, a ``src`` and ``M`` that mix float32 and half dtypes run in float32)
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
@@ -523,7 +593,7 @@ def warp_affine(
if not (len(M.shape) == 3 and M.shape[-2:] == (2, 3)):
raise ValueError(f"Input M must be a Bx2x3 torch.Tensor. Got {M.shape}")
- B, C, H, W = src.size()
+ B = src.shape[0]
B_M = M.shape[0]
if dsize[0] < 0 or dsize[1] < 0:
raise ValueError(f"Output size must be non-negative. Got {dsize}.")
@@ -542,48 +612,16 @@ def warp_affine(
out_dtype = src.dtype
if _runs_in_float32(src, M):
src, M = src.float(), M.float()
+ if not torch.jit.is_scripting():
+ src, M = _reconcile_under_autocast(src, M)
- 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)
-
- # Closed-form 3x3 inverse (see warp_perspective) — cusolver-free, so affine warps run on the
- # Jetson wheel where ``torch.linalg.inv`` dlopen-fails.
- src_norm_trans_dst_norm = _inverse_3x3_closed_form(dst_norm_trans_src_norm)
-
- # Generate the grid from the matrix batch. When a single shared transform is passed for a
- # batch of images (``M`` is ``1x2x3`` with ``src`` ``BxCxHxW``), build one grid and expand it
- # (a stride-0 view, no copy) instead of materializing B identical grids — this is what makes a
- # batch-shared warp as cheap as torchvision's. When ``B_M == B`` (per-sample) nothing changes.
- if torch.jit.is_tracing():
- # Under tracing/ONNX use F.affine_grid (a single op the exporter lowers cleanly).
- grid = F.affine_grid(
- src_norm_trans_dst_norm[:, :2, :], [B_M, C, dsize[0], dsize[1]], align_corners=align_corners
- )
+ # Outside a caller's autocast region, except the sampling; see warp_perspective.
+ if torch.jit.is_scripting():
+ grid = _warp_affine_grid(src, M, dsize, align_corners)
else:
- # Eager fast path: apply the affine matrix to a base grid directly instead of F.affine_grid
- # — three broadcast multiply-adds per axis, markedly cheaper on launch-bound hardware. The
- # base grid reproduces F.affine_grid's convention for the requested ``align_corners`` (pixel
- # corners at +/-1 vs pixel centers). A shared (1x2x3) matrix broadcasts across the batch.
- h_out, w_out = dsize
- if align_corners:
- xs = (
- torch.zeros(1, device=src.device, dtype=src.dtype)
- if w_out == 1
- else torch.linspace(-1.0, 1.0, w_out, device=src.device, dtype=src.dtype)
- )
- ys = (
- torch.zeros(1, device=src.device, dtype=src.dtype)
- if h_out == 1
- else torch.linspace(-1.0, 1.0, h_out, device=src.device, dtype=src.dtype)
- )
- else:
- xs = torch.linspace(-1.0 + 1.0 / w_out, 1.0 - 1.0 / w_out, w_out, device=src.device, dtype=src.dtype)
- ys = torch.linspace(-1.0 + 1.0 / h_out, 1.0 - 1.0 / h_out, h_out, device=src.device, dtype=src.dtype)
- base_y, base_x = torch.meshgrid(ys, xs, indexing="ij") # (H, W)
- m = src_norm_trans_dst_norm # (B_M, 3, 3); affine, so the bottom row is [0, 0, 1]
- gx = m[:, 0, 0, None, None] * base_x + m[:, 0, 1, None, None] * base_y + m[:, 0, 2, None, None]
- gy = m[:, 1, 0, None, None] * base_x + m[:, 1, 1, None, None] * base_y + m[:, 1, 2, None, None]
- grid = torch.stack([gx, gy], dim=-1) # (B_M, H, W, 2)
+ with _autocast_disabled(src.device.type):
+ grid = _warp_affine_grid(src, M, dsize, align_corners)
+
if torch.jit.is_tracing():
# Keep both batch sizes dynamic. Using their maximum expands a shared grid for non-empty images,
# but leaves a singleton grid intact for an empty source so grid_sample still rejects that pairing.
@@ -713,6 +751,7 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
``1e-8`` of zero after that rescaling: those are left undivided, as
:func:`~kornia.geometry.conversions.convert_points_from_homogeneous` does for points at
infinity
+ - a caller's autocast region does not change the grid, outside TorchScript
Args:
grid: Unwrapped grid of the shape ``(1, H, W, 2)``, or ``(N, H, W, 2)`` with a
@@ -750,7 +789,13 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
src_homo_dst = src_homo_dst / _unit_projective_scale(src_homo_dst)
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
- flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
+ # Outside a caller's autocast region, which would round the matrix product to half precision and the sampling
+ # positions with it. TorchScript has no context managers; a scripted call keeps the caller's precision.
+ if torch.jit.is_scripting():
+ flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
+ else:
+ with _autocast_disabled(src_homo_dst.device.type):
+ flow = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
return flow.view(batch_size, height, width, 2) # NxHxWx2
@@ -821,6 +866,7 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
``1e-8`` of zero after that rescaling: those are left undivided, as
:func:`~kornia.geometry.conversions.convert_points_from_homogeneous` does for points at
infinity
+ - a caller's autocast region does not change the grid, outside TorchScript
Args:
grid: Unwrapped grid of the shape ``(1, D, H, W, 3)``, or ``(N, D, H, W, 3)``
@@ -856,7 +902,12 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
src_homo_dst = src_homo_dst / _unit_projective_scale(src_homo_dst)
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
- flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
+ # Outside a caller's autocast region, as in warp_grid.
+ if torch.jit.is_scripting():
+ flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
+ else:
+ with _autocast_disabled(src_homo_dst.device.type):
+ flow = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
@@ -1123,7 +1174,8 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
\alpha = \text{scale} \cdot \cos(\text{angle}) \\
\beta = \text{scale} \cdot \sin(\text{angle})
- With two different factors, the left 2x2 block is the rotation times ``diag(scale[:, 0], scale[:, 1])``.
+ With two different factors, the left 2x2 block is the rotation times ``diag(scale[:, 0], scale[:, 1])``. A caller's
+ autocast region does not change the result.
Convention:
- ``center`` is ``(x, y)`` in pixels, origin at top-left
@@ -1207,7 +1259,10 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
rotat_m = eye_like(3, center)
rotat_m[:, :2, :2] = angle_to_rotation_matrix(angle)
- affine_m = shift_m @ rotat_m @ scale_m @ shift_m_inv
+ # A caller's autocast region would run these products in half precision: in bfloat16, a rotation about the center
+ # of a 640 x 480 image moved its corner by about 1 px, and came back in bfloat16 for float32 inputs.
+ with _autocast_disabled(center.device.type):
+ affine_m = shift_m @ rotat_m @ scale_m @ shift_m_inv
return affine_m[:, :2, :] # Bx2x3
@@ -1395,6 +1450,8 @@ def get_affine_matrix2d(
- ``sx`` and ``sy`` are angles in radians, using :func:`get_shear_matrix2d`'s
negative-tangent, x-then-y shear about ``center``, applied before rotation, scale and translation
- returns ``(B, 3, 3)`` affine matrix in pixel coordinates
+ - a caller's autocast region does not change the result
+ (there, mixed float32 and half ``center`` and shears run in float32)
Args:
translations: torch.Tensor containing the translation vector with shape ``(B, 2)``.
@@ -1425,8 +1482,11 @@ def get_affine_matrix2d(
transform_h = convert_affinematrix_to_homography(transform)
if any(s is not None for s in [sx, sy]):
- shear_mat = get_shear_matrix2d(center, sx, sy)
- transform_h = transform_h @ shear_mat
+ # Outside a caller's autocast region, as in get_rotation_matrix2d.
+ transform_h, center, sx, sy = _reconcile_under_autocast(transform_h, center, sx, sy)
+ with _autocast_disabled(center.device.type):
+ shear_mat = get_shear_matrix2d(center, sx, sy)
+ transform_h = transform_h @ shear_mat
return transform_h
@@ -1565,6 +1625,8 @@ def get_affine_matrix3d(
rotation convention follows the right-hand rule (see
:func:`kornia.geometry.conversions.axis_angle_to_rotation_matrix`)
- returns ``(B, 4, 4)`` affine matrix in pixel coordinates
+ - a caller's autocast region does not change the result
+ (there, mixed float32 and half ``center`` and shears run in float32)
Args:
translations: torch.Tensor containing the translation vector (dx,dy,dz) with shape ``(B, 3)``.
@@ -1603,8 +1665,13 @@ def get_affine_matrix3d(
# F.pad transform to get Bx3x3
transform_h = convert_affinematrix_to_homography3d(transform)
if any(s is not None for s in [sxy, sxz, syx, syz, szx, szy]):
- shear_mat = get_shear_matrix3d(center, sxy, sxz, syx, syz, szx, szy)
- transform_h = transform_h @ shear_mat
+ # Outside a caller's autocast region, as in get_rotation_matrix2d.
+ transform_h, center, sxy, sxz, syx, syz, szx, szy = _reconcile_under_autocast(
+ transform_h, center, sxy, sxz, syx, syz, szx, szy
+ )
+ with _autocast_disabled(center.device.type):
+ shear_mat = get_shear_matrix3d(center, sxy, sxz, syx, syz, szx, szy)
+ transform_h = transform_h @ shear_mat
return transform_h
@@ -1756,6 +1823,8 @@ def warp_affine3d(
- align_corners: ``True`` by default
- padding_mode: ``'zeros'`` by default
- ``M`` has the batch of ``src``: one matrix is not shared by a larger batch
+ - a caller's autocast region does not change the matrix arithmetic or the sampling grid
+ (there, a ``src`` and ``M`` that mix float32 and half dtypes run in float32)
- an empty batch returns shape ``(0, C, d, h, w)`` with gradients connected to both inputs
even when a source spatial dimension is zero
- a zero output dimension returns an autograd-connected empty tensor;
@@ -1802,21 +1871,25 @@ def warp_affine3d(
out_dtype = src.dtype
if _runs_in_float32(src, M):
src, M = src.float(), M.float()
+ src, M = _reconcile_under_autocast(src, M)
size_src: tuple[int, int, int] = (D, H, W)
size_out: tuple[int, int, int] = dsize
- M_4x4 = convert_affinematrix_to_homography3d(M) # Bx4x4
+ # Outside a caller's autocast region, except the sampling; see warp_perspective. F.affine_grid is a matrix product
+ # too, so the normalization is not the only step it would round.
+ with _autocast_disabled(src.device.type):
+ M_4x4 = convert_affinematrix_to_homography3d(M) # Bx4x4
- # we need to F.normalize the transformation since grid sample needs -1/1 coordinates
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4
+ # we need to F.normalize the transformation since grid sample needs -1/1 coordinates
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4
- src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
- P_norm: torch.Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
+ src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
+ P_norm: torch.Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
- # 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)
+ # 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 _torch_grid_sample(src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode).to(
out_dtype
)
@@ -1898,6 +1971,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
:func:`kornia.geometry.conversions.axis_angle_to_rotation_matrix`); a positive rotation
about +z is **clockwise on screen** (y-down image axes) — opposite of :func:`get_rotation_matrix2d`
- returns the projection matrix ``(B, 3, 4)`` in pixel coordinates
+ - a caller's autocast region does not change the result
Args:
center: center of the rotation (x,y,z) in the source with shape ``(B, 3)``.
@@ -1933,27 +2007,29 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
raise AssertionError(center.dtype, angles.dtype)
_check_scale_shape3d(scales)
- # create rotation matrix
- axis_angle_rad: torch.Tensor = torch.torch.deg2rad(angles)
- rmat: torch.Tensor = axis_angle_to_rotation_matrix(axis_angle_rad) # Bx3x3
- scaling_matrix: torch.Tensor = eye_like(3, rmat)
- scaling_matrix = scaling_matrix * scales.unsqueeze(dim=1)
- rmat = rmat @ scaling_matrix.to(rmat)
+ # Outside a caller's autocast region, as in get_rotation_matrix2d.
+ with _autocast_disabled(center.device.type):
+ # create rotation matrix
+ axis_angle_rad: torch.Tensor = torch.torch.deg2rad(angles)
+ rmat: torch.Tensor = axis_angle_to_rotation_matrix(axis_angle_rad) # Bx3x3
+ scaling_matrix: torch.Tensor = eye_like(3, rmat)
+ scaling_matrix = scaling_matrix * scales.unsqueeze(dim=1)
+ rmat = rmat @ scaling_matrix.to(rmat)
- # define matrix to move forth and back to origin
- from_origin_mat = eye_like(4, rmat, shared_memory=False) # Bx4x4
- from_origin_mat[..., :3, -1] += center
+ # define matrix to move forth and back to origin
+ from_origin_mat = eye_like(4, rmat, shared_memory=False) # Bx4x4
+ from_origin_mat[..., :3, -1] += center
- to_origin_mat = from_origin_mat.clone()
- # An identity plus a translation column is unit triangular, so it is always invertible.
- to_origin_mat = _torch_inverse_cast(from_origin_mat, check_errors=False)
+ to_origin_mat = from_origin_mat.clone()
+ # An identity plus a translation column is unit triangular, so it is always invertible.
+ to_origin_mat = _torch_inverse_cast(from_origin_mat, check_errors=False)
- # append translation with torch.zeros
- proj_mat = projection_from_Rt(rmat, torch.zeros_like(center)[..., None]) # Bx3x4
+ # append translation with torch.zeros
+ proj_mat = projection_from_Rt(rmat, torch.zeros_like(center)[..., None]) # Bx3x4
- # chain 4x4 transforms
- proj_mat = convert_affinematrix_to_homography3d(proj_mat) # Bx4x4
- proj_mat = from_origin_mat @ proj_mat @ to_origin_mat
+ # chain 4x4 transforms
+ proj_mat = convert_affinematrix_to_homography3d(proj_mat) # Bx4x4
+ proj_mat = from_origin_mat @ proj_mat @ to_origin_mat
return proj_mat[..., :3, :] # Bx3x4
@@ -2224,6 +2300,8 @@ def warp_perspective3d(
- align_corners: ``False`` by default (differs from the 2D :func:`warp_perspective`,
whose default is ``True``)
- border_mode: ``'zeros'`` by default
+ - a caller's autocast region does not change the matrix arithmetic or the sampling grid, outside TorchScript
+ (in the region, a ``src`` and ``M`` that mix float32 and half dtypes run in float32)
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
@@ -2272,6 +2350,8 @@ def warp_perspective3d(
out_dtype = src.dtype
if _runs_in_float32(src, M):
src, M = src.float(), M.float()
+ if not torch.jit.is_scripting():
+ src, M = _reconcile_under_autocast(src, M)
# launches the warper
d, h, w = src.shape[-3:]
@@ -2321,6 +2401,9 @@ def homography_warp(
batch
- with ``normalized_coordinates=False`` the pixel 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
+ - with ``normalized_coordinates=True`` a caller's autocast region does not change the sampling grid, outside
+ TorchScript
+ (in the region, a patch and homography that mix float32 and half dtypes run in float32)
- align_corners: ``False`` by default (differs from :func:`warp_perspective`). Along a source axis longer
than one pixel, a pixel homography samples the same positions under both settings, which then differ
only in ``padding_mode="reflection"`` and, with ``mode="nearest"``, in which pixel a sample exactly
@@ -2375,6 +2458,8 @@ def homography_warp(
f"src_H_dst.device: {src_homo_dst.device}."
)
if normalized_homography:
+ if not torch.jit.is_scripting():
+ patch_src, src_homo_dst = _reconcile_under_autocast(patch_src, src_homo_dst)
height, width = dsize
if normalized_coordinates:
grid = create_meshgrid(
@@ -2412,7 +2497,12 @@ def _transform_warp_impl3d(
align_corners: bool,
) -> torch.Tensor:
"""Compute the transform in normalized coordinates and perform the warping."""
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
+ # Outside a caller's autocast region, except the sampling; see warp_perspective.
+ if torch.jit.is_scripting():
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
+ else:
+ with _autocast_disabled(src.device.type):
+ dst_norm_trans_src_norm = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
return homography_warp3d(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode, align_corners, True)
@@ -2457,6 +2547,9 @@ def homography_warp3d(
- 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
+ - with ``normalized_coordinates=True`` a caller's autocast region does not change the sampling grid, outside
+ TorchScript
+ (in the region, a patch and homography that mix float32 and half dtypes run in float32)
- 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"`` and, with ``mode="nearest"``, in which voxel a
@@ -2501,6 +2594,8 @@ def homography_warp3d(
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()
+ if not torch.jit.is_scripting():
+ patch_src, src_homo_dst = _reconcile_under_autocast(patch_src, src_homo_dst)
depth, height, width = dsize
if normalized_coordinates:
grid = create_meshgrid3d(
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index 65494f13c..c041a49cb 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -41,7 +41,7 @@ from __future__ import annotations
import torch
-from kornia.core.utils import _torch_grid_sample, _torch_solve_cast
+from kornia.core.utils import _autocast_disabled, _reconcile_under_autocast, _torch_grid_sample, _torch_solve_cast
from kornia.geometry.grid import create_meshgrid
__all__ = ["get_tps_transform", "warp_image_tps", "warp_points_tps"]
@@ -54,10 +54,19 @@ def _pair_square_euclidean(tensor1: torch.Tensor, tensor2: torch.Tensor) -> torc
Tensors with shapes (B, N, C) and (B, M, C).
"""
+ if not torch.jit.is_scripting():
+ tensor1, tensor2 = _reconcile_under_autocast(tensor1, tensor2)
# ||t1-t2||^2 = (t1-t2)^T(t1-t2) = t1^T*t1 + t2^T*t2 - 2*t1^T*t2
t1_sq: torch.Tensor = tensor1.mul(tensor1).sum(dim=-1, keepdim=True)
t2_sq: torch.Tensor = tensor2.mul(tensor2).sum(dim=-1, keepdim=True).transpose(1, 2)
- t1_t2: torch.Tensor = tensor1.matmul(tensor2.transpose(1, 2))
+ # A caller's autocast region would run this product in half precision and the kernels with it: in bfloat16, a
+ # float32 warp_image_tps of a 256 px [0, 1] image was 0.08 off. TorchScript has no context managers; a scripted call
+ # keeps the caller's precision.
+ if torch.jit.is_scripting():
+ t1_t2: torch.Tensor = tensor1.matmul(tensor2.transpose(1, 2))
+ else:
+ with _autocast_disabled(tensor1.device.type):
+ t1_t2 = tensor1.matmul(tensor2.transpose(1, 2))
square_dist: torch.Tensor = -2 * t1_t2 + t1_sq + t2_sq
return square_dist.clamp(min=0) # handle possible numerical errors
@@ -96,6 +105,9 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> tup
identity mapping gives zero kernel weights and an identity affine up to solver round-off, and any pairs
related by an affine map give zero kernel weights, except a constant map of more than three points, whose
equal ``points_dst`` make the system singular
+ - for float32 points, a caller's autocast region does not change the result, outside TorchScript
+ (in the region, mixed float32 and half points meet in float32, except that CPU autocast raises on a half
+ dtype other than the region's)
- zero or one point makes the linear system singular and ``torch.linalg.solve`` raises; two points, like any
set of points all on one line, make it singular too, but round-off can hide that, and the solve then
returns huge affine weights that throw points off that line far away and may miss the landmarks themselves
@@ -184,6 +196,8 @@ def warp_points_tps(
order; no normalization is applied, and the output is in the same frame, not clamped
- ``kernel_centers`` must be the second argument passed to :func:`get_tps_transform`
(see its Convention block)
+ - for float32 points, a caller's autocast region does not change the result, outside TorchScript
+ (in the region, mixed float32 and half points meet in float32)
Args:
points_src: torch.Tensor of source points ``(B, N, 2)``.
@@ -277,6 +291,9 @@ def warp_image_tps(
:math:`[-1, 1]` sample the padding. Pixel-space control points silently give a wrong
warp of the right shape
- align_corners: ``False`` by default (the matrix warps default to ``True``)
+ - for float32 points, a caller's autocast region does not change the sampling positions, outside TorchScript
+ (in the region, mixed float32 and half points meet in float32, except that CPU autocast raises on a half
+ ``image`` of a dtype other than the region's)
Args:
image: input image torch.Tensor ``(B, C, H, W)``.
diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.py
index 260002089..7071ce504 100644
--- a/tests/augmentation/test_conventions_geometric_matrix.py
+++ b/tests/augmentation/test_conventions_geometric_matrix.py
@@ -29,6 +29,49 @@ from kornia.constants import Resample, SamplePadding
from testing.base import BaseTester
+class TestGeometricAugmentationAutocast(BaseTester):
+ """A caller's autocast region does not reach the matrix or the sampling grid of these augmentations (#6573)."""
+
+ # Exact: in and out of the region run the same arithmetic on one device.
+
+ @pytest.mark.parametrize(
+ "name,make",
+ [
+ ("RandomAffine", lambda: K.RandomAffine(25.0, (0.1, 0.1), (0.9, 1.1), 10.0, p=1.0)),
+ ("RandomRotation", lambda: K.RandomRotation(25.0, p=1.0)),
+ ("RandomPerspective", lambda: K.RandomPerspective(0.3, p=1.0)),
+ ("RandomShear", lambda: K.RandomShear(10.0, p=1.0)),
+ ("RandomAffine3D", lambda: K.RandomAffine3D(25.0, p=1.0)),
+ ("RandomRotation3D", lambda: K.RandomRotation3D(25.0, p=1.0)),
+ ("RandomPerspective3D", lambda: K.RandomPerspective3D(0.3, p=1.0)),
+ ],
+ ids=lambda case: case if isinstance(case, str) else "",
+ )
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_region_does_not_change_the_output_6573(self, name, make, autocast_dtype, device):
+ # In bfloat16 a seeded float32 RandomRotation of a 256 px [0, 1] image was up to 0.83 off, RandomAffine 0.41
+ # and RandomPerspective 0.94, from the half-precision products of the matrix builders and the warps.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ generator = torch.Generator().manual_seed(0)
+ shape = (1, 1, 32, 32, 32) if name.endswith("3D") else (1, 3, 256, 256)
+ image = torch.rand(shape, generator=generator).to(device)
+
+ def run():
+ torch.manual_seed(3)
+ augmentation = make()
+ return augmentation(image), augmentation.transform_matrix
+
+ expected, expected_matrix = run()
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual, actual_matrix = run()
+ assert actual.dtype == actual_matrix.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ self.assert_close(actual_matrix, expected_matrix, rtol=0, atol=0)
+
+
class TestConventionGeometricMatrices(BaseTester):
def test_nearest_resize_uses_nearest_exact_and_half_pixel_matrix(self):
image = torch.arange(49, dtype=torch.float64).view(1, 1, 7, 7)
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index 1011536f5..18709b09a 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -29,6 +29,7 @@ from kornia.core.utils import (
_extract_device_dtype,
_inverse_3x3_closed_form,
_is_singular,
+ _reconcile_under_autocast,
_torch_histc_cast,
_torch_inverse_cast,
_torch_linalg_svdvals,
@@ -1035,6 +1036,55 @@ def test_autocast_disabled_covers_other_autocast_device_types(device_type):
assert not torch.is_autocast_enabled(device_type)
+ "first,second",
+ [
+ (torch.float32, torch.bfloat16),
+ (torch.bfloat16, torch.float32),
+ (torch.float32, torch.float16),
+ (torch.bfloat16, torch.float16),
+ ],
+)
+def test_reconcile_under_autocast_meets_in_float32(first, second):
+ a, b = torch.ones(2, 2, dtype=first), torch.ones(2, 2, dtype=second)
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ out_a, out_none, out_b = _reconcile_under_autocast(a, None, b)
+ assert out_a.dtype == out_b.dtype == torch.float32
+ assert out_none is None
+
+
+ "first,second",
+ [
+ # One dtype has nothing to reconcile, and without a half operand autocast leaves the pair alone.
+ (torch.bfloat16, torch.bfloat16),
+ (torch.float32, torch.float32),
+ # Autocast does not cast float64 or integer operands, so these mismatches keep raising where they did.
+ (torch.float64, torch.bfloat16),
+ (torch.float64, torch.float32),
+ (torch.int64, torch.bfloat16),
+ ],
+)
+def test_reconcile_under_autocast_leaves_what_autocast_leaves(first, second):
+ a, b = torch.ones(2, 2, dtype=first), torch.ones(2, 2, dtype=second)
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ out_a, out_b = _reconcile_under_autocast(a, b)
+ assert out_a is a
+ assert out_b is b
+
+
+def test_reconcile_under_autocast_does_nothing_outside_autocast():
+ a, b = torch.ones(2, 2, dtype=torch.float32), torch.ones(2, 2, dtype=torch.bfloat16)
+ out_a, out_b = _reconcile_under_autocast(a, b)
+ assert out_a is a
+ assert out_b is b
+ # The region of another device type is not this tensor's region either.
+ with torch.autocast("cuda", dtype=torch.float16):
+ out_a, out_b = _reconcile_under_autocast(a, b)
+ assert out_a is a
+ assert out_b is b
+
+
@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
def test_eager_backend_traces_autocast_disabled_on_meta():
# torch.is_autocast_enabled("meta") raises, and under torch.compile Dynamo reports that as its own internal error
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index b57a69ebb..0b6b34e36 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -1453,6 +1453,50 @@ class TestAffine2d(BaseTester):
self.assert_close(out, expected, atol=0, rtol=0)
+class TestWarpByBuiltMatrixAutocast(BaseTester):
+ """rotate, scale and rotate3d build their matrix and warp by it, both outside a caller's autocast region (#6573)."""
+
+ # Exact: in and out of the region run the same arithmetic on one device.
+
+ @staticmethod
+ def _skip_unsupported(device, autocast_dtype):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+
+ @staticmethod
+ def _call(op_name, device, dtype):
+ transform = kornia.geometry.transform
+ generator = torch.Generator().manual_seed(0)
+ if op_name == "rotate3d":
+ volume = torch.rand(1, 1, 32, 32, 32, generator=generator).to(device=device, dtype=dtype)
+ yaw, pitch, roll = (torch.tensor([value], device=device, dtype=dtype) for value in (25.0, 12.5, 8.0))
+ return transform.rotate3d(volume, yaw, pitch, roll)
+ image = torch.rand(1, 3, 256, 256, generator=generator).to(device=device, dtype=dtype)
+ if op_name == "rotate":
+ return transform.rotate(image, torch.tensor([25.0], device=device, dtype=dtype))
+ return transform.scale(image, torch.tensor([[1.13, 1.13]], device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("op_name", ["rotate", "scale", "rotate3d"])
+ @pytest.mark.parametrize("src_dtype", [torch.float32, torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_region_does_not_change_the_warp_6573(self, op_name, src_dtype, autocast_dtype, device):
+ # In bfloat16, float32 rotate, scale and rotate3d of [0, 1] inputs were off by 0.11, 0.36 and 0.14.
+ self._skip_unsupported(device, autocast_dtype)
+ if (
+ device.type == "cpu"
+ and src_dtype in (torch.float16, torch.bfloat16)
+ and src_dtype != getattr(torch, autocast_dtype)
+ ):
+ pytest.skip("CPU autocast rejects a half tensor of the other half dtype in torch.stack and torch.cat")
+ expected = self._call(op_name, device, src_dtype)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = self._call(op_name, device, src_dtype)
+ assert actual.dtype == src_dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+
class TestGetAffineMatrix(BaseTester):
def test_smoke(self, device, dtype):
H, W = 5, 5
diff --git a/tests/geometry/transform/test_crop3d.py b/tests/geometry/transform/test_crop3d.py
index 3f015b1ce..2c23c0305 100644
--- a/tests/geometry/transform/test_crop3d.py
+++ b/tests/geometry/transform/test_crop3d.py
@@ -608,3 +608,37 @@ class TestCrop3DAffineBoxes(BaseTester):
skewed = self._skewed_box(device, dtype)
with pytest.raises(AssertionError, match="affine map"):
kornia.geometry.transform.crop_by_boxes3d(volume, cube, skewed - 2, align_corners=True)
+
+ @pytest.mark.parametrize("region_dtype", ["bfloat16", "float16"])
+ def test_crop_by_boxes3d_takes_fractional_corners_in_a_region_6573(self, region_dtype, device):
+ # The two matrix products of the affine check ran in the region's dtype: in bfloat16 their rounding alone failed
+ # the check on boxes with fractional corners, which pass outside it.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and region_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ volume = torch.rand(1, 1, 64, 64, 64, generator=torch.Generator().manual_seed(0)).to(device)
+ edges = ((11, 0, 0), (0, 7, 0), (0, 0, 5))
+ src = self._box((13.37, 27.81, 41.59), edges, device, torch.float32)
+ dst = self._box((0, 0, 0), edges, device, torch.float32)
+ expected = kornia.geometry.transform.crop_by_boxes3d(volume, src, dst, align_corners=True)
+ with torch.autocast(device.type, dtype=getattr(torch, region_dtype)):
+ actual = kornia.geometry.transform.crop_by_boxes3d(volume, src, dst, align_corners=True)
+ assert actual.dtype == torch.float32
+ # Exact: in and out of the region run the same arithmetic on one device.
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("region_dtype", ["bfloat16", "float16"])
+ def test_crop_by_boxes3d_still_rejects_in_a_region_6573(self, region_dtype, device):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and region_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ volume = self._coordinate_volume(device, torch.float32)
+ cube = self._box((2, 2, 2), ((3, 0, 0), (0, 3, 0), (0, 0, 3)), device, torch.float32)
+ skewed = self._skewed_box(device, torch.float32)
+ with (
+ torch.autocast(device.type, dtype=getattr(torch, region_dtype)),
+ pytest.raises(AssertionError, match="affine map"),
+ ):
+ kornia.geometry.transform.crop_by_boxes3d(volume, cube, skewed - 2, align_corners=True)
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index 098c27262..9c6d841f7 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -576,6 +576,70 @@ class TestHomographyWarper(BaseTester):
self.assert_close(cached, direct, rtol=0, atol=0)
self.assert_close(cached[..., 1:-1], image[..., 1:-1])
+ @pytest.mark.parametrize("entry", ["homography_warp", "module", "precomputed", "warp_grid"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_region_does_not_reach_the_normalized_grid_6573(self, entry, autocast_dtype, device):
+ # warp_grid's matrix product ran in the autocast dtype: in bfloat16 a float32 homography_warp of a 256 px
+ # [0, 1] image was 0.73 off. A grid cached inside the region kept the error outside it.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ image = torch.rand(1, 3, 256, 256, generator=torch.Generator().manual_seed(0)).to(device)
+ homography = torch.tensor(
+ [[[0.9, -0.42, 0.01], [0.42, 0.9, -0.02], [1e-3, 0.0, 1.0]]], device=device, dtype=torch.float32
+ )
+ transform = kornia.geometry.transform
+
+ def warp():
+ if entry == "homography_warp":
+ return transform.homography_warp(image, homography, (256, 256), align_corners=True)
+ warper = transform.HomographyWarper(256, 256, align_corners=True)
+ if entry == "module":
+ return warper(image, homography)
+ if entry == "warp_grid":
+ return transform.warp_grid(warper.grid.to(image), homography)
+ warper.precompute_warp_grid(homography)
+ return warper
+
+ expected = warp()
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = warp()
+ if entry == "precomputed":
+ # the grid was built in the region; the sampling happens outside it
+ expected, actual = expected(image), actual(image)
+ assert actual.dtype == torch.float32
+ # Exact: in and out of the region run the same arithmetic on one device.
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("normalized_coordinates", [True, False])
+ @pytest.mark.parametrize(
+ "patch_dtype,matrix_dtype",
+ [(torch.float32, "bfloat16"), (torch.float32, "float16"), (torch.bfloat16, "float32")],
+ )
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_mixed_dtypes_run_in_float32_in_a_region_6573(
+ self, normalized_coordinates, patch_dtype, matrix_dtype, autocast_dtype, device
+ ):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ image = torch.rand(1, 3, 96, 96, generator=torch.Generator().manual_seed(0)).to(device)
+ values = [[0.9, -0.42, 0.01], [0.42, 0.9, -0.02], [1e-3, 0.0, 1.0]]
+ if not normalized_coordinates:
+ values = [[0.9, -0.42, 30.0], [0.42, 0.9, -20.0], [1e-4, 0.0, 1.0]]
+ homography = torch.tensor([values], device=device, dtype=torch.float32).to(getattr(torch, matrix_dtype))
+ image = image.to(patch_dtype)
+ warp = kornia.geometry.transform.homography_warp
+ options = {"align_corners": True, "normalized_coordinates": normalized_coordinates}
+ expected = warp(image.float(), homography.float(), (96, 96), **options)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = warp(image, homography, (96, 96), **options)
+ assert actual.dtype == torch.float32
+ # Exact: the mixed call in the region and the float32 call outside it run the same arithmetic on one device.
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
@pytest.mark.parametrize("entry", ["functional", "module", "precomputed"])
def test_autocast_does_not_reach_the_pixel_grid(self, entry, device):
# A caller's bfloat16 autocast ran the homography's matrix product in bfloat16 and rounded the pixel columns
@@ -1048,6 +1112,72 @@ class TestHomographyWarper3D(BaseTester):
self.assert_close(grid[..., 2].to(device=device, dtype=dtype), flow[..., 2], atol=1e-4, rtol=1e-4)
+class TestHomographyWarp3dAutocast(BaseTester):
+ """A caller's autocast region does not reach the normalized grid of homography_warp3d and warp_grid3d (#6573)."""
+
+ # Exact: in and out of the region run the same arithmetic on one device.
+
+ @pytest.mark.parametrize("entry", ["homography_warp3d", "warp_grid3d"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_region_does_not_reach_the_normalized_grid_6573(self, entry, autocast_dtype, device):
+ # warp_grid3d's matrix product ran in the autocast dtype: in bfloat16 a float32 homography_warp3d of a 32 voxel
+ # [0, 1] volume was 0.11 off.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ generator = torch.Generator().manual_seed(0)
+ volume = torch.rand(1, 1, 32, 32, 32, generator=generator).to(device)
+ grid = (torch.rand(1, 32, 32, 32, 3, generator=generator).to(device) * 2.0) - 1.0
+ homography = torch.tensor(
+ [[[0.9, -0.42, 0.0, 0.01], [0.42, 0.9, 0.0, -0.02], [0.0, 0.0, 1.0, 0.03], [1e-3, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=torch.float32,
+ )
+ transform = kornia.geometry.transform
+
+ def warp():
+ if entry == "warp_grid3d":
+ return transform.warp_grid3d(grid, homography)
+ return transform.homography_warp3d(volume, homography, (32, 32, 32), align_corners=True)
+
+ expected = warp()
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = warp()
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+
+class TestHomographyWarp3dMixedDtypesAutocast(BaseTester):
+ """A half homography with a float32 volume runs in float32 in a caller's autocast region (#6573)."""
+
+ # Exact: the mixed call in the region and the float32 call outside it run the same arithmetic on one device.
+
+ @pytest.mark.parametrize("normalized_coordinates", [True, False])
+ @pytest.mark.parametrize("matrix_dtype", ["bfloat16", "float16"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_mixed_dtypes_run_in_float32_in_a_region_6573(
+ self, normalized_coordinates, matrix_dtype, autocast_dtype, device
+ ):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ volume = torch.rand(1, 1, 16, 16, 16, generator=torch.Generator().manual_seed(0)).to(device)
+ homography = torch.tensor(
+ [[[0.9, -0.42, 0.0, 0.01], [0.42, 0.9, 0.0, -0.02], [0.0, 0.0, 1.0, 0.03], [1e-3, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=torch.float32,
+ ).to(getattr(torch, matrix_dtype))
+ warp = kornia.geometry.transform.homography_warp3d
+ options = {"align_corners": True, "normalized_coordinates": normalized_coordinates}
+ expected = warp(volume, homography.float(), (16, 16, 16), **options)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = warp(volume, homography, (16, 16, 16), **options)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+
class TestHomographyShapeChecks(BaseTester):
"""A homography of an unsupported rank raises instead of having its first dimension read as the batch."""
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 27dcf7684..d4c29c648 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -1619,6 +1619,290 @@ class TestGetPerspectiveTransformAutocast(BaseTester):
self.assert_close(scripted(src, dst), kornia.geometry.transform.get_perspective_transform(src, dst))
+class TestWarpAutocast(BaseTester):
+ """A caller's autocast region does not reach the sampling grid of warp_affine and warp_perspective (#6573)."""
+
+ # Exact: in and out of the region run the same arithmetic on one device.
+
+ @staticmethod
+ def _skip_unsupported(device, autocast_dtype):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+
+ @staticmethod
+ def _warp_inputs(op_name, device, dtype):
+ # A 25-degree rotation of a 256 px image: the normalized matrix needs more digits than half precision keeps.
+ image = torch.rand(1, 3, 256, 256, generator=torch.Generator().manual_seed(0))
+ center, angle, scale = torch.tensor([[127.5, 127.5]]), torch.tensor([25.0]), torch.ones(1, 2)
+ matrix = kornia.geometry.transform.get_rotation_matrix2d(center, angle, scale)
+ if op_name == "warp_perspective":
+ matrix = torch.cat([matrix, torch.tensor([[[1e-4, 0.0, 1.0]]])], dim=1)
+ return image.to(device=device, dtype=dtype), matrix.to(device=device, dtype=dtype)
+
+ @staticmethod
+ def _warp(op_name, image, matrix):
+ return getattr(kornia.geometry.transform, op_name)(image, matrix, (256, 256), align_corners=False)
+
+ @pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
+ @pytest.mark.parametrize("src_dtype", [torch.float32, torch.float64, torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_region_does_not_change_the_warp_6573(self, op_name, src_dtype, autocast_dtype, device):
+ # normalize_homography's matrix products ran in the autocast dtype: 0.55 off in bfloat16 for a float32 image of
+ # [0, 1] values, without a sign of it, as the output is still float32. A half image runs in float32 and got the
+ # same matrix. Autocast does not cast a float64 one, so its result never changed.
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps" and src_dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ image, matrix = self._warp_inputs(op_name, device, src_dtype)
+ expected = self._warp(op_name, image, matrix)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = self._warp(op_name, image, matrix)
+ assert actual.dtype == src_dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ _mixed_dtypes = (
+ (torch.float32, "bfloat16"),
+ (torch.float32, "float16"),
+ (torch.bfloat16, "float32"),
+ (torch.float16, "float32"),
+ (torch.bfloat16, "float16"),
+ (torch.float16, "bfloat16"),
+ )
+
+ @pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
+ @pytest.mark.parametrize("src_dtype,matrix_dtype", _mixed_dtypes)
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_mixed_dtypes_run_in_float32_in_a_region_6573(
+ self, op_name, src_dtype, matrix_dtype, autocast_dtype, device
+ ):
+ # A half matrix from a model under AMP with a float32 image is a normal training setup. It ran its products in
+ # the autocast dtype, 0.38 off in bfloat16; autocast reconciled the operands, so leaving the region must too.
+ self._skip_unsupported(device, autocast_dtype)
+ image, matrix = self._warp_inputs(op_name, device, torch.float32)
+ image, matrix = image.to(src_dtype), matrix.to(getattr(torch, matrix_dtype))
+ expected = self._warp(op_name, image.float(), matrix.float()).to(src_dtype)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = self._warp(op_name, image, matrix)
+ assert actual.dtype == src_dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
+ def test_region_does_not_change_the_gradient_6573(self, op_name, device):
+ self._skip_unsupported(device, "bfloat16")
+ image, matrix = self._warp_inputs(op_name, device, torch.float32)
+ matrix.requires_grad_()
+ expected = torch.autograd.grad(self._warp(op_name, image, matrix).sum(), matrix)[0]
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ out = self._warp(op_name, image, matrix)
+ actual = torch.autograd.grad(out.sum(), matrix)[0]
+ self.assert_close(actual, expected, rtol=1e-5, atol=1e-5)
+
+ @pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
+ def test_trace_in_a_region_6573(self, op_name, device):
+ # Tracing takes the other grid path, F.affine_grid or transform_points, both matrix products. A trace taken in
+ # the region recorded their half-precision casts, which stayed in the graph after the region.
+ self._skip_unsupported(device, "bfloat16")
+ image, matrix = self._warp_inputs(op_name, device, torch.float32)
+ expected = self._warp(op_name, image, matrix)
+ with torch.autocast(device.type, dtype=torch.bfloat16, cache_enabled=False):
+ traced = torch.jit.trace(lambda x, m: self._warp(op_name, x, m), (image, matrix), check_trace=False)
+ # A compiled or traced graph differs from eager by up to 4.1e-05, over the float32 default.
+ self.assert_close(traced(image, matrix), expected, rtol=1e-3, atol=1e-3)
+
+ @pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
+ def test_still_scriptable_6573(self, op_name, device, dtype):
+ # TorchScript has no context managers, so a scripted call skips the autocast guard; it must keep scripting.
+ image = torch.rand(1, 2, 5, 6, device=device, dtype=dtype)
+ rows = 2 if op_name == "warp_affine" else 3
+ matrix = torch.eye(3, device=device, dtype=dtype)[None, :rows]
+ op = getattr(kornia.geometry.transform, op_name)
+ scripted = torch.jit.script(op)
+ self.assert_close(scripted(image, matrix, (4, 3)), op(image, matrix, (4, 3)))
+
+ @pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_dynamo_mixed_dtypes_in_a_region_6573(self, op_name, autocast_dtype, device, torch_optimizer):
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps":
+ pytest.skip("under torch.compile on MPS, a nested autocast(enabled=False) has no effect (#6601)")
+ image, matrix = self._warp_inputs(op_name, device, torch.float32)
+ half_matrix = matrix.to(getattr(torch, autocast_dtype))
+ op = torch_optimizer(lambda x, m: self._warp(op_name, x, m))
+ expected = self._warp(op_name, image, half_matrix.float())
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = op(image, half_matrix)
+ assert actual.dtype == torch.float32
+ # A compiled or traced graph differs from eager by up to 4.1e-05, over the float32 default.
+ self.assert_close(actual, expected, rtol=1e-3, atol=1e-3)
+
+ @pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_dynamo_in_a_region_6573(self, op_name, autocast_dtype, device, torch_optimizer):
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps":
+ pytest.skip("under torch.compile on MPS, a nested autocast(enabled=False) has no effect (#6601)")
+ image, matrix = self._warp_inputs(op_name, device, torch.float32)
+ op = torch_optimizer(lambda x, m: self._warp(op_name, x, m))
+ expected = self._warp(op_name, image, matrix)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = op(image, matrix)
+ assert actual.dtype == torch.float32
+ # A compiled or traced graph differs from eager by up to 4.1e-05, over the float32 default.
+ self.assert_close(actual, expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(op(image, matrix), expected, rtol=1e-3, atol=1e-3)
+
+
+class TestMatrixBuildersAutocast(BaseTester):
+ """A caller's autocast region does not reach the products of the affine matrix builders (#6573)."""
+
+ # Exact: in and out of the region run the same arithmetic on one device.
+
+ @staticmethod
+ def _skip_unsupported(device, autocast_dtype):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+
+ @staticmethod
+ def _builder(op_name, device, dtype):
+ # A centre far from the origin gives translation entries that need more digits than half precision keeps.
+ def tensor(*values):
+ return torch.tensor(values, device=device, dtype=dtype)
+
+ shear_a, shear_b = tensor(0.13), tensor(0.07)
+ center2, center3 = tensor([319.5, 239.5]), tensor([319.5, 239.5, 15.5])
+ angle2, angle3 = tensor(25.0), tensor([10.0, 20.0, 25.0])
+ scale2, scale3 = tensor([1.13, 0.87]), tensor([1.13, 0.87, 1.05])
+ move2, move3 = tensor([3.3, 1.7]), tensor([3.3, 1.7, 0.9])
+ transform = kornia.geometry.transform
+ builders = {
+ "get_rotation_matrix2d": lambda: transform.get_rotation_matrix2d(center2, angle2, scale2),
+ "get_affine_matrix2d": lambda: transform.get_affine_matrix2d(move2, center2, scale2, angle2),
+ "get_affine_matrix2d_shear": lambda: transform.get_affine_matrix2d(
+ move2, center2, scale2, angle2, shear_a, shear_b
+ ),
+ "get_projective_transform": lambda: transform.get_projective_transform(center3, angle3, scale3),
+ "get_affine_matrix3d": lambda: transform.get_affine_matrix3d(move3, center3, scale3, angle3),
+ "get_affine_matrix3d_shear": lambda: transform.get_affine_matrix3d(
+ move3, center3, scale3, angle3, shear_a, shear_b, shear_a, shear_b, shear_a, shear_b
+ ),
+ }
+ return builders[op_name], angle2 if "2d" in op_name else angle3
+
+ @staticmethod
+ def _shear_builder(op_name, device):
+ def build(dtype, shear_dtype, promote=False):
+ def tensor(values, value_dtype=dtype):
+ return torch.tensor([values], device=device, dtype=torch.float32).to(value_dtype)
+
+ first, second = tensor(0.13, shear_dtype), tensor(0.07, shear_dtype)
+ if promote:
+ first, second = first.float(), second.float()
+ transform = kornia.geometry.transform
+ if op_name == "get_affine_matrix2d":
+ center, scale, angle = tensor([319.5, 239.5]), tensor([1.13, 0.87]), tensor(25.0)
+ return transform.get_affine_matrix2d(tensor([3.3, 1.7]), center, scale, angle, first, second)
+ center, scale, angle = tensor([319.5, 239.5, 15.5]), tensor([1.13, 0.87, 1.05]), tensor([10.0, 20.0, 25.0])
+ shears = (first, second, first, second, first, second)
+ return transform.get_affine_matrix3d(tensor([3.3, 1.7, 0.9]), center, scale, angle, *shears)
+
+ return build
+
+ _builders = (
+ "get_rotation_matrix2d",
+ "get_affine_matrix2d",
+ "get_affine_matrix2d_shear",
+ "get_projective_transform",
+ "get_affine_matrix3d",
+ "get_affine_matrix3d_shear",
+ )
+
+ @pytest.mark.parametrize("op_name", _builders)
+ @pytest.mark.parametrize("src_dtype", [torch.float32, torch.float64, torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_region_does_not_change_the_matrix_6573(self, op_name, src_dtype, autocast_dtype, device):
+ # The matrix products ran in the autocast dtype and the matrix came back in it: in bfloat16, a rotation about
+ # the center of a 640 x 480 image moved its corner by about 1 px, and rotate, scale and the affine
+ # augmentations warped by that matrix.
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps" and src_dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ if (
+ device.type == "cpu"
+ and src_dtype in (torch.float16, torch.bfloat16)
+ and src_dtype != getattr(torch, autocast_dtype)
+ ):
+ pytest.skip("CPU autocast rejects a half tensor of the other half dtype in torch.stack")
+ build, _ = self._builder(op_name, device, src_dtype)
+ expected = build()
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = build()
+ assert actual.dtype == src_dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("op_name", ["get_affine_matrix2d", "get_affine_matrix3d"])
+ @pytest.mark.parametrize("shear_dtype", ["bfloat16", "float16"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_half_shear_with_float32_center_in_a_region_6573(self, op_name, shear_dtype, autocast_dtype, device):
+ # Autocast cast both sides of the shear product, so half shears with a float32 center ran; they meet in float32.
+ self._skip_unsupported(device, autocast_dtype)
+ shear_dtype = getattr(torch, shear_dtype)
+ build = self._shear_builder(op_name, device)
+ expected = build(torch.float32, shear_dtype, promote=True)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = build(torch.float32, shear_dtype)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("op_name", ["get_affine_matrix2d", "get_affine_matrix3d"])
+ @pytest.mark.parametrize("center_dtype", [torch.bfloat16, torch.float16])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_float32_shear_with_half_center_in_a_region_6573(self, op_name, center_dtype, autocast_dtype, device):
+ # The reverse mismatch raised under the guard, while the base ran it in the autocast dtype.
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps":
+ pytest.skip("the reference is in float64, which MPS does not support")
+ if device.type == "cpu" and center_dtype != getattr(torch, autocast_dtype):
+ pytest.skip("CPU autocast rejects a half tensor of the other half dtype in torch.stack")
+ build = self._shear_builder(op_name, device)
+ expected = build(torch.float64, torch.float64)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = build(center_dtype, torch.float32)
+ assert actual.dtype == torch.float32
+ # The rotation part is still built in the half dtype of its inputs, as outside autocast.
+ self.assert_close(actual.double(), expected, rtol=0, atol=2.0)
+
+ @pytest.mark.parametrize("op_name", _builders)
+ def test_region_does_not_change_the_gradient_6573(self, op_name, device):
+ self._skip_unsupported(device, "bfloat16")
+ build, angle = self._builder(op_name, device, torch.float32)
+ angle.requires_grad_()
+ expected = torch.autograd.grad(build().sum(), angle)[0]
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ out = build()
+ actual = torch.autograd.grad(out.sum(), angle)[0]
+ self.assert_close(actual, expected, rtol=1e-5, atol=1e-5)
+
+ @pytest.mark.parametrize("op_name", ["get_rotation_matrix2d", "get_affine_matrix2d_shear"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_dynamo_in_a_region_6573(self, op_name, autocast_dtype, device, torch_optimizer):
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps":
+ pytest.skip("under torch.compile on MPS, a nested autocast(enabled=False) has no effect (#6601)")
+ build, _ = self._builder(op_name, device, torch.float32)
+ expected = build()
+ op = torch_optimizer(build)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = op()
+ assert actual.dtype == torch.float32
+ # A compiled graph differs from eager by up to 6.1e-05 on entries near 200, inside the float32 default's
+ # relative tolerance; this keeps the tolerance of the 2D warps, which need it.
+ self.assert_close(actual, expected, rtol=1e-3, atol=1e-3)
+
+
class TestGetTranslationMatrix2d(BaseTester):
@pytest.mark.parametrize("shape", [(2,), (1,), (3,), (1, 1, 2), (2, 3), (2, 2, 2), ()])
def test_rejects_unsupported_shape(self, shape, device, dtype):
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index 647145143..73aab445a 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -885,6 +885,114 @@ class TestWarpAffine3d(BaseTester):
self.assert_close(output, expected, rtol=1e-4, atol=1e-4)
+class TestWarp3dAutocast(BaseTester):
+ """A caller's autocast region does not reach the sampling grid of warp_affine3d and warp_perspective3d (#6573)."""
+
+ # Exact: in and out of the region run the same arithmetic on one device.
+
+ @staticmethod
+ def _skip_unsupported(device, autocast_dtype):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+
+ @staticmethod
+ def _warp_inputs(op_name, device, dtype):
+ volume = torch.rand(1, 1, 32, 32, 32, generator=torch.Generator().manual_seed(0))
+ center, angles, scales = (
+ torch.tensor([[15.5, 15.5, 15.5]]),
+ torch.tensor([[10.0, 20.0, 25.0]]),
+ torch.ones(1, 3),
+ )
+ matrix = proj.get_projective_transform(center, angles, scales)
+ if op_name == "warp_perspective3d":
+ matrix = torch.cat([matrix, torch.tensor([[[1e-4, 0.0, 0.0, 1.0]]])], dim=1)
+ return volume.to(device=device, dtype=dtype), matrix.to(device=device, dtype=dtype)
+
+ @staticmethod
+ def _warp(op_name, volume, matrix, align_corners=False):
+ return getattr(proj, op_name)(volume, matrix, (32, 32, 32), align_corners=align_corners)
+
+ @pytest.mark.parametrize("op_name", ["warp_affine3d", "warp_perspective3d"])
+ @pytest.mark.parametrize("src_dtype", [torch.float32, torch.float64, torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_region_does_not_change_the_warp_6573(self, op_name, src_dtype, autocast_dtype, align_corners, device):
+ # normalize_homography3d's matrix products and the grid, from F.affine_grid or transform_points, ran in the
+ # autocast dtype: up to 0.17 off in bfloat16 for a float32 volume of [0, 1] values, whose output stayed float32.
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps" and src_dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ volume, matrix = self._warp_inputs(op_name, device, src_dtype)
+ expected = self._warp(op_name, volume, matrix, align_corners)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = self._warp(op_name, volume, matrix, align_corners)
+ assert actual.dtype == src_dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ _mixed_dtypes = (
+ (torch.float32, "bfloat16"),
+ (torch.float32, "float16"),
+ (torch.bfloat16, "float32"),
+ (torch.float16, "float32"),
+ (torch.bfloat16, "float16"),
+ (torch.float16, "bfloat16"),
+ )
+
+ @pytest.mark.parametrize("op_name", ["warp_affine3d", "warp_perspective3d"])
+ @pytest.mark.parametrize("src_dtype,matrix_dtype", _mixed_dtypes)
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_mixed_dtypes_run_in_float32_in_a_region_6573(
+ self, op_name, src_dtype, matrix_dtype, autocast_dtype, device
+ ):
+ # The 3D grid takes the matrix dtype, so a half volume with a matrix of the other half dtype reached grid_sample
+ # with two half dtypes under the guard, which CUDA autocast rejects.
+ self._skip_unsupported(device, autocast_dtype)
+ volume, matrix = self._warp_inputs(op_name, device, torch.float32)
+ volume, matrix = volume.to(src_dtype), matrix.to(getattr(torch, matrix_dtype))
+ expected = self._warp(op_name, volume.float(), matrix.float()).to(src_dtype)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = self._warp(op_name, volume, matrix)
+ assert actual.dtype == src_dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("op_name", ["warp_affine3d", "warp_perspective3d"])
+ def test_region_does_not_change_the_gradient_6573(self, op_name, device):
+ self._skip_unsupported(device, "bfloat16")
+ volume, matrix = self._warp_inputs(op_name, device, torch.float32)
+ matrix.requires_grad_()
+ expected = torch.autograd.grad(self._warp(op_name, volume, matrix).sum(), matrix)[0]
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ out = self._warp(op_name, volume, matrix)
+ actual = torch.autograd.grad(out.sum(), matrix)[0]
+ self.assert_close(actual, expected, rtol=1e-5, atol=1e-5)
+
+ def test_warp_perspective3d_still_scriptable_6573(self, device, dtype):
+ # TorchScript has no context managers, so a scripted call skips the autocast guard; it must keep scripting.
+ volume = torch.rand(1, 2, 4, 5, 6, device=device, dtype=dtype)
+ matrix = torch.eye(4, device=device, dtype=dtype)[None]
+ scripted = torch.jit.script(proj.warp_perspective3d)
+ self.assert_close(scripted(volume, matrix, (3, 4, 5)), proj.warp_perspective3d(volume, matrix, (3, 4, 5)))
+
+ @pytest.mark.parametrize("op_name", ["warp_affine3d", "warp_perspective3d"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_dynamo_in_a_region_6573(self, op_name, autocast_dtype, device, torch_optimizer):
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "mps":
+ pytest.skip("under torch.compile on MPS, a nested autocast(enabled=False) has no effect (#6601)")
+ volume, matrix = self._warp_inputs(op_name, device, torch.float32)
+ op = torch_optimizer(lambda x, m: self._warp(op_name, x, m))
+ expected = self._warp(op_name, volume, matrix)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = op(volume, matrix)
+ assert actual.dtype == torch.float32
+ # A compiled graph differs from eager by up to 6.3e-06 here, inside the float32 default; this keeps the
+ # tolerance of the 2D warps, which need it.
+ self.assert_close(actual, expected, rtol=1e-3, atol=1e-3)
+ self.assert_close(op(volume, matrix), expected, rtol=1e-3, atol=1e-3)
+
+
class TestGetRotationMatrix3d(BaseTester):
def test_smoke(self, device, dtype):
center = torch.rand(1, 3, device=device, dtype=dtype)
diff --git a/tests/geometry/transform/test_thin_plate_spline.py b/tests/geometry/transform/test_thin_plate_spline.py
index 4e1ae6245..fa29ad1d8 100644
--- a/tests/geometry/transform/test_thin_plate_spline.py
+++ b/tests/geometry/transform/test_thin_plate_spline.py
@@ -174,6 +174,106 @@ class TestWarpPoints(BaseTester):
self.assert_close(op(src, dst, kernel, affine), op_jit(src, dst, kernel, affine))
+class TestThinPlateSplineAutocast(BaseTester):
+ """A caller's autocast region does not reach the kernel distances of the thin plate spline (#6573)."""
+
+ # Exact: in and out of the region run the same arithmetic on one device.
+ # Without the guard, warp_points_tps differs by 6.5e-05 in autocast(float16), which passes the float32 default.
+
+ @pytest.mark.parametrize(
+ "entry", ["get_tps_transform", "warp_points_tps", "warp_image_tps", "RandomThinPlateSpline"]
+ )
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_region_does_not_change_the_result_6573(self, entry, autocast_dtype, device):
+ # The one matrix product of _pair_square_euclidean ran in the autocast dtype: in bfloat16, a float32
+ # warp_image_tps of a 256 px [0, 1] image was 0.08 off and a seeded RandomThinPlateSpline 0.29.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+ image = torch.rand(1, 3, 256, 256, generator=torch.Generator().manual_seed(0)).to(device)
+ src = torch.tensor([[[-0.8, -0.8], [0.8, -0.8], [0.8, 0.8], [-0.8, 0.8], [0.1, -0.2]]], device=device)
+ dst = src + torch.tensor(
+ [[[0.03, -0.02], [-0.02, 0.05], [0.04, 0.01], [-0.03, -0.04], [0.02, 0.03]]], device=device
+ )
+ transform = kornia.geometry.transform
+
+ def run():
+ if entry == "RandomThinPlateSpline":
+ torch.manual_seed(3)
+ return kornia.augmentation.RandomThinPlateSpline(p=1.0)(image)
+ kernel, affine = transform.get_tps_transform(src, dst)
+ if entry == "get_tps_transform":
+ return torch.cat([kernel, affine], dim=1)
+ if entry == "warp_points_tps":
+ return transform.warp_points_tps(src, src, kernel, affine)
+ return transform.warp_image_tps(image, src, kernel, affine, align_corners=True)
+
+ expected = run()
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = run()
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+
+class TestThinPlateSplineMixedDtypesAutocast(BaseTester):
+ """Half points with float32 ones meet in float32 in a caller's autocast region, which casts both sides (#6573)."""
+
+ # Exact: the mixed call in the region and the float32 call outside it run the same arithmetic on one device.
+
+ @staticmethod
+ def _skip_unsupported(device, autocast_dtype):
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ if device.type == "cuda" and autocast_dtype == "bfloat16" and not torch.cuda.is_bf16_supported():
+ pytest.skip("this CUDA device does not support bfloat16")
+
+ @staticmethod
+ def _inputs(device):
+ image = torch.rand(1, 3, 96, 96, generator=torch.Generator().manual_seed(0)).to(device)
+ src = torch.tensor([[[-0.8, -0.8], [0.8, -0.8], [0.8, 0.8], [-0.8, 0.8], [0.1, -0.2]]], device=device)
+ dst = src + torch.tensor(
+ [[[0.03, -0.02], [-0.02, 0.05], [0.04, 0.01], [-0.03, -0.04], [0.02, 0.03]]], device=device
+ )
+ kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)
+ return image, src, dst, kernel, affine
+
+ @pytest.mark.parametrize("half", ["bfloat16", "float16"])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_float32_image_half_kernel_centers_6573(self, half, autocast_dtype, device):
+ # A float32 image with kernel centers and weights a model predicted under AMP: the base ran this in the autocast
+ # dtype, and the guard around the matrix product of the distances made it raise.
+ self._skip_unsupported(device, autocast_dtype)
+ half = getattr(torch, half)
+ image, src, _, kernel, affine = self._inputs(device)
+ warp = kornia.geometry.transform.warp_image_tps
+ src, kernel, affine = src.to(half), kernel.to(half), affine.to(half)
+ expected = warp(image, src.float(), kernel.float(), affine.float(), align_corners=True)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ actual = warp(image, src, kernel, affine, align_corners=True)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("first,second", [("float32", "bfloat16"), ("bfloat16", "float32"), ("float32", "float16")])
+ @pytest.mark.parametrize("autocast_dtype", ["bfloat16", "float16"])
+ def test_mixed_points_6573(self, first, second, autocast_dtype, device):
+ self._skip_unsupported(device, autocast_dtype)
+ if device.type == "cpu" and autocast_dtype not in (first, second):
+ pytest.skip("CPU autocast rejects a half tensor of the other half dtype in torch.cat")
+ _, src, dst, kernel, affine = self._inputs(device)
+ src, dst = src.to(getattr(torch, first)), dst.to(getattr(torch, second))
+ transform = kornia.geometry.transform
+ expected_weights = transform.get_tps_transform(src.float(), dst.float())
+ expected_points = transform.warp_points_tps(src.float(), dst.float(), kernel, affine)
+ with torch.autocast(device.type, dtype=getattr(torch, autocast_dtype)):
+ weights = transform.get_tps_transform(src, dst)
+ points = transform.warp_points_tps(src, dst, kernel, affine)
+ assert points.dtype == torch.float32
+ self.assert_close(points, expected_points, rtol=0, atol=0)
+ self.assert_close(weights[0].float(), expected_weights[0])
+ self.assert_close(weights[1].float(), expected_weights[1])
+
+
class TestWarpImage(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 3])
def test_smoke(self, batch_size, device, dtype):