Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(liegroup): keep a user tensor that requires grad instead of re-wrapping it as a Parameter (#4947)

Dmytro Mishkin137d543c9d4e
diff --git a/changelog.d/4947.fixed.md b/changelog.d/4947.fixed.md
new file mode 100644
index 000000000..570b93483
--- /dev/null
+++ b/changelog.d/4947.fixed.md
@@ -0,0 +1 @@
+`So2`, `Se2`, `Se3` and `ParametrizedLine` built from a tensor that requires grad keep that tensor, so the gradient reaches it; they used to wrap it in a new `nn.Parameter` and leave the caller's `.grad` at `None`. Such a tensor is now registered as a buffer: it no longer appears in the module's `.parameters()`, but `state_dict()`, `load_state_dict()` and `.to()` still reach it. A tensor that does not require grad still becomes a parameter. (#4943)
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 4fd55bfa9..0520f2b5e 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -468,17 +468,19 @@ def is_exporting() -> bool:
def register_module_state(module: torch.nn.Module, name: str, x: torch.Tensor) -> None:
"""Store tensor ``x`` on ``module`` as ``name`` so it is optimizable, movable and serializable.
- A leaf tensor (user-provided data or an existing parameter) becomes an ``nn.Parameter``, as
- before. ``nn.Parameter(x)`` would re-root a tensor that already carries a ``grad_fn`` as a new
- leaf, so a group built from ``Se3.exp(v)`` would stop propagating gradients to ``v``; such a
- tensor is registered as a buffer instead, which keeps its history while ``.to()``,
+ An existing ``nn.Parameter`` is kept, and a tensor that takes no part in autograd (no
+ ``grad_fn`` and ``requires_grad=False``) becomes an ``nn.Parameter``, so the module is
+ optimizable. ``nn.Parameter(x)`` would re-root any other tensor as a new leaf: a group built
+ from ``Se3.exp(v)`` would stop propagating gradients to ``v``, and a group built from the
+ caller's own leaf that requires grad would take its gradient away from that leaf. Such a
+ tensor is registered as a buffer instead, which keeps it and its history while ``.to()``,
``state_dict()`` and ``load_state_dict()`` still reach it under the same key. Under graph
capture (``torch.jit.trace``, ``torch.compile``, ``torch.export`` and the dynamo ONNX
exporter) neither a parameter nor a buffer can be created inside the traced region, so the
tensor is kept as a plain attribute of the module being built.
"""
if isinstance(x, torch.nn.Parameter) or not (torch.jit.is_tracing() or is_compiling() or is_exporting()):
- if x.grad_fn is None or isinstance(x, torch.nn.Parameter):
+ if isinstance(x, torch.nn.Parameter) or (x.grad_fn is None and not x.requires_grad):
x = x if isinstance(x, torch.nn.Parameter) else torch.nn.Parameter(x)
else:
module.register_buffer(name, x)
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index 3c55f3c86..b4de15bea 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -298,6 +298,17 @@ class TestSe2(BaseTester):
self.assert_close(x.inverse().adjoint(), x.adjoint().inverse())
self.assert_close((x * y).adjoint(), x.adjoint() @ y.adjoint())
+ def test_user_leaf_translation_receives_the_gradient(self, device, dtype):
+ # A tensor that requires grad is kept, not re-wrapped as a new Parameter, so the gradient reaches it (#4943).
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ t = torch.tensor([[1.0, 2.0]], device=device, dtype=dtype, requires_grad=True)
+ s = Se2(So2.identity(1, device, dtype), t)
+ (s * torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)).sum().backward()
+ assert t.grad is not None
+ self.assert_close(t.grad, torch.ones_like(t))
+ assert "_translation" in s.state_dict()
+
def test_derived_state_moves_and_serializes(self, device, dtype):
# A group built from a tensor with autograd history keeps that history; its state must
# still be registered so ``state_dict`` and ``.to()`` / ``.double()`` reach it.
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index 2b96291ed..112bd3d7e 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -358,6 +358,18 @@ class TestSe3(BaseTester):
self.assert_close(s_in_s.so3.q.data, i.so3.q.data)
self.assert_close(s_in_s.t, i.t)
+ def test_user_leaf_translation_receives_the_gradient(self, device, dtype):
+ # A tensor that requires grad is kept, not re-wrapped as a new Parameter, so the gradient reaches it (#4943).
+ t = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype, requires_grad=True)
+ s = Se3(So3.identity(1, device, dtype), t)
+ (s * torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)).sum().backward()
+ assert t.grad is not None
+ self.assert_close(t.grad, torch.ones_like(t))
+ assert "_translation" in s.state_dict()
+ # a tensor that does not require grad still becomes an optimizable parameter
+ plain = Se3(So3.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype))
+ assert [name for name, _ in plain.named_parameters()] == ["_translation"]
+
def test_derived_state_moves_and_serializes(self, device, dtype):
v = torch.rand(2, 6, device=device, dtype=dtype, requires_grad=True)
s = Se3.exp(v)
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index c3546b18b..c03eb6ca3 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -240,6 +240,18 @@ class TestSo2(BaseTester):
s = So2.identity(batch_size, device=device, dtype=dtype)
self.assert_close(s.matrix(), s.adjoint())
+ def test_user_leaf_receives_the_gradient(self, device, dtype):
+ # A complex leaf that requires grad is kept, not re-wrapped as a new Parameter, so the gradient reaches it
+ # (#4943). d/dz of sum(R @ (1, 0)) = d(re + im)/dz.
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ re = torch.tensor([0.6], device=device, dtype=dtype)
+ z = torch.complex(re, re + 0.2).requires_grad_(True)
+ s = So2(z)
+ (s * torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)).sum().backward()
+ assert z.grad is not None
+ assert "_z" in s.state_dict()
+
def test_derived_state_moves_and_serializes(self, device, dtype):
theta = torch.rand(2, device=device, dtype=dtype, requires_grad=True)
s = So2.exp(theta)
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index e2d84e20c..521230b90 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -163,6 +163,22 @@ class TestParametrizedLine(BaseTester):
moved.direction.sum().backward()
assert p1.grad is not None
+ def test_user_leaf_receives_the_gradient(self, device, dtype):
+ # A tensor that requires grad is kept, not re-wrapped as a new Parameter, so the gradient reaches it (#4943).
+ origin = torch.tensor([0.5, 1.0], device=device, dtype=dtype, requires_grad=True)
+ direction = torch.tensor([0.6, 0.8], device=device, dtype=dtype, requires_grad=True)
+ line = ParametrizedLine(origin, direction)
+ assert line.origin is origin and line.direction is direction
+ assert [name for name, _ in line.named_buffers()] == ["_origin", "_direction"]
+ assert list(line.state_dict()) == ["_origin", "_direction"]
+ line.point_at(2.0).sum().backward()
+ assert origin.grad is not None and direction.grad is not None
+ self.assert_close(origin.grad, torch.ones_like(origin))
+ self.assert_close(direction.grad, torch.full_like(direction, 2.0))
+ # a tensor that does not require grad still becomes an optimizable parameter
+ plain = ParametrizedLine(origin.detach().clone(), direction.detach().clone())
+ assert [name for name, _ in plain.named_parameters()] == ["_origin", "_direction"]
+
class TestFitLine(BaseTester):
@pytest.mark.parametrize("B", (1, 2))