π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): read sin from the skew part and the cross product so angle_error_mat and angle_error_vec resolve small angles (#5505)
εΊζ’η69659ff77af4
diff --git a/changelog.d/5505.fixed.md b/changelog.d/5505.fixed.mdnew file mode 100644index 000000000..3f012b3b5--- /dev/null+++ b/changelog.d/5505.fixed.md@@ -0,0 +1,10 @@+`kornia.metrics.angle_error_mat` and `kornia.metrics.angle_error_vec` now read the sine of the angle from the skew+part of the relative rotation and from the cross product of the two unit vectors and return `atan2(sin, cos)`,+so a float32 angle is resolved to about 2e-5 degrees over the whole range (#5500). Previously both used+`acos` of the cosine, which returned exactly 0 for every angle below about 0.03 degrees and 180 for 179.99+degrees in float32, and had an infinite or NaN gradient at exactly 0 and 180 degrees on older torch versions;+the gradient there is now the subgradient 0.+`angle_error_vec` also scales each vector by its largest absolute entry instead of its norm, so very long and very short+vectors keep their angle: two float32 vectors 45 degrees apart with lengths 1.8e19, 1.9e19, 1e30, 9e-23 or 1e-40, or two+float16 vectors with lengths 255, 257 or 6e4, now return 45.0, where previously the squared norms or their product+overflowed or underflowed and the result was 90, NaN, NaN, 41.4 and NaN in float32 and 90, NaN and NaN in float16.diff --git a/kornia/metrics/pose.py b/kornia/metrics/pose.pyindex 5cfbb5a68..685b8bdfd 100644--- a/kornia/metrics/pose.py+++ b/kornia/metrics/pose.py@@ -38,11 +38,25 @@ from kornia.core.check import ()+def _angle_deg(sin_theta: Tensor, cos_theta: Tensor) -> Tensor:+ """Angle in degrees from a non-negative sine and a cosine, the same in eager, compiled and ONNX graphs."""+ # -atan2(-sin, cos) is atan2(sin, cos). At sin = +0 and cos < 0 the ONNX export's atan2 returns -pi instead of+ # pi; with -0 it returns -pi in both, which the negation turns into pi.+ theta = torch.rad2deg(-torch.atan2(-sin_theta, cos_theta))+ # The ONNX export's atan2 also maps NaN to 0, so a NaN input (a zero vector) would read as a perfect match.+ nan = sin_theta + cos_theta+ return torch.where(torch.isnan(nan), nan, theta)++def angle_error_mat(R1: Tensor, R2: Tensor) -> Tensor:r"""Geodesic angle (in degrees) between two rotation matrices.- The relative rotation :math:`R_1^\top R_2` has trace :math:`1 + 2\cos\theta`, so the geodesic- angle is :math:`\theta = \arccos\!\big((\mathrm{tr}(R_1^\top R_2) - 1) / 2\big)`.+ The relative rotation :math:`R = R_1^\top R_2` has trace :math:`1 + 2\cos\theta` and skew part+ :math:`(R - R^\top) / 2 = \sin\theta\,[\mathbf{n}]_\times` for its unit axis :math:`\mathbf{n}`, so the+ geodesic angle is :math:`\theta = \operatorname{atan2}(\sin\theta, \cos\theta)`. Reading+ :math:`\sin\theta` from the skew part keeps the digits of small angles that+ :math:`\arccos\!\big((\mathrm{tr}\,R - 1) / 2\big)` loses next to :math:`1`: in float32 the result+ stays within about :math:`2 \cdot 10^{-5}` degrees of the exact angle over the whole range.Args:R1: a rotation matrix of shape :math:`(*, 3, 3)`.@@ -52,10 +66,9 @@ def angle_error_mat(R1: Tensor, R2: Tensor) -> Tensor:the per-matrix angle in degrees, with shape :math:`(*,)`... note::- The gradient is infinite/NaN exactly at :math:`0^\circ` and :math:`180^\circ` (identical or- opposite rotations), because :math:`\frac{d}{dx}\arccos(x) \to \infty` at :math:`x = \pm 1`.- This is inherent to every geodesic/angular metric; it only bites if you backpropagate through- a perfect or exactly-opposite match.+ The angle has a kink at exactly :math:`0^\circ` and :math:`180^\circ` (identical or opposite+ rotations). The gradient there is the subgradient :math:`0` that ``norm`` returns at a zero+ vector, so backpropagating through a perfect or exactly-opposite match stays finite.Example:>>> angle_error_mat(torch.eye(3), torch.eye(3))@@ -69,14 +82,21 @@ def angle_error_mat(R1: Tensor, R2: Tensor) -> Tensor:relative = R1.transpose(-2, -1) @ R2trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1)- cos_theta = ((trace - 1.0) / 2.0).clamp(-1.0, 1.0)- return torch.rad2deg(cos_theta.acos())+ cos_theta = (trace - 1.0) / 2.0+ # (R - R^T) / 2 = sin(theta) [n]_x, so its three independent entries have norm sin(theta).+ skew = relative - relative.transpose(-2, -1)+ sin_theta = 0.5 * torch.stack((skew[..., 2, 1], skew[..., 0, 2], skew[..., 1, 0]), dim=-1).norm(dim=-1)+ return _angle_deg(sin_theta, cos_theta)def angle_error_vec(v1: Tensor, v2: Tensor) -> Tensor:r"""Angle (in degrees) between two vectors.- The angle is :math:`\theta = \arccos\!\big((v_1 \cdot v_2) / (\lVert v_1 \rVert \lVert v_2 \rVert)\big)`.+ With the unit vectors :math:`\hat v_1` and :math:`\hat v_2`, the angle is+ :math:`\theta = \operatorname{atan2}(\lVert \hat v_1 \times \hat v_2 \rVert, \hat v_1 \cdot \hat v_2)`.+ Reading :math:`\sin\theta` from the cross product keeps the digits of small angles that+ :math:`\arccos(\hat v_1 \cdot \hat v_2)` loses next to :math:`1`: in float32 the result stays within+ about :math:`2 \cdot 10^{-5}` degrees of the exact angle over the whole range.Args:v1: a vector of shape :math:`(*, 3)`.@@ -86,10 +106,9 @@ def angle_error_vec(v1: Tensor, v2: Tensor) -> Tensor:the per-vector angle in degrees, with shape :math:`(*,)`... note::- The gradient is infinite/NaN exactly at :math:`0^\circ` and :math:`180^\circ` (identical or- opposite vectors), because :math:`\frac{d}{dx}\arccos(x) \to \infty` at :math:`x = \pm 1`.- This is inherent to every geodesic/angular metric; it only bites if you backpropagate through- a perfect or exactly-opposite match.+ The angle has a kink at exactly :math:`0^\circ` and :math:`180^\circ` (identical or opposite+ vectors). The gradient there is the subgradient :math:`0` that ``norm`` returns at a zero+ vector, so backpropagating through a perfect or exactly-opposite match stays finite... note::A zero-length vector gives ``NaN`` rather than raising, since the angle is undefined there.@@ -106,10 +125,13 @@ def angle_error_vec(v1: Tensor, v2: Tensor) -> Tensor:KORNIA_CHECK_SHAPE(v2, ["*", "3"])KORNIA_CHECK_SAME_SHAPE(v1, v2)- dot = (v1 * v2).sum(-1)- norms = v1.norm(dim=-1) * v2.norm(dim=-1)- cos_theta = (dot / norms).clamp(-1.0, 1.0)- return torch.rad2deg(cos_theta.acos())+ # atan2 does not depend on the length of either vector, so scaling each one by its largest entry is enough.+ # Unlike a norm, that cannot overflow or underflow, and a zero vector still gives 0 / 0 = NaN.+ v1 = v1 / v1.abs().amax(dim=-1, keepdim=True)+ v2 = v2 / v2.abs().amax(dim=-1, keepdim=True)+ sin_theta = torch.linalg.cross(v1, v2, dim=-1).norm(dim=-1)+ cos_theta = (v1 * v2).sum(-1)+ return _angle_deg(sin_theta, cos_theta)def translation_ate(t: Tensor, t_gt: Tensor) -> Tensor:@@ -129,9 +151,7 @@ def translation_ate(t: Tensor, t_gt: Tensor) -> Tensor:treated as a single sample and returns shape :math:`(1,)`... note::- Unlike the :func:`angle_error_vec` / :func:`angle_error_mat` angular metrics, this has no- ``arccos`` singularity: the gradient stays finite even at zero distance, where ``norm``- returns the subgradient ``0``.+ The gradient stays finite even at zero distance, where ``norm`` returns the subgradient ``0``.Example:>>> t = torch.tensor([0.0, 0.0, 0.0])diff --git a/tests/metrics/test_pose.py b/tests/metrics/test_pose.pyindex c57e91ea2..bd54d37b5 100644--- a/tests/metrics/test_pose.py+++ b/tests/metrics/test_pose.py@@ -73,6 +73,32 @@ class TestAngleErrorMat(BaseTester):with pytest.raises(Exception):kornia.metrics.angle_error_mat(R1, R2)+ def test_small_and_near_half_turn_angles(self, device, dtype):+ # Built in float64 and cast, so the angle is exact up to the cast. The skew part resolves these;+ # acos((tr - 1) / 2) returns exactly 0 and 180 for all four.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("a rotation this small rounds to the identity in half precision")+ small = {torch.float32: 0.01, torch.float64: 1e-6}[dtype]+ atol = {torch.float32: 1e-4, torch.float64: 1e-9}[dtype]+ angles = torch.tensor([small, 180.0 - small], dtype=torch.float64)+ # Unit length with all three components nonzero, so each entry of the skew part carries part of sin(theta).+ axis = torch.tensor([[0.48, 0.6, 0.64]], dtype=torch.float64)+ R1 = kornia.geometry.axis_angle_to_rotation_matrix(torch.tensor([[0.3, -0.5, 0.8]], dtype=torch.float64))+ R2 = R1 @ kornia.geometry.axis_angle_to_rotation_matrix(torch.deg2rad(angles)[:, None] * axis)+ R1 = R1.expand(2, 3, 3).to(device=device, dtype=dtype)+ out = kornia.metrics.angle_error_mat(R1, R2.to(device=device, dtype=dtype))+ self.assert_close(out, angles.to(device=device, dtype=dtype), rtol=0.0, atol=atol)++ def test_gradient_is_zero_at_zero_and_half_turn(self, device, dtype):+ # Both ends are kinks of the angle: norm returns the subgradient 0 at the zero skew part.+ eye = torch.eye(3, device=device, dtype=dtype)+ half_turn = torch.diag(torch.tensor([1.0, -1.0, -1.0], device=device, dtype=dtype))+ R1 = torch.stack([eye, eye]).requires_grad_()+ out = kornia.metrics.angle_error_mat(R1, torch.stack([eye, half_turn]))+ self.assert_close(out, torch.tensor([0.0, 180.0], device=device, dtype=dtype))+ out.sum().backward()+ self.assert_close(R1.grad, torch.zeros_like(R1))+class TestAngleErrorVec(BaseTester):def test_aligned_orthogonal_opposite(self, device, dtype):@@ -95,6 +121,17 @@ class TestAngleErrorVec(BaseTester):zero = torch.zeros(3, device=device, dtype=dtype)unit = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)assert torch.isnan(kornia.metrics.angle_error_vec(zero, unit))+ assert torch.isnan(kornia.metrics.angle_error_vec(unit, zero))++ def test_huge_and_tiny_vectors(self, device, dtype):+ # The squared norm of these overflows (huge) or underflows (tiny) in the dtype; the angle is still 45 degrees.+ finfo = torch.finfo(dtype)+ # Negative entries, so the scale has to come from the magnitude of the largest entry.+ a = torch.tensor([-1.0, 0.0, 0.0], device=device, dtype=dtype)+ b = torch.tensor([-1.0, -1.0, 0.0], device=device, dtype=dtype)+ expected = torch.tensor(45.0, device=device, dtype=dtype)+ for scale in (4.0 * finfo.max**0.5, 0.25 * finfo.tiny**0.5):+ self.assert_close(kornia.metrics.angle_error_vec(scale * a, scale * b), expected)def test_mismatched_batch_raises(self, device, dtype):# A batch of 1 against a batch of 5 used to broadcast instead of raising.@@ -108,6 +145,32 @@ class TestAngleErrorVec(BaseTester):v2 = torch.tensor([0.0, 1.0, 0.0], device=device, dtype=torch.float64)self.gradcheck(kornia.metrics.angle_error_vec, (v1, v2), requires_grad=(True, False))+ def test_small_and_near_half_turn_angles(self, device, dtype):+ # Rotating v1 about an axis orthogonal to it opens exactly that angle between the two vectors. The+ # cross product resolves these; acos(cos) returns exactly 0 and 180 for all four.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("two directions this close round to the same direction in half precision")+ small = {torch.float32: 0.01, torch.float64: 1e-6}[dtype]+ atol = {torch.float32: 1e-4, torch.float64: 1e-9}[dtype]+ angles = torch.tensor([small, 180.0 - small], dtype=torch.float64)+ axis = torch.tensor([[1.0, 0.0, 0.0]], dtype=torch.float64)+ v1 = torch.tensor([[0.0, 0.6, 0.8]], dtype=torch.float64)+ R = kornia.geometry.axis_angle_to_rotation_matrix(torch.deg2rad(angles)[:, None] * axis)+ v2 = 3.0 * (R @ v1[..., None])[..., 0]+ out = kornia.metrics.angle_error_vec(+ v1.expand(2, 3).to(device=device, dtype=dtype), v2.to(device=device, dtype=dtype)+ )+ self.assert_close(out, angles.to(device=device, dtype=dtype), rtol=0.0, atol=atol)++ def test_gradient_is_zero_at_zero_and_half_turn(self, device, dtype):+ # Both ends are kinks of the angle: norm returns the subgradient 0 at the zero cross product.+ x = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)+ v1 = torch.stack([x, x]).requires_grad_()+ out = kornia.metrics.angle_error_vec(v1, torch.stack([x, -x]))+ self.assert_close(out, torch.tensor([0.0, 180.0], device=device, dtype=dtype))+ out.sum().backward()+ self.assert_close(v1.grad, torch.zeros_like(v1))+class TestTranslationAte(BaseTester):def test_single_returns_batch_shape(self, device, dtype):diff --git a/tests/onnx/test_export_coverage.py b/tests/onnx/test_export_coverage.pyindex dd1106074..ee9367ab5 100644--- a/tests/onnx/test_export_coverage.py+++ b/tests/onnx/test_export_coverage.py@@ -168,6 +168,20 @@ def _cases():),id="fit_line_2d_vertical",),+ pytest.param(+ # Exactly 0 and 180 degrees, and a zero vector: the exported atan2 returns -pi for atan2(+0, negative) and+ # maps NaN to 0, where eager returns +pi and NaN (#5500).+ _Fn(+ lambda R1, R2, v1, v2: (kornia.metrics.angle_error_mat(R1, R2), kornia.metrics.angle_error_vec(v1, v2))+ ),+ (+ torch.stack([torch.eye(3), torch.eye(3)]),+ torch.stack([torch.eye(3), torch.diag(torch.tensor([1.0, -1.0, -1.0]))]),+ torch.tensor([[1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),+ torch.tensor([[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]),+ ),+ id="angle_error_kinks",+ ),]