Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): optimize float16 and bfloat16 ImageRegistrator models in float32 (#6568)

Dmytro Mishkine4a444e9bb54
diff --git a/changelog.d/6568.fixed.md b/changelog.d/6568.fixed.md
new file mode 100644
index 000000000..72c6545f4
--- /dev/null
+++ b/changelog.d/6568.fixed.md
@@ -0,0 +1,7 @@
+`ImageRegistrator.register` now optimizes a float16 or bfloat16 model or image in float32 and hands the model back in
+its own dtype. It used to optimize in the half dtype, where Adam's second-moment estimate and `eps` round to 0 for
+gradients below about 0.0055: a float16 similarity registration ended in NaN parameters on CPU and raised in
+`linalg.inv` on CUDA, and half registrations stopped short of the float32 result, such as -5.78 to -5.85 degrees
+instead of -6.00 for a 6 degree rotation. A float16, bfloat16 or float32 model now also registers images of another
+of these dtypes, which used to raise in `grid_sample`, and `warp_src_into_dst` and `warp_dst_into_src` sample such a
+pair in float32 and return the image's dtype.
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index fe2077dfc..d3d3be84b 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -50,6 +50,13 @@ from .pyramid import build_pyramid
__all__ = ["BaseModel", "Homography", "ImageRegistrator", "Similarity"]
+_HALF_DTYPES = (torch.float16, torch.bfloat16)
+
+
+def _float32_if_half(tensor: torch.Tensor) -> torch.Tensor:
+ """Return a ``float16``/``bfloat16`` tensor as ``float32``, and any other tensor unchanged."""
+ return tensor.float() if tensor.dtype in _HALF_DTYPES else tensor
+
class BaseModel(ABC, nn.Module):
"""Declare the interface of a transform model that ImageRegistrator optimizes.
@@ -262,6 +269,18 @@ class ImageRegistrator(nn.Module):
gives a shift of :math:`(-t_x, -t_y)`.
- :meth:`register` always starts from the identity, so a loaded ``state_dict`` drives the warps but is not a
warm start.
+ - A ``float16``/``bfloat16`` model or image is optimized in ``float32``: during :meth:`register` both images,
+ also when ``allow_shape_mismatch`` resizes ``src_img``, and the model's half parameters and buffers are
+ ``float32``, and afterwards those tensors and their gradients return to their own dtype, also when
+ :meth:`register` raises. Adam's second-moment estimate ``0.001 * g**2`` and its ``eps`` of ``1e-8`` are
+ both 0 in ``float16`` once ``|g| < 0.0055``, so a ``float16`` optimization divides by zero and ends in NaN,
+ and ``bfloat16`` steps round to the dtype's coarse spacing. For a half model the intermediate models of
+ ``output_intermediate_models`` are computed in ``float32`` and rounded to the model's dtype, so the last
+ one can differ by an ulp from the returned ``self.model()``, which is computed in the model's dtype.
+ - A ``float16``, ``bfloat16`` or ``float32`` model therefore registers images of any of these dtypes.
+ :meth:`warp_src_into_dst` and :meth:`warp_dst_into_src` sample a model and an image of two different ones
+ of them in ``float32`` too and return the image's dtype; a model and an image of the same dtype go to the
+ warper unchanged, as before.
Args:
model_type: Geometrical model for registration: ``'homography'``, ``'similarity'``, or ``'translation'``,
@@ -382,18 +401,36 @@ class ImageRegistrator(nn.Module):
"""
self.reset_model()
- if src_img.shape != dst_img.shape:
- if not self.allow_shape_mismatch:
- raise ValueError(
- f"Cannot register images of different shapes {src_img.shape} {dst_img.shape}. "
- "Consider setting `allow_shape_mismatch = True`"
- )
- src_img = F.interpolate(
- src_img,
- size=dst_img.shape[-2:],
- mode="bilinear",
- align_corners=False,
+ if src_img.shape != dst_img.shape and not self.allow_shape_mismatch:
+ raise ValueError(
+ f"Cannot register images of different shapes {src_img.shape} {dst_img.shape}. "
+ "Consider setting `allow_shape_mismatch = True`"
)
+ # Half precision is optimized in float32 (see the class Convention), the resize of src_img included. Every
+ # promotion runs inside the region that gives the model's tensors their dtype back; restoring a tensor that an
+ # error left unpromoted is a no-op.
+ restore = [(t, t.dtype) for t in (*self.model.parameters(), *self.model.buffers()) if t.dtype in _HALF_DTYPES]
+ try:
+ for tensor, _ in restore:
+ tensor.data = tensor.data.float()
+ src_img, dst_img = _float32_if_half(src_img), _float32_if_half(dst_img)
+ if src_img.shape != dst_img.shape:
+ src_img = F.interpolate(src_img, size=dst_img.shape[-2:], mode="bilinear", align_corners=False)
+ aux_models = self._optimize(src_img, dst_img, verbose, output_intermediate_models)
+ finally:
+ for tensor, dtype in restore:
+ tensor.data = tensor.data.to(dtype)
+ if tensor.grad is not None:
+ tensor.grad = tensor.grad.to(dtype)
+ model = self.model()
+ if output_intermediate_models:
+ return model, [aux.to(model.dtype) for aux in aux_models]
+ return model
+
+ def _optimize(
+ self, src_img: torch.Tensor, dst_img: torch.Tensor, verbose: bool, output_intermediate_models: bool
+ ) -> List[torch.Tensor]:
+ """Run the coarse-to-fine optimization of :meth:`register` and return the model after each level, if asked."""
# ToDo: better parameter passing to optimizer
_opt_args: Dict[str, Any] = {}
_opt_args["lr"] = self.lr
@@ -428,21 +465,25 @@ class ImageRegistrator(nn.Module):
opt.step()
if output_intermediate_models:
aux_models.append(self.model().clone().detach())
- if output_intermediate_models:
- return self.model(), aux_models
- return self.model()
+ return aux_models
+
+ def _warp(self, img: torch.Tensor, model: torch.Tensor) -> torch.Tensor:
+ """Warp ``img`` by ``model`` at the image's size, in the image's dtype (see the class Convention)."""
+ _height, _width = img.shape[-2:]
+ warper = self.warper(_height, _width)
+ if model.dtype == img.dtype:
+ return warper(img, model)
+ # register() optimizes a half model or image in float32, so the two can differ in dtype; such a pair is
+ # sampled in float32 as well
+ return warper(_float32_if_half(img), _float32_if_half(model)).to(img.dtype)
def warp_src_into_dst(self, src_img: torch.Tensor) -> torch.Tensor:
r"""Warp src_img with estimated model."""
- _height, _width = src_img.shape[-2:]
- warper = self.warper(_height, _width)
- return warper(src_img, self.model())
+ return self._warp(src_img, self.model())
def warp_dst_into_src(self, dst_img: torch.Tensor) -> torch.Tensor:
r"""Warp dst_img with inverted estimated model."""
- _height, _width = dst_img.shape[-2:]
- warper = self.warper(_height, _width)
- return warper(dst_img, self.model.forward_inverse())
+ return self._warp(dst_img, self.model.forward_inverse())
@deprecated(replace_with="ImageRegistrator.warp_dst_into_src", version="0.9.0")
def warp_dst_inro_src(self, dst_img: torch.Tensor) -> torch.Tensor:
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index 462ff3137..dd9aeffc7 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -345,11 +345,13 @@ class TestImageRegistrator(BaseTester):
@pytest.mark.parametrize("height, width", [(32, 48), (48, 32)])
def test_register_rotation_non_square_5063(self, device, dtype, height, width):
# dst is src rotated by angle_to_rotation_matrix(6 deg) about the image centre, in pixels. The model maps dst to
- # src, so rot converges to -6 on a non-square image as on a square one: measured -6.00 to -6.01 in float32 and
- # float64, -5.78 to -5.85 in float16 and bfloat16. Rotating in the anisotropic normalized frame converged to
- # -5.27 and -5.42 in float32, and -4.99 to -5.38 in half precision.
- if not supports_bilinear_2d_grid_sample_backward(device, dtype):
- pytest.skip(f"torch has no {dtype} bilinear grid_sample kernel with backward on {device.type}")
+ # src, so rot converges to -6 on a non-square image as on a square one: measured -6.00 to -6.01 in every dtype,
+ # since half precision is optimized in float32 (bfloat16 then rounds the angle to -6.0). Optimizing in the half
+ # dtype stopped at -5.78 to -5.85, and rotating in the anisotropic normalized frame converged to -5.27 and
+ # -5.42 in float32.
+ sampled = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype # the dtype register() samples
+ if not supports_bilinear_2d_grid_sample_backward(device, sampled):
+ pytest.skip(f"torch has no {sampled} bilinear grid_sample kernel with backward on {device.type}")
def scene(degrees: float) -> torch.Tensor:
# smooth analytic blobs, so the fixture needs no seed; sampled at R^-1 (x - c) + c
@@ -368,7 +370,7 @@ class TestImageRegistrator(BaseTester):
ir = ImageRegistrator("rotation", lr=0.1, num_iterations=60, pyramid_levels=1, tolerance=0.0).to(device, dtype)
ir.register(scene(0.0), scene(6.0))
- assert abs(ir.model.rot.item() + 6.0) < 0.4
+ assert abs(ir.model.rot.item() + 6.0) < 0.05
def test_different_shapes_message_6454(self, device, dtype):
# The message carried a run of spaces from its string literal.
@@ -387,17 +389,16 @@ class TestConventionsImageRegistrator(BaseTester):
def _scene(self, dx: float, dy: float, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
# Four Gaussian blobs, moved by (dx, dy) pixels. Analytic, so the fixture needs no seed; register() draws no
- # random numbers either, so every run is deterministic.
+ # random numbers either, so every run is deterministic. Built in float64 on the CPU and then cast, so no
+ # device needs a half arange kernel (torch 2.5.1 has no bfloat16 arange on MPS).
ys, xs = torch.meshgrid(
- torch.arange(self.height, device=device, dtype=dtype),
- torch.arange(self.width, device=device, dtype=dtype),
- indexing="ij",
+ torch.arange(self.height, dtype=torch.float64), torch.arange(self.width, dtype=torch.float64), indexing="ij"
)
blobs = [(12.0, 9.0, 4.0, 1.0), (30.0, 20.0, 6.0, 0.8), (38.0, 7.0, 3.0, 0.6), (20.0, 24.0, 3.5, 0.9)]
- img = torch.zeros(self.height, self.width, device=device, dtype=dtype)
+ img = torch.zeros(self.height, self.width, dtype=torch.float64)
for cx, cy, sigma, amplitude in blobs:
img = img + amplitude * torch.exp(-((xs - dx - cx) ** 2 + (ys - dy - cy) ** 2) / (2 * sigma**2))
- return img[None, None]
+ return img[None, None].to(dtype).to(device)
@staticmethod
def _skip_without_kernels(device: torch.device, dtype: torch.dtype) -> None:
@@ -503,3 +504,82 @@ class TestConventionsImageRegistrator(BaseTester):
assert set(seen) == {((1, 1, self.height, self.width), (1, 1, self.height, self.width))}
with pytest.raises(ValueError):
ir.register(dst.expand(1, 3, -1, -1), dst)
+
+ @pytest.mark.parametrize("resize", [False, True])
+ @pytest.mark.parametrize("model_type", ["similarity", "homography"])
+ def test_convention_image_registrator_optimizes_half_in_float32(self, device, dtype, model_type, resize):
+ # Adam's second-moment estimate 0.001 * g**2 and its eps of 1e-8 are both 0 in float16 once |g| < 0.0055, so
+ # a float16 optimization divided by zero: a float16 similarity registration of this scene ended in NaN on CPU
+ # and raised in linalg.inv on CUDA. A half model is optimized in float32 and handed back in its own dtype, so
+ # it ends where a float32 registration of the same half images does. With allow_shape_mismatch=True that
+ # includes the resize of src_img, which runs in float32 as well.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float16/bfloat16 registration")
+ self._skip_without_kernels(device, torch.float32) # register() samples half images in float32
+ src = self._scene(0.0, 0.0, device, dtype)
+ dst = self._scene(3.0, -1.5, device, dtype)
+ if resize:
+ src = src[..., ::2, ::2]
+ kwargs = {"lr": 3e-3, "num_iterations": 40, "pyramid_levels": 2, "allow_shape_mismatch": resize}
+ ir = ImageRegistrator(model_type, **kwargs).to(device, dtype)
+ reference = ImageRegistrator(model_type, **kwargs).to(device)
+ actual = ir.register(src, dst)
+ expected = reference.register(src.float(), dst.float())
+ assert actual.dtype == dtype
+ assert torch.isfinite(actual).all()
+ for tensor in [*ir.model.parameters(), *ir.model.buffers()]:
+ assert tensor.dtype == dtype
+ expected_parameters = dict(reference.model.named_parameters())
+ # The same float32 optimization: bit for bit on CPU, up to CUDA's atomic grid_sample backward elsewhere.
+ exact = {"rtol": 0.0, "atol": 0.0} if device.type == "cpu" else {}
+ for name, parameter in ir.model.named_parameters():
+ assert parameter.grad is None or parameter.grad.dtype == dtype
+ self.assert_close(parameter, expected_parameters[name].to(dtype), **exact)
+ self.assert_close(actual, expected.to(dtype))
+
+ @pytest.mark.parametrize("model_is_half", [True, False])
+ @pytest.mark.parametrize("other", ["float32", "other half"])
+ def test_convention_image_registrator_warps_mixed_dtypes(self, device, dtype, model_is_half, other):
+ # register() optimizes a half model or image in float32, so a model and images of different dtypes, one of
+ # them half, register; the warps then sample such a pair in float32 as well and return the image's dtype.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float16/bfloat16 registration")
+ self._skip_without_kernels(device, torch.float32) # register() and these warps sample in float32
+ other_half = torch.bfloat16 if dtype == torch.float16 else torch.float16
+ other_dtype = torch.float32 if other == "float32" else other_half
+ model_dtype, image_dtype = (dtype, other_dtype) if model_is_half else (other_dtype, dtype)
+ src = self._scene(0.0, 0.0, device, image_dtype)
+ dst = self._scene(3.0, -1.5, device, image_dtype)
+ ir = ImageRegistrator("similarity", lr=1e-2, num_iterations=10, pyramid_levels=1).to(device, model_dtype)
+ model = ir.register(src, dst).detach()
+ assert model.dtype == model_dtype
+ assert (model[0, :2, 2].abs() > 0.01).all() # a model away from the identity
+ size = (self.height, self.width)
+ expected_src_to_dst = homography_warp(src.float(), model.float(), size, align_corners=False).to(image_dtype)
+ inverse = ir.model.forward_inverse().detach().float()
+ expected_dst_to_src = homography_warp(dst.float(), inverse, size, align_corners=False).to(image_dtype)
+ exact = {"rtol": 0.0, "atol": 0.0}
+ self.assert_close(ir.warp_src_into_dst(src).detach(), expected_src_to_dst, **exact)
+ self.assert_close(ir.warp_dst_into_src(dst).detach(), expected_dst_to_src, **exact)
+
+ def test_convention_image_registrator_failed_setup_keeps_model_dtype(self, device, dtype, monkeypatch):
+ # register() promotes a half model and images to float32 only inside the region that gives the model's tensors
+ # their dtype back, so an error while it prepares the images, such as running out of memory in the float32
+ # copy of src_img, leaves the model in its own dtype.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float16/bfloat16 registration")
+ src = self._scene(0.0, 0.0, device, dtype)
+ ir = ImageRegistrator("similarity", num_iterations=1, pyramid_levels=1).to(device, dtype)
+ to_float = torch.Tensor.float
+
+ def out_of_memory(tensor: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ if tensor.dim() == 4: # an image, not one of the model's tensors
+ raise torch.OutOfMemoryError("fake out of memory")
+ return to_float(tensor, *args, **kwargs)
+
+ monkeypatch.setattr(torch.Tensor, "float", out_of_memory)
+ with pytest.raises(torch.OutOfMemoryError):
+ ir.register(src, src)
+ monkeypatch.undo()
+ for tensor in [*ir.model.parameters(), *ir.model.buffers()]:
+ assert tensor.dtype == dtype