Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry)!: enforce the abstract methods of BaseWarper and BaseModel (#6437)

Muhammad Talha9644dade5006
diff --git a/changelog.d/6437.breaking.md b/changelog.d/6437.breaking.md
new file mode 100644
index 000000000..54fe078c4
--- /dev/null
+++ b/changelog.d/6437.breaking.md
@@ -0,0 +1 @@
+`BaseWarper` and `BaseModel` (the base of `Homography` and `Similarity`) are now real abstract base classes, so constructing one directly, or a subclass that does not implement every abstract method (`forward` and `precompute_warp_grid` for `BaseWarper`; `reset_model`, `forward` and `forward_inverse` for `BaseModel`), raises `TypeError`. Previously the `@abstractmethod` decorators were not enforced: the base class was instantiable and its methods returned `None`, so a subclass that forgot `forward` failed late inside `ImageRegistrator`, or a missing `reset_model` was silently a no-op. Implement all abstract methods in custom warpers and models; `HomographyWarper`, `Homography` and `Similarity` are unchanged.
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index d5ac85aca..7d37dd867 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -32,7 +32,7 @@ Which class to use:
from __future__ import annotations
-from abc import abstractmethod
+from abc import ABC, abstractmethod
from typing import Any, Optional
import torch
@@ -46,16 +46,15 @@ from .imgwarp import _normalize_warped_pixel_grid, _warp_pixel_grid, homography_
__all__ = ["BaseWarper", "HomographyWarper"]
-class BaseWarper(nn.Module):
+class BaseWarper(ABC, nn.Module):
"""Declare the interface of a homography warper module that ImageRegistrator can call.
``BaseWarper(height, width)`` only stores the destination ``height`` and ``width``. A subclass implements
``warper(patch_src, src_homo_dst)``, which samples a ``(B, C, H, W)`` source on that destination grid by a
``(B, 3, 3)`` destination→source homography, and ``precompute_warp_grid(src_homo_dst)``, which caches the grid.
:class:`~kornia.geometry.transform.image_registrator.ImageRegistrator` takes such a class as ``warper`` and calls
- it as ``warper(height, width)``. The two methods are marked abstract, but :class:`torch.nn.Module` does not enforce
- it: ``BaseWarper`` itself constructs, and its ``forward`` returns ``None``
- (`#6399 <https://github.com/kornia/kornia/issues/6399>`_). To warp images, use :class:`HomographyWarper`.
+ it as ``warper(height, width)``. Both methods are abstract: constructing ``BaseWarper`` itself, or a subclass that
+ does not implement both, raises ``TypeError``. To warp images, use :class:`HomographyWarper`.
Convention:
- subclasses receive ``src_homo_dst`` as the destination→source homography
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 025b16134..488848d41 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -34,7 +34,7 @@ Which class to use:
:class:`~kornia.geometry.ransac.RANSAC` or :func:`~kornia.geometry.homography.find_homography_dlt`.
"""
-from abc import abstractmethod
+from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
import torch
@@ -51,16 +51,16 @@ from .pyramid import build_pyramid
__all__ = ["BaseModel", "Homography", "ImageRegistrator", "Similarity"]
-class BaseModel(nn.Module):
+class BaseModel(ABC, nn.Module):
"""Declare the interface of a transform model that ImageRegistrator optimizes.
A subclass holds its transform parameters as :class:`~torch.nn.parameter.Parameter` and implements
``reset_model()``, which returns them to the identity, ``forward()``, the matrix with which its warper warps the
source image into the destination, and ``forward_inverse()``, the matrix of the reverse warp.
:class:`ImageRegistrator` takes an instance as ``model_type``, together with a ``warper`` class. The three methods
- are marked abstract, but :class:`torch.nn.Module` does not enforce it: ``BaseModel`` itself constructs, as
- :class:`~kornia.geometry.transform.BaseWarper` does (`#6399 <https://github.com/kornia/kornia/issues/6399>`_). For
- the built-in models, use :class:`Homography` or :class:`Similarity`.
+ are abstract: constructing ``BaseModel`` itself, or a subclass that does not implement all three, raises
+ ``TypeError``, as for :class:`~kornia.geometry.transform.BaseWarper`. For the built-in models, use
+ :class:`Homography` or :class:`Similarity`.
See Also:
- :class:`Homography`: the built-in model of a full homography.
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index e577efc26..b7a508ecf 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -26,6 +26,50 @@ from testing.base import BaseTester
from testing.error import compute_patch_abs_error
+class TestBaseWarper(BaseTester):
+ def test_base_cannot_be_instantiated(self):
+ with pytest.raises(TypeError, match="abstract"):
+ kornia.geometry.transform.BaseWarper(4, 4)
+
+ def test_abstract_contract(self):
+ assert kornia.geometry.transform.BaseWarper.__abstractmethods__ == {"forward", "precompute_warp_grid"}
+
+ def test_subclass_without_forward_is_rejected(self):
+ class NoForward(kornia.geometry.transform.BaseWarper):
+ def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None:
+ pass
+
+ with pytest.raises(TypeError, match="forward"):
+ NoForward(4, 4)
+
+ def test_subclass_without_precompute_is_rejected(self):
+ class NoPrecompute(kornia.geometry.transform.BaseWarper):
+ def forward(self, patch_src, src_homo_dst=None):
+ return patch_src
+
+ with pytest.raises(TypeError, match="precompute_warp_grid"):
+ NoPrecompute(4, 4)
+
+ def test_complete_subclass_works(self, device, dtype):
+ class Identity(kornia.geometry.transform.BaseWarper):
+ def forward(self, patch_src, src_homo_dst=None):
+ return patch_src
+
+ def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None:
+ pass
+
+ warper = Identity(4, 4).to(device, dtype)
+ assert isinstance(warper, torch.nn.Module)
+ assert (warper.height, warper.width) == (4, 4)
+ patch = torch.rand(1, 1, 4, 4, device=device, dtype=dtype)
+ assert warper(patch) is patch
+
+ def test_homography_warper_stays_concrete(self):
+ warper = kornia.geometry.transform.HomographyWarper(4, 4)
+ assert isinstance(warper, kornia.geometry.transform.BaseWarper)
+ assert not getattr(type(warper), "__abstractmethods__", None)
+
+
class TestHomographyWarper(BaseTester):
num_tests = 10
threshold = 0.1
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index 5a88c2267..ddd1fcb8e 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -113,6 +113,88 @@ class TestHomography(BaseTester):
assert h is not None
+class TestBaseModel(BaseTester):
+ def test_base_cannot_be_instantiated(self):
+ with pytest.raises(TypeError, match="abstract"):
+ kornia.geometry.transform.BaseModel()
+
+ def test_abstract_contract(self):
+ assert kornia.geometry.transform.BaseModel.__abstractmethods__ == {"reset_model", "forward", "forward_inverse"}
+
+ @pytest.mark.parametrize("missing", ["reset_model", "forward", "forward_inverse"])
+ def test_subclass_missing_a_method_is_rejected(self, missing):
+ methods = {
+ "reset_model": lambda self: None,
+ "forward": lambda self: torch.eye(3)[None],
+ "forward_inverse": lambda self: torch.eye(3)[None],
+ }
+ del methods[missing]
+ incomplete = type("Incomplete", (kornia.geometry.transform.BaseModel,), methods)
+
+ with pytest.raises(TypeError, match=missing):
+ incomplete()
+
+ @pytest.mark.parametrize("model_cls", [Homography, Similarity])
+ def test_builtin_models_stay_concrete(self, model_cls):
+ model = model_cls()
+ assert isinstance(model, kornia.geometry.transform.BaseModel)
+ assert not getattr(model_cls, "__abstractmethods__", None)
+
+ def test_custom_model_with_registrator(self, device, dtype):
+ """Verify registration resets and invokes a custom model in both warp directions."""
+ # A complete BaseModel subclass is still an ordinary nn.Module: ImageRegistrator resets it, calls both of its
+ # transforms, optimizes its parameters and returns what it produces.
+ 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}")
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip(f"torch has no {dtype} reflection padding kernel on {device.type}")
+
+ calls = {"reset_model": 0, "forward": 0, "forward_inverse": 0}
+ shift_after_reset = 0.25
+
+ class Translation(kornia.geometry.transform.BaseModel):
+ def __init__(self) -> None:
+ super().__init__()
+ self.shift = torch.nn.Parameter(torch.zeros(2))
+
+ def _homography(self, sign: float) -> torch.Tensor:
+ homography = torch.eye(3, dtype=self.shift.dtype, device=self.shift.device)
+ homography[:2, 2] = sign * self.shift
+ return homography[None]
+
+ def reset_model(self) -> None:
+ calls["reset_model"] += 1
+ torch.nn.init.constant_(self.shift, shift_after_reset)
+
+ def forward(self) -> torch.Tensor:
+ calls["forward"] += 1
+ return self._homography(1.0)
+
+ def forward_inverse(self) -> torch.Tensor:
+ calls["forward_inverse"] += 1
+ return self._homography(-1.0)
+
+ model = Translation()
+ assert [name for name, _ in model.named_parameters()] == ["shift"]
+
+ ir = ImageRegistrator(
+ model, warper=kornia.geometry.transform.HomographyWarper, num_iterations=1, pyramid_levels=1
+ ).to(device, dtype)
+ torch.manual_seed(0)
+ image = torch.rand(1, 1, 16, 16).to(device, dtype)
+ result = ir.register(image, image)
+
+ assert result.shape == (1, 3, 3)
+ # register() resets the model once and fits it through both warp directions
+ assert calls["reset_model"] == 1
+ assert calls["forward"] >= 1
+ assert calls["forward_inverse"] >= 1
+ # the result is the custom model's own transform: reset to the sentinel shift, then moved by one optimizer step
+ # of learning rate 1e-3 at most
+ expected_shift = torch.full((2,), shift_after_reset, device=device, dtype=dtype)
+ self.assert_close(result.detach()[0, :2, 2], expected_shift, atol=0.05, rtol=0.0)
+
+
class TestImageRegistrator(BaseTester):
@pytest.mark.parametrize("model_type", ["homography", "similarity", "translation", "scale", "rotation"])
def test_smoke(self, device, dtype, model_type):