Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): squeeze a (B, 1) z or angle to (B,) in So2 so it rotates (B, 2) points pairwise, not into (B, B, 2) (#5005)

εŒΊζ’“η99a65c5e74d8
diff --git a/changelog.d/5005.breaking.md b/changelog.d/5005.breaking.md
new file mode 100644
index 000000000..ff4029cc2
--- /dev/null
+++ b/changelog.d/5005.breaking.md
@@ -0,0 +1,7 @@
+`So2` reads a `(B, 1)` complex number or angle as `(B,)`: an element built by `So2(z)` or `So2.exp(theta)` from a column
+now has `z` and `log()` of shape `(B,)` and `matrix()` of shape `(B, 2, 2)`, `So2.hat(theta)` returns `(B, 2, 2)`, and
+`So2 * points` rotates `(B, 2)` points pairwise into `(B, 2)`. They used to keep the column, so `z` and `log()` were
+`(B, 1)`, `matrix()` and `hat()` were `(B, 1, 2, 2)` (which `vee()` rejects), `So2 * points` broadcast into `(B, B, 2)`
+with every rotation applied to every point, and `Se2` rejected the element. The given tensor is still what the module
+registers, so a `(B, 1)` `nn.Parameter` stays its parameter and `state_dict()` keeps the `(B, 1)` shape. `(B,)` and `()`
+inputs are unchanged. Fixes #4932.
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 67f21a6c5..767ba8f27 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -38,21 +38,18 @@ class So2(nn.Module):
See more: https://en.wikipedia.org/wiki/Orthogonal_group#Special_orthogonal_group
Convention:
- - Stores the rotation as a complex number ``z`` of shape :math:`()`, :math:`(B,)`, or :math:`(B, 1)`.
- For unit :math:`z = \cos\theta + i \sin\theta`, ``matrix()`` is
- :math:`[[\cos\theta, -\sin\theta], [\sin\theta, \cos\theta]]`. Non-unit ``z = a + i b`` is accepted
- and produces :math:`[[a, -b], [b, a]]`, which rotates and scales by :math:`|z|`. The complex storage rules
- out bfloat16.
+ - Represents the rotation as a complex number ``z`` of shape :math:`()` or :math:`(B,)`; a :math:`(B, 1)`
+ ``z`` or angle is accepted and read as :math:`(B,)`. For unit :math:`z = \cos\theta + i \sin\theta`,
+ ``matrix()`` is :math:`[[\cos\theta, -\sin\theta], [\sin\theta, \cos\theta]]`. Non-unit ``z = a + i b``
+ is accepted and produces :math:`[[a, -b], [b, a]]`, which rotates and scales by :math:`|z|`. The complex
+ storage rules out bfloat16.
- A positive angle rotates the x axis toward the y axis: counter-clockwise in a y-up frame, clockwise as
displayed on y-down image axes. For a unit rotation, ``matrix()`` is the transpose of
:func:`~kornia.geometry.conversions.angle_to_rotation_matrix`, which takes degrees.
``log`` returns the angle in :math:`[-\pi, \pi]`, and ``adjoint()`` is the 2x2 identity.
- Known defects: ``hat`` returns the symmetric :math:`[[0, \theta], [\theta, 0]]` instead of the generator
:math:`[[0, -\theta], [\theta, 0]]`, and ``vee`` reads its ``[0, 1]`` entry
- (`#4929 <https://github.com/kornia/kornia/issues/4929>`_); an accepted :math:`(B, 1)` ``z`` or angle
- yields :math:`(B, 1, 2, 2)` from ``matrix()`` or ``hat()``, which ``vee()`` rejects, and times
- :math:`(B, 2)` points returns :math:`(B, B, 2)`, every rotation applied to every point
- (`#4932 <https://github.com/kornia/kornia/issues/4932>`_); ``.to()`` a real dtype keeps the real part of
+ (`#4929 <https://github.com/kornia/kornia/issues/4929>`_); ``.to()`` a real dtype keeps the real part of
``z``, drops its imaginary part and makes ``matrix()`` raise
(`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
@@ -71,7 +68,7 @@ class So2(nn.Module):
Internally represented by torch.complex number `z`.
Args:
- z: Complex number with the shape of :math:`(B,)`, :math:`(B, 1)`, or :math:`()`.
+ z: Complex number with the shape of :math:`(B,)` or :math:`()`; :math:`(B, 1)` is read as :math:`(B,)`.
Example:
>>> real = torch.tensor(0.6)
@@ -90,13 +87,16 @@ class So2(nn.Module):
if not (is_scalar or is_flat or is_column):
raise ValueError(f"Invalid input size, we expect [], [B], or [B, 1]. Got: {z.shape}")
+ # A (B, 1) z is stored as given, so a caller's nn.Parameter stays the module's own parameter, and the ``z``
+ # property reads it as (B,): kept as a column, it broadcast against the (B,) coordinates of __mul__ as an
+ # outer product (#4932).
register_module_state(self, "_z", z)
def __repr__(self) -> str:
return f"{self.z}"
def __getitem__(self, idx: int | slice) -> So2:
- return So2(self._z[idx])
+ return So2(self.z[idx])
@overload
def __mul__(self, right: So2) -> So2: ...
@@ -138,15 +138,19 @@ class So2(nn.Module):
@property
def z(self) -> torch.Tensor:
- """Return the underlying complex number, with the shape it was constructed with."""
- return self._z
+ """Return the underlying complex number of shape :math:`()` or :math:`(B,)`.
+
+ A :math:`(B, 1)` ``z`` given to the constructor stays stored, and registered, as it was given, and is read
+ here as a :math:`(B,)` view.
+ """
+ return self._z.squeeze(-1) if self._z.dim() == 2 else self._z
@staticmethod
def exp(theta: torch.Tensor) -> So2:
"""Convert elements of lie algebra to elements of lie group.
Args:
- theta: angle in radians of shape :math:`(B,)`, :math:`(B, 1)`, or :math:`()`.
+ theta: angle in radians of shape :math:`(B,)` or :math:`()`; :math:`(B, 1)` is squeezed to :math:`(B,)`.
Example:
>>> v = torch.tensor([3.1415/2])
@@ -178,14 +182,14 @@ class So2(nn.Module):
@staticmethod
def hat(theta: torch.Tensor) -> torch.Tensor:
- """Convert an angle to the matrix that :meth:`vee` inverts for scalar or :math:`(B,)` input.
+ """Convert an angle to the matrix that :meth:`vee` inverts.
- The output has shape ``theta.shape + (2, 2)``; see the class convention for :math:`(B, 1)`.
+ The output has shape :math:`(2, 2)` or :math:`(B, 2, 2)`; a :math:`(B, 1)` angle is squeezed to :math:`(B,)`.
The matrix is not the so(2) generator (`#4929 <https://github.com/kornia/kornia/issues/4929>`_).
Args:
- theta: angle in radians of shape :math:`(B,)`, :math:`(B, 1)`, or :math:`()`.
+ theta: angle in radians of shape :math:`(B,)` or :math:`()`; :math:`(B, 1)` is squeezed to :math:`(B,)`.
Example:
>>> theta = torch.tensor(3.1415/2)
@@ -200,6 +204,8 @@ class So2(nn.Module):
is_column = KORNIA_CHECK_SHAPE(theta, ["B", "1"], raises=False)
if not (is_scalar or is_flat or is_column):
raise ValueError(f"Invalid input size, we expect [], [B], or [B, 1]. Got: {theta.shape}")
+ if is_column:
+ theta = theta.squeeze(-1) # (B, 1) would give (B, 1, 2, 2), which vee() rejects (#4932)
z = torch.zeros_like(theta)
row0 = torch.stack((z, theta), -1)
row1 = torch.stack((theta, z), -1)
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index 5471e6bcf..2608344b8 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -22,7 +22,7 @@ import pytest
import torch
from kornia.geometry.conversions import angle_to_rotation_matrix
-from kornia.geometry.liegroup import So2
+from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.vector import Vector2
from testing.base import BaseTester
@@ -39,7 +39,8 @@ class TestSo2(BaseTester):
z = torch.randn(2, 1, dtype=cdtype, device=device)
s = So2(z)
assert isinstance(s, So2)
- self.assert_close(s.z.data, z.data)
+ assert s.z.shape == (2,) # a (B, 1) z is read as (B,) (#4932)
+ self.assert_close(s.z.data, z.data[:, 0])
@pytest.mark.parametrize("input_shape", [(1,), (2,), (5,), ()])
@pytest.mark.parametrize("cdtype", (torch.cfloat, torch.cdouble))
@@ -114,7 +115,7 @@ class TestSo2(BaseTester):
assert isinstance(s2, So2)
self.assert_close(s1.z, s2.z)
self.assert_close(So2(z1).z, z1)
- self.assert_close(So2(z2).z, z2)
+ self.assert_close(So2(z2).z, z2.flatten()) # (B, 1) is squeezed to (B,); (1,) for batch_size None stays
self.assert_close(So2(z3).z, z3)
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
@@ -164,8 +165,8 @@ class TestSo2(BaseTester):
def test_exp(self, device, dtype, batch_size):
theta = self._make_rand_data(device, dtype, (batch_size, 1))
s = So2.exp(theta)
- self.assert_close(s.z.real, theta.cos())
- self.assert_close(s.z.imag, theta.sin())
+ self.assert_close(s.z.real, theta.flatten().cos())
+ self.assert_close(s.z.imag, theta.flatten().sin())
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
@pytest.mark.parametrize("cdtype", (torch.cfloat, torch.cdouble))
@@ -177,7 +178,7 @@ class TestSo2(BaseTester):
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp_log(self, device, dtype, batch_size):
theta = self._make_rand_data(device, dtype, (batch_size, 1))
- self.assert_close(So2.exp(theta).log(), theta)
+ self.assert_close(So2.exp(theta).log(), theta.flatten())
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_wart_so2_hat_and_vee_layout_4929(self, device, dtype, batch_size):
@@ -326,26 +327,54 @@ class TestSo2(BaseTester):
rotation = So2.exp(torch.tensor(0.3, device=device, dtype=dtype)).matrix().detach()
self.assert_close(So2.from_matrix(rotation).log(), torch.tensor(0.3, device=device, dtype=dtype))
- def test_wart_so2_column_angle_outer_broadcasts_4932(self, device, dtype):
+ def test_so2_column_angle_is_squeezed_4932(self, device, dtype):
if dtype == torch.bfloat16:
pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
theta = torch.tensor([0.3, 0.5, 0.7], device=device, dtype=dtype)
p = torch.tensor([[1.0, 0.0], [0.0, 1.0], [2.0, 3.0]], device=device, dtype=dtype)
paired = So2.exp(theta) * p # the (B,) layout rotates point i by angle i
assert paired.shape == (3, 2)
- # https://github.com/kornia/kornia/issues/4932: the accepted (B, 1) layout keeps its singleton axis in
- # matrix() and hat(), but vee() rejects the latter. Multiplication broadcasts z against (B,) coordinates,
- # so entry [i, j] is R(theta_i) p_j: every rotation applied to every point.
+ # https://github.com/kornia/kornia/issues/4932 (fixed): a (B, 1) z or angle used to keep its singleton axis, so
+ # matrix() and hat() returned (B, 1, 2, 2), vee() rejected the latter and `*` broadcast z against the (B,)
+ # point coordinates into (B, B, 2), every rotation applied to every point. It is read as (B,).
column = theta[:, None]
- assert So2.exp(column).matrix().shape == (3, 1, 2, 2)
+ col = So2.exp(column)
+ assert col.z.shape == (3,)
+ self.assert_close(col.z, So2.exp(theta).z)
+ assert So2(col.z[:, None]).z.shape == (3,)
+ assert col.matrix().shape == (3, 2, 2)
column_hat = So2.hat(column)
- assert column_hat.shape == (3, 1, 2, 2)
- with pytest.raises(ValueError):
- So2.vee(column_hat)
- out = So2.exp(column) * p
- assert out.shape == (3, 3, 2)
- self.assert_close(out.diagonal(dim1=0, dim2=1).mT, paired)
- self.assert_close(out[0, 2], So2.exp(theta[0]) * p[2])
+ assert column_hat.shape == (3, 2, 2)
+ self.assert_close(So2.vee(column_hat), theta)
+ out = col * p
+ assert out.shape == (3, 2)
+ self.assert_close(out, paired)
+ moved = Se2(col, torch.zeros(3, 2, device=device, dtype=dtype)) * p # used to raise on the (3, 1) z
+ self.assert_close(moved, paired)
+ # (1, 1) becomes (1,), while (1,) and () are unchanged
+ assert So2.exp(theta[:1, None]).z.shape == (1,)
+ assert So2.exp(theta[:1]).z.shape == (1,) and So2.exp(theta[0]).z.shape == ()
+ # the (B,) reading is a view, so the gradient reaches the (B, 1) angle
+ column = column.clone().requires_grad_()
+ (So2.exp(column) * p).sum().backward()
+ assert column.grad.shape == (3, 1) and torch.isfinite(column.grad).all()
+
+ def test_so2_column_parameter_stays_the_module_parameter_4932(self, device, dtype):
+ # Reading a (B, 1) z as (B,) must not take a caller's nn.Parameter away from the module: it stays its own
+ # parameter under the same state_dict key and shape, so an optimizer over So2.parameters() trains it.
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ theta = torch.tensor([0.3, 0.5, 0.7], device=device, dtype=dtype)
+ param = torch.nn.Parameter(torch.complex(theta.cos(), theta.sin())[:, None])
+ s = So2(param)
+ assert s.z.shape == (3,)
+ assert [(name, t is param) for name, t in s.named_parameters()] == [("_z", True)]
+ assert s.state_dict()["_z"].shape == (3, 1)
+ assert s[1].z.shape == () # indexing reads the (B,) view, as for a (B,) z
+ before = torch.view_as_real(param.detach()).clone() # torch.equal has no complex float16 kernel
+ s.log().sum().backward()
+ torch.optim.SGD(s.parameters(), lr=0.1).step()
+ assert not torch.equal(torch.view_as_real(param.detach()), before)
def test_wart_so2_real_dtype_cast_drops_the_imaginary_part_4923(self, device, dtype):
if dtype == torch.bfloat16: