π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): register plain Quaternion tensors as buffers (#5446)
RiverYufd36a2ffa003
diff --git a/changelog.d/5446.breaking.md b/changelog.d/5446.breaking.mdnew file mode 100644index 000000000..8ae4290ef--- /dev/null+++ b/changelog.d/5446.breaking.md@@ -0,0 +1,7 @@+`Quaternion` now registers plain tensor data as a persistent buffer, preserving autograd history+and explicitly supplied `nn.Parameter` inputs at construction. Previously, plain tensor rotations+were omitted from module state; `Quaternion`, `So3` and `Se3` now save and restore them+and follow enclosing module device/dtype conversions. This adds `_data`, `_q._data`+and `_rotation._q._data` checkpoint keys, respectively. Older checkpoints missing these+keys now fail with `strict=True`; `strict=False` reports the missing keys and retains+the target's initialized rotation, which must be supplied separately if needed.diff --git a/docs/source/geometry.quaternion.rst b/docs/source/geometry.quaternion.rstindex c9cd281b7..309e7c956 100644--- a/docs/source/geometry.quaternion.rst+++ b/docs/source/geometry.quaternion.rst@@ -6,6 +6,14 @@ kornia.geometry.quaternion.. currentmodule:: kornia.geometry.quaternion+Module state+------------++Quaternion data given as a plain tensor is a persistent buffer under ``_data``; an ``nn.Parameter`` stays a+parameter under the same key. ``So3`` saves its rotation as ``_q._data`` and ``Se3`` as ``_rotation._q._data``,+prefixed by the enclosing module's attribute names when nested. ``load_state_dict(strict=True)`` raises on a state+dict that lacks these keys; with ``strict=False`` they are reported as missing and the target keeps its own rotation.+.. autoclass:: Quaternion:members::special-members:diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.pyindex f3ea6103f..14b024c64 100644--- a/kornia/geometry/liegroup/se3.py+++ b/kornia/geometry/liegroup/se3.py@@ -53,9 +53,9 @@ class Se3(nn.Module):``from_matrix`` ignores the bottom row.- ``t`` is always a tensor registered as module state, whichever constructor built the pose; a ``Vector3``passed to the constructor is unwrapped. ``g * p`` returns a ``Vector3`` only when ``p`` is one.- - Known defect: ``state_dict`` and ``.to()`` skip the rotation unless its quaternion is an ``nn.Parameter``, so- ``load_state_dict`` can restore one pose's translation next to another pose's rotation- (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ - ``state_dict()``, ``load_state_dict()`` and module device/dtype conversions include both the rotation+ and translation. Rotation state follows :class:`~kornia.geometry.quaternion.Quaternion`'s+ buffer/parameter convention.Example:>>> q = Quaternion.identity()diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.pyindex e4d04a736..7b9b6cc0f 100644--- a/kornia/geometry/liegroup/so3.py+++ b/kornia/geometry/liegroup/so3.py@@ -97,12 +97,12 @@ class So3(nn.Module):- ``from_matrix`` does not check its input by default: a reflection (det :math:`-1`) is accepted withouterror and returns an ``So3`` whose ``matrix()`` is not the input. ``check_rotation=True`` raises``ValueError`` instead.- - Known defects: the quaternion is stored as given, so with a non-unit ``q`` the ``matrix()`` is not a+ - The quaternion is registered as module state following+ :class:`~kornia.geometry.quaternion.Quaternion`'s buffer/parameter convention, including rotations+ produced by ``exp``, ``identity``, ``random``, ``from_matrix`` and group operations.+ - Known defect: the quaternion is stored as given, so with a non-unit ``q`` the ``matrix()`` is not arotation and ``s * p`` scales ``p`` by :math:`|q|^2`- (`#4942 <https://github.com/kornia/kornia/issues/4942>`_); ``exp``, ``identity``, ``random``,- ``from_matrix`` and every operation store the quaternion as a plain tensor, which has no ``state_dict()``- entry and which ``.to()`` leaves unchanged; only a quaternion built on an ``nn.Parameter`` is saved and moved- (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).Example:>>> q = Quaternion.identity()diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 586ca80d6..029dfc35f 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -69,14 +69,16 @@ class Quaternion(nn.Module):``to_axis_angle()``, ``polar_angle`` and ``slerp`` read only the direction of ``q``: rescaling ``q`` by apositive factor changes their result by roundoff only, as long as its squared components stay within therange of the dtype and its norm stays above ``1e-12``.+ - At construction, plain tensor data is registered as a persistent buffer; an explicit ``nn.Parameter``+ remains a parameter. Both are saved and restored by ``state_dict()`` and ``load_state_dict()`` and follow+ an enclosing module's device and dtype conversions. Construction preserves the input tensor and its+ autograd history. ``Quaternion.to()`` returns a new quaternion; enclosing module conversions update the+ existing module's state.- Known defects: ``to_euler()`` returns a triple that does not reproduce the rotation for a non-unit ``q``(`#3953 <https://github.com/kornia/kornia/issues/3953>`_) and for most rotations at a pitch of:math:`\pm\pi/2` (`#3950 <https://github.com/kornia/kornia/issues/3950>`_); below a norm of ``1e-12``,``matrix()`` and ``slerp`` give wrong results, and the zero quaternion's ``matrix()`` is the identity- (`#3952 <https://github.com/kornia/kornia/issues/3952>`_); data given as a plain tensor is not- registered with ``nn.Module``, so an enclosing module's ``state_dict()``, ``load_state_dict()`` and- ``.to()`` skip it, while an ``nn.Parameter`` is saved, restored and moved- (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ (`#3952 <https://github.com/kornia/kornia/issues/3952>`_).Example:>>> q = Quaternion.identity(batch_size=4)@@ -102,6 +104,7 @@ class Quaternion(nn.Module):Args:data: torch.Tensor or parameter containing the quaternion data with the shape of :math:`(*, 4)`.+ Stored without copying as a persistent buffer, or as a parameter if already an ``nn.Parameter``.Example:>>> # Create with torch.tensor(no gradients tracked by default)@@ -120,7 +123,10 @@ class Quaternion(nn.Module):if data.ndim == 0 or data.shape[-1] != 4:raise ValueError(f"Quaternion input must have last dimension == 4. Got shape {tuple(data.shape)}")- self._data = data+ if isinstance(data, nn.Parameter):+ self._data = data+ else:+ self.register_buffer("_data", data)def to(self, *args: Any, **kwargs: Any) -> "Quaternion":"""Move and/or cast the quaternion data.diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.pyindex 112cef5f5..0e0c2bf87 100644--- a/tests/geometry/liegroup/test_se3.py+++ b/tests/geometry/liegroup/test_se3.py@@ -434,12 +434,15 @@ class TestSe3(BaseTester):assert s.t.grad_fn is not Noneassert "_translation" in s.state_dict()restored = Se3(So3.identity(2, device, dtype), torch.zeros(2, 3, device=device, dtype=dtype))- assert list(restored.state_dict()) == list(s.state_dict()) == ["_translation"]+ assert list(restored.state_dict()) == list(s.state_dict()) == ["_translation", "_rotation._q._data"]restored.load_state_dict(s.state_dict())self.assert_close(restored.t, s.t.detach())+ self.assert_close(restored.quaternion.data, s.quaternion.data.detach())+ self.assert_close(restored.matrix(), s.matrix().detach())other = torch.float16 if dtype == torch.float32 else torch.float32 # float64 is unavailable on MPSmoved = s.to(other)assert moved.t.dtype == other and moved.t.grad_fn is not None+ assert moved.quaternion.data.dtype == other and moved.quaternion.data.grad_fn is not Nonemoved.t.sum().backward()assert v.grad is not None@@ -558,20 +561,47 @@ class TestSe3(BaseTester):assert isinstance(identity * Vector3(p), Vector3)self.assert_close((identity * Vector3(p)).data, p)- def test_wart_se3_load_state_dict_restores_translation_not_rotation_4923(self, device, dtype):+ def test_se3_state_dict_restores_translation_and_rotation_4923(self, device, dtype):src = Se3.exp(torch.tensor([[1.0, -2.0, 3.0, 0.4, 0.2, -0.3]], device=device, dtype=dtype))dst = Se3(Quaternion.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype))eye = torch.eye(3, device=device, dtype=dtype)[None]assert (src.r.matrix() - eye).abs().max() > 0.1 # the source rotation is not the identity- # https://github.com/kornia/kornia/issues/4923: the quaternion is not registered, so the state dict holds- # only the translation; loading reports every key matched, restores the translation and keeps the old- # rotation.- assert list(src.state_dict()) == ["_translation"]- assert list(Se3.identity(1, device, dtype).state_dict()) == ["_translation"] # the identity saves t alone too+ # #4923: loading must restore the entire pose, including a plain tensor rotation.+ assert list(src.state_dict()) == ["_translation", "_rotation._q._data"]+ assert list(Se3.identity(1, device, dtype).state_dict()) == list(src.state_dict())result = dst.load_state_dict(src.state_dict())assert not result.missing_keys and not result.unexpected_keysself.assert_close(dst.t, src.t.detach())- self.assert_close(dst.r.matrix(), eye)+ self.assert_close(dst.quaternion.data, src.quaternion.data)+ self.assert_close(dst.r.matrix(), src.r.matrix())+ self.assert_close(dst.matrix(), src.matrix())+ point = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)+ self.assert_close(dst * point, src * point)+ assert list(dict(dst.named_parameters())) == ["_translation"]+ assert list(dict(dst.named_buffers())) == ["_rotation._q._data"]++ def test_parent_casts_rotation_and_translation_4923(self, device, dtype):+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ pose = Se3(Quaternion.identity(1, device, dtype), torch.ones(1, 3, device=device, dtype=dtype))+ parent = torch.nn.ModuleDict({"pose": pose})+ for method, expected_dtype in (("double", torch.float64), ("float", torch.float32)):+ assert getattr(parent, method)() is parent+ assert pose.quaternion.data.dtype == expected_dtype+ assert pose.t.dtype == expected_dtype+ point = torch.zeros(1, 3, device=device, dtype=expected_dtype)+ self.assert_close(pose * point, torch.ones_like(point))++ def test_old_checkpoint_missing_rotation_4923(self, device, dtype):+ pose = Se3.identity(1, device, dtype)+ old_state = {"_translation": torch.ones(1, 3, device=device, dtype=dtype)}+ with pytest.raises(RuntimeError, match=r'Missing key.*"_rotation\._q\._data"'):+ pose.load_state_dict(old_state, strict=True)+ result = pose.load_state_dict(old_state, strict=False)+ assert result.missing_keys == ["_rotation._q._data"]+ assert result.unexpected_keys == []+ self.assert_close(pose.t, old_state["_translation"])+ self.assert_close(pose.quaternion.data, torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype))def test_random_translation_is_uniform_in_the_unit_interval(self, device, dtype):# random draws its translation with torch.rand, which the Vector3 it used to build drew as well (#4931).diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.pyindex 74f8c3f57..9df4093d2 100644--- a/tests/geometry/liegroup/test_so3.py+++ b/tests/geometry/liegroup/test_so3.py@@ -667,22 +667,38 @@ class TestSo3Conventions(BaseTester):assert bool(torch.isfinite(s.log()).all())assert bool(((s.matrix() - flip).abs() > 0.5).any())- def test_wart_rotation_state_not_registered_4923(self, device, dtype):- # #4923 https://github.com/kornia/kornia/issues/4923: a Quaternion built from a plain tensor keeps it as an- # unregistered attribute, so a module holding it (directly or through So3) saves no key for the rotation,- # and load_state_dict reports success while keeping the old rotation. This test turns red when the- # rotation is registered.- saved = torch.tensor([[0.8, 0.2, -0.4, 0.4]], device=device, dtype=dtype)- stale = torch.tensor([[0.0, 0.6, 0.0, 0.8]], device=device, dtype=dtype)- source, target = _RotationHolder(saved, as_parameter=False), _RotationHolder(stale, as_parameter=False)- assert list(source.state_dict()) == []- result = target.load_state_dict(source.state_dict())- assert not result.missing_keys and not result.unexpected_keys- self.assert_close(target.quat.data, stale)- self.assert_close(target.rot.q.data, stale)- # control: a rotation stored as an nn.Parameter is saved and restored- source, target = _RotationHolder(saved, as_parameter=True), _RotationHolder(stale, as_parameter=True)+ @pytest.mark.parametrize("as_parameter", [False, True])+ def test_rotation_state_round_trip_4923(self, device, dtype, as_parameter):+ # #4923: plain tensor rotations must be restored just like explicit Parameters.+ saved = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device, dtype=dtype)+ stale = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)+ source, target = _RotationHolder(saved, as_parameter), _RotationHolder(stale, as_parameter)assert list(source.state_dict()) == ["quat._data", "rot._q._data"]target.load_state_dict(source.state_dict())self.assert_close(target.quat.data, saved)self.assert_close(target.rot.q.data, saved)+ self.assert_close(target.rot.matrix(), source.rot.matrix())+ point = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)+ self.assert_close(target.rot * point, torch.tensor([[-1.0, -2.0, 3.0]], device=device, dtype=dtype))++ @pytest.mark.parametrize("as_parameter", [False, True])+ def test_parent_casts_rotation_state_4923(self, device, dtype, as_parameter):+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ data = torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype)+ parent = _RotationHolder(data, as_parameter)+ for method, expected_dtype in (("double", torch.float64), ("float", torch.float32)):+ assert getattr(parent, method)() is parent+ assert parent.quat.data.dtype == expected_dtype+ assert parent.rot.q.data.dtype == expected_dtype+ self.assert_close(parent.quat.data, data.to(expected_dtype))+ self.assert_close(parent.rot.q.data, data.to(expected_dtype))++ def test_old_checkpoint_missing_rotation_4923(self, device, dtype):+ rotation = So3.identity(1, device, dtype)+ with pytest.raises(RuntimeError, match=r'Missing key.*"_q\._data"'):+ rotation.load_state_dict({}, strict=True)+ result = rotation.load_state_dict({}, strict=False)+ assert result.missing_keys == ["_q._data"]+ assert result.unexpected_keys == []+ self.assert_close(rotation.q.data, torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype))diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex f2087042d..45a0c6bc9 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -24,7 +24,7 @@ from torch.nn import Parameterfrom kornia.geometry.quaternion import Quaternion, average_quaternions-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availableclass TestQuaternion(BaseTester):@@ -564,6 +564,96 @@ def _align_sign(q: torch.Tensor, ref: torch.Tensor) -> torch.Tensor:return q+class TestQuaternionState(BaseTester):+ @pytest.mark.parametrize("requires_grad", [False, True])+ def test_plain_tensor_is_persistent_buffer(self, device, dtype, requires_grad):+ data = torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype, requires_grad=requires_grad)+ q = Quaternion(data)+ assert q.data is data+ assert q.data.requires_grad == requires_grad+ assert not isinstance(q.data, Parameter)+ assert list(q.named_parameters()) == []+ assert dict(q.named_buffers())["_data"] is data+ assert q.state_dict(keep_vars=True)["_data"] is data++ @pytest.mark.parametrize("requires_grad", [False, True])+ def test_explicit_parameter_keeps_identity(self, device, dtype, requires_grad):+ data = Parameter(torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype), requires_grad)+ q = Quaternion(data)+ assert q.data is data+ assert q.data.requires_grad == requires_grad+ assert dict(q.named_parameters())["_data"] is data+ assert list(q.named_buffers()) == []+ assert q.state_dict(keep_vars=True)["_data"] is data++ def test_parameter_optimizer_updates_callers_tensor(self, device, dtype):+ data = Parameter(torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype))+ q = Quaternion(data)+ optimizer = torch.optim.SGD(q.parameters(), lr=0.25)+ q.norm().sum().backward()+ self.assert_close(data.grad, torch.full_like(data, 0.5))+ optimizer.step()+ assert q.data is data+ self.assert_close(data, torch.full_like(data, 0.375))++ @pytest.mark.parametrize("non_leaf", [False, True])+ def test_tensor_keeps_autograd_connection(self, device, dtype, non_leaf):+ leaf = torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype, requires_grad=True)+ data = -leaf if non_leaf else leaf # Both signs represent the same unit rotation.+ q = Quaternion(data)+ assert q.data is data+ assert q.data.is_leaf == (not non_leaf)+ assert q.data.grad_fn is data.grad_fn+ assert not isinstance(q.data, Parameter)+ q.norm().sum().backward()+ self.assert_close(leaf.grad, leaf.detach())++ @pytest.mark.parametrize("as_parameter", [False, True])+ def test_state_dict_round_trip(self, device, dtype, as_parameter):+ saved = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device, dtype=dtype)+ stale = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)+ source = Quaternion(Parameter(saved) if as_parameter else saved)+ target = Quaternion(Parameter(stale.clone()) if as_parameter else stale.clone())+ target_data = target.data+ target.load_state_dict(source.state_dict())+ assert target.data is target_data+ self.assert_close(target.data, saved)+ self.assert_close(target.matrix(), source.matrix())+ expected = torch.diag(torch.tensor([-1.0, -1.0, 1.0], device=device, dtype=dtype))[None]+ self.assert_close(target.matrix(), expected)++ @pytest.mark.parametrize("as_parameter", [False, True])+ def test_to_returns_new_quaternion(self, device, dtype, as_parameter):+ data = torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype)+ q = Quaternion(Parameter(data) if as_parameter else data)+ same_dtype = q.to(dtype=dtype)+ assert same_dtype is not q+ assert same_dtype.data is q.data+ other = torch.float16 if dtype == torch.float32 else torch.float32+ converted = q.to(dtype=other)+ assert converted is not q+ assert converted.data.dtype == other+ assert q.data.dtype == dtype+ self.assert_close(converted.data, data.to(other))++ def test_old_checkpoint_missing_rotation_4923(self, device, dtype):+ q = Quaternion.identity(1, device, dtype)+ with pytest.raises(RuntimeError, match=r'Missing key.*"_data"'):+ q.load_state_dict({}, strict=True)+ result = q.load_state_dict({}, strict=False)+ assert result.missing_keys == ["_data"]+ assert result.unexpected_keys == []+ self.assert_close(q.data, torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype))++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_dynamo(self, device, dtype, torch_optimizer):+ def matrix(data):+ return Quaternion(data).matrix()++ data = torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype)+ self.assert_close(torch_optimizer(matrix, fullgraph=True)(data), matrix(data))++class TestQuaternionAverage(BaseTester):@pytest.mark.parametrize("M", [1, 2, 5, 10])def test_average_identity(self, device, dtype, M):