Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): preserve Hyperplane module state (#5717)

Anton Soloviev7c68723682f5
diff --git a/changelog.d/5717.breaking.md b/changelog.d/5717.breaking.md
new file mode 100644
index 000000000..c2cbc1c4e
--- /dev/null
+++ b/changelog.d/5717.breaking.md
@@ -0,0 +1,13 @@
+`Hyperplane` now registers its normal and offset as module state under the keys `_n` and `_d`: `state_dict()`
+saves them, `load_state_dict()` restores them, and `.to()`, `.double()` and an enclosing module's conversions move
+and cast them. Previously a plane's `state_dict()` was empty, loading a state dict into a module holding a plane
+reported success and kept the old plane, and `.to()` left the plane on its original device and dtype.
+As in `ParametrizedLine`, a floating-point tensor without autograd history is now stored as an `nn.Parameter`. So a
+plane built from plain tensors, including the result of `Hyperplane.through` or `fit_plane` on points without autograd
+history, has two trainable parameters (an optimizer built from `model.parameters()` now updates them), and the distances
+and projections it returns require grad (call `.detach()` before `.numpy()`). Previously such a plane had no parameters
+and its outputs did not require grad. A caller's `nn.Parameter` stays a parameter, a tensor with autograd history keeps
+it, and an integer tensor is stored as a buffer.
+A state dict saved before this change has no plane keys, so loading it with `strict=True` now raises on the missing
+`_n` and `_d` keys; `strict=False` reports them and keeps the plane the module was built with, as before. A whole
+module saved with `torch.save` before this change still loads with its plane, which is moved to registered state.
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 5c6254c18..5133f1a7c 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -18,7 +18,7 @@
# kornia.geometry.plane module inspired by Eigen::geometry::Hyperplane
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h
-from typing import Optional
+from typing import Any, Optional
import torch
from torch import nn
@@ -26,7 +26,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE, are_checks_enabled
from kornia.core.exceptions import BaseError, ValueCheckError
from kornia.core.tensor_wrapper import _unwrap, _wrap
-from kornia.core.utils import _torch_linalg_svdvals, _torch_svd_cast, is_compiling
+from kornia.core.utils import _torch_linalg_svdvals, _torch_svd_cast, is_compiling, register_module_state
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.vector import Scalar, Vector3
@@ -47,8 +47,13 @@ class Hyperplane(nn.Module):
- :meth:`through` points the normal along :math:`(p_2 - p_0) \times (p_1 - p_0)`, as Eigen's
``Hyperplane::Through`` does: the opposite of the right-hand normal of the loop
:math:`p_0 \to p_1 \to p_2`. Swapping two points flips it.
- - Known defect: ``normal`` and ``offset`` are not registered module state, so ``state_dict()`` is empty and
- ``.to()`` neither moves nor casts them (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
+ - The normal and offset are registered module state under the keys ``_n`` and ``_d``, so ``state_dict()``,
+ ``load_state_dict()`` and ``.to()`` include both tensors. As in
+ :class:`~kornia.geometry.line.ParametrizedLine`, a floating-point tensor without autograd history becomes
+ an ``nn.Parameter``: a plane built from plain tensors, including the result of :meth:`through` and
+ :func:`fit_plane` on points without autograd history, has trainable parameters, and the distances and
+ projections it returns require grad. A caller's ``nn.Parameter`` is kept, a tensor with autograd history
+ keeps that history, and an integer tensor is stored as a buffer.
Args:
n: The normal vector :math:`n`, a :class:`~kornia.geometry.vector.Vector3`.
@@ -62,8 +67,26 @@ class Hyperplane(nn.Module):
# TODO: fix checkers
# KORNIA_CHECK_SHAPE(n, ["B", "*"])
# KORNIA_CHECK_SHAPE(d, ["B"])
- self._n = n
- self._d = d
+ for name, value in (("_n", n.data), ("_d", d.data)):
+ if value.is_floating_point() or value.is_complex():
+ register_module_state(self, name, value)
+ else:
+ # Integer plane coefficients cannot be trainable parameters.
+ self.register_buffer(name, value)
+
+ def __setstate__(self, state: dict[str, Any]) -> None:
+ super().__setstate__(state)
+ # Whole-object checkpoints predating registered state still hold the tensor wrappers.
+ # Restore the module first so its hooks, training flag and other attributes survive.
+ for name in ("_n", "_d"):
+ value = self.__dict__.get(name)
+ if isinstance(value, (Vector3, Scalar)):
+ delattr(self, name)
+ tensor = value.data
+ if tensor.is_floating_point() or tensor.is_complex():
+ register_module_state(self, name, tensor)
+ else:
+ self.register_buffer(name, tensor)
def __str__(self) -> str:
return f"Normal: {self.normal}\nOffset: {self.offset}"
@@ -80,7 +103,7 @@ class Hyperplane(nn.Module):
direction. For a 3D plane this is the vector :math:`n` in
:math:`n^T x + d = 0`.
"""
- return self._n
+ return Vector3(self._n)
@property
def offset(self) -> Scalar:
@@ -91,7 +114,7 @@ class Hyperplane(nn.Module):
in :math:`n^T x + d = 0`. The value controls where the plane sits
relative to the origin for the stored normal direction.
"""
- return self._d
+ return Scalar(self._d)
def abs_distance(self, p: Vector3) -> Scalar:
"""Compute unsigned distances from points to the hyperplane.
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 55e82f04a..31cb4b8c3 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -21,7 +21,7 @@ import torch
from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
from kornia.core.exceptions import BaseError, ValueCheckError
from kornia.geometry.plane import Hyperplane, fit_plane
-from kornia.geometry.vector import Vector3
+from kornia.geometry.vector import Scalar, Vector3
from testing.base import BaseTester
@@ -142,6 +142,96 @@ class TestHyperplane(BaseTester):
loaded_plane = torch.load(file_path, weights_only=False)
self.assert_close(plane.normal.unwrap(), loaded_plane.normal.unwrap())
+ @pytest.mark.parametrize("integer", [False, True])
+ def test_legacy_serialization(self, device, dtype, tmp_path, integer):
+ # Recreate the pre-registration object layout without calling the current constructor.
+ legacy = Hyperplane.__new__(Hyperplane)
+ torch.nn.Module.__init__(legacy)
+ coefficient_dtype = torch.int64 if integer else torch.float32
+ legacy._n = Vector3(torch.tensor([0, 0, 1], dtype=coefficient_dtype))
+ legacy._d = Scalar(torch.tensor(-2, dtype=coefficient_dtype))
+ legacy.description = "retained attribute"
+ legacy.eval()
+ path = tmp_path / "legacy_plane.pt"
+ torch.save(legacy, path)
+
+ loaded = torch.load(path, weights_only=False)
+ assert isinstance(loaded.normal.data, torch.Tensor)
+ assert isinstance(loaded.offset.data, torch.Tensor)
+ assert set(loaded.state_dict()) == {"_n", "_d"}
+ # Migrated like a freshly built plane: floating coefficients become parameters, integer ones buffers.
+ assert {name for name, _ in loaded.named_parameters()} == (set() if integer else {"_n", "_d"})
+ assert loaded.description == legacy.description
+ assert not loaded.training
+ loaded.to(device=device, dtype=dtype)
+ coefficient_dtype = torch.int64 if integer else dtype
+ assert loaded.normal.data.device == torch.device(device)
+ assert loaded.offset.data.device == torch.device(device)
+ assert loaded.normal.data.dtype == coefficient_dtype
+ assert loaded.offset.data.dtype == coefficient_dtype
+ point = Vector3(torch.tensor([4, 5, 3], device=device, dtype=coefficient_dtype))
+ assert loaded.signed_distance(point).data.item() == 1
+
+ @pytest.mark.parametrize("constructor", ["direct", "from_vector", "through", "fit_plane"])
+ def test_module_state_round_trip(self, device, dtype, tmp_path, constructor):
+ points = torch.tensor([[0.0, 0.0, 2.0], [2.0, 0.0, 2.0], [0.0, 1.0, 2.0]])
+ normal = Vector3(torch.tensor([0.0, 0.0, -1.0]))
+ if constructor == "direct":
+ plane = Hyperplane(normal, Scalar(torch.tensor(2.0)))
+ elif constructor == "from_vector":
+ plane = Hyperplane.from_vector(normal, Vector3(points[0]))
+ elif constructor == "through":
+ plane = Hyperplane.through(*points.unbind())
+ else:
+ plane = fit_plane(points)
+
+ source = torch.nn.Module()
+ source.plane = plane
+ source.to(device=device, dtype=dtype)
+ assert source.plane.normal.data.device == torch.device(device)
+ assert source.plane.normal.data.dtype == dtype
+ assert source.plane.offset.data.device == torch.device(device)
+ assert source.plane.offset.data.dtype == dtype
+
+ target = torch.nn.Module()
+ target.plane = Hyperplane(
+ Vector3(torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)),
+ Scalar(torch.tensor(-1.0, device=device, dtype=dtype)),
+ )
+ path = tmp_path / "plane_state.pt"
+ torch.save(source.state_dict(), path)
+ target.load_state_dict(torch.load(path, weights_only=True))
+ probe = Vector3(torch.tensor([[1.0, 3.0, 5.0], [2.0, 4.0, 6.0]], device=device, dtype=dtype))
+ self.assert_close(target.plane.signed_distance(probe).data, source.plane.signed_distance(probe).data)
+ self.assert_close(target.plane.projection(probe).data, source.plane.projection(probe).data)
+
+ @pytest.mark.parametrize("derived", [False, True])
+ def test_module_state_preserves_gradients(self, device, dtype, derived):
+ n = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype, requires_grad=True)
+ d = torch.tensor(2.0, device=device, dtype=dtype, requires_grad=True)
+ plane = Hyperplane(Vector3(n * 2 if derived else n), Scalar(d * 2 if derived else d))
+ point = Vector3(torch.tensor([1.0, 3.0, 5.0], device=device, dtype=dtype))
+ plane.signed_distance(point).data.backward()
+ scale = 2 if derived else 1
+ self.assert_close(n.grad, point.data * scale)
+ self.assert_close(d.grad, torch.ones_like(d) * scale)
+
+ def test_module_state_keeps_parameters(self, device, dtype):
+ normal = torch.nn.Parameter(torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype))
+ offset = torch.nn.Parameter(torch.tensor(2.0, device=device, dtype=dtype))
+ plane = Hyperplane(Vector3(normal), Scalar(offset))
+ parameters = dict(plane.named_parameters())
+ assert parameters["_n"] is normal
+ assert parameters["_d"] is offset
+
+ def test_integer_module_state(self, device):
+ plane = Hyperplane(Vector3(torch.tensor([0, 0, 1])), Scalar(torch.tensor(-2))).to(device)
+ restored = Hyperplane(Vector3(torch.tensor([1, 0, 0])), Scalar(torch.tensor(0))).to(device)
+ restored.load_state_dict(plane.state_dict())
+ assert not list(plane.parameters())
+ point = Vector3(torch.tensor([4, 5, 3], device=device))
+ assert restored.signed_distance(point).data.item() == 1
+
@pytest.mark.parametrize("shape", [(2,), (1, 2), (3,), (1, 3)])
def test_through_two_points_raises(self, device, dtype, shape):
# Hyperplane stores a Vector3 normal and has no 2D form: two points must be rejected with a
@@ -522,19 +612,16 @@ class TestConventionsHyperplane(BaseTester):
plane.signed_distance(p).data / torch.linalg.vector_norm(plane.normal.data), torch.zeros_like(one)
)
- def test_wart_hyperplane_state_not_registered_4923(self, device, dtype):
- # Hyperplane keeps its normal and offset as Vector3 / Scalar wrappers outside the module state (#4923), so
- # state_dict() is empty and .to() leaves both in the original dtype. Registering them, as ParametrizedLine
- # does, flips both assertions.
+ def test_convention_hyperplane_state_registered_4923(self, device, dtype):
normal = torch.tensor([2.0, 1.0, -2.0], device=device, dtype=dtype) / 3
e = torch.tensor([1.0, 2.0, 0.5], device=device, dtype=dtype)
plane = Hyperplane.from_vector(Vector3(normal), Vector3(e))
- assert list(plane.state_dict()) == []
+ assert set(plane.state_dict()) == {"_n", "_d"}
other = torch.float16 if dtype == torch.float32 else torch.float32 # float64 is unavailable on MPS
moved = plane.to(other)
- assert moved.normal.data.dtype == dtype
- assert moved.offset.data.dtype == dtype
+ assert moved.normal.data.dtype == other
+ assert moved.offset.data.dtype == other
class TestConventionsFitPlane(BaseTester):