π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): avoid NaN gradients in Horn essential decomposition (#5876)
peng xiange4a64fa0db76
diff --git a/changelog.d/5876.fixed.md b/changelog.d/5876.fixed.mdnew file mode 100644index 000000000..d2f3cf4f5--- /dev/null+++ b/changelog.d/5876.fixed.md@@ -0,0 +1 @@+`decompose_essential_matrix_no_svd` no longer returns NaN gradients when the translation is perpendicular to a column of the rotation, for example a stereo rig or forward motion without rotation, or planar motion that rotates about the camera's y axis and translates perpendicular to it. Its outputs are unchanged.diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 356fe5c1a..a9b0fcf8c 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -603,14 +603,13 @@ def decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.Tensor# B, to select which b1largest = torch.argmax(norms, dim=-2)- # B, 3, 3- e_cross_products = scale_factor[:, None, None] * cross_products / norms-# broadcast the index- index_expanded = largest.unsqueeze(-1).expand(-1, -1, e_cross_products.size(-1))+ index_expanded = largest.unsqueeze(-1).expand(-1, -1, cross_products.size(-1))- # slice at dim=1, select for each batch one b (e1*e2 or e2*e3 or e3*e1), B, 1, 3- b1 = torch.gather(e_cross_products, dim=1, index=index_expanded).squeeze(1)+ # Select before dividing: unused zero cross products would give 0/0 and NaN gradients.+ b1 = torch.gather(cross_products, dim=1, index=index_expanded).squeeze(1)+ selected_norm = torch.gather(norms, dim=1, index=largest.unsqueeze(-1)).squeeze(1)+ b1 = scale_factor[:, None] * b1 / selected_norm# normalizationb1_ = b1 / torch.norm(b1, dim=-1, keepdim=True)diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex 6c433a7fd..6e4ab91ee 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -717,21 +717,96 @@ class TestDecomposeEssentialMatrixNoSVD(BaseTester):assert t.shape == batch_shape[:-1] + (1,)def test_gradcheck(self, device):+ """Check both rotation candidates and the translation against finite differences."""E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)def eval_rot1(input):+ """Return the first rotation candidate for its gradient check."""return epi.decompose_essential_matrix_no_svd(input)[0]def eval_rot2(input):+ """Return the second rotation candidate for its gradient check."""return epi.decompose_essential_matrix_no_svd(input)[1]def eval_vec(input):+ """Return the unit translation candidate for its gradient check."""return epi.decompose_essential_matrix_no_svd(input)[2]self.gradcheck(eval_rot1, (E_mat,))self.gradcheck(eval_rot2, (E_mat,))self.gradcheck(eval_vec, (E_mat,))+ @pytest.mark.parametrize("axis", [0, 1, 2])+ @pytest.mark.parametrize("angle", [0.0, 0.3])+ def test_axis_aligned_pose_gradients_5867(self, axis, angle, device, dtype):+ """Compare sparse-pose outputs and all angular derivatives with Rodrigues' formula."""+ # E(theta) = [t]_x R_t(theta), with t a coordinate axis. One cross product is nonzero;+ # the other two vanish. Rodrigues gives R, dR/dtheta, and the second candidate R_pi R.+ generators = torch.tensor(+ [+ [[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]],+ [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]],+ [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ ],+ device=device,+ dtype=dtype,+ )+ generator = generators[axis]+ squared = generator @ generator+ identity = torch.eye(3, device=device, dtype=dtype)+ translation = identity[axis]+ half_turn = 2 * translation[:, None] * translation[None, :] - identity+ theta = torch.tensor(angle, device=device, dtype=dtype, requires_grad=True)++ def pose(theta):+ """Decompose the essential matrix of a rotation about the translation axis."""+ rotation = identity + theta.sin() * generator + (1 - theta.cos()) * squared+ return epi.decompose_essential_matrix_no_svd(generator @ rotation)++ rotation = identity + theta.sin() * generator + (1 - theta.cos()) * squared+ derivative = theta.cos() * generator + theta.sin() * squared+ expected = (rotation[None], (half_turn @ rotation)[None], translation.reshape(1, 3, 1))+ expected_jacobians = (derivative[None], (half_turn @ derivative)[None], torch.zeros_like(expected[2]))+ for actual, reference in zip(pose(theta), expected):+ self.assert_close(actual, reference)+ # Check every scalar derivative, including the entries that should remain zero.+ for actual, reference in zip(torch.autograd.functional.jacobian(pose, theta), expected_jacobians):+ assert torch.isfinite(actual).all()+ self.assert_close(actual, reference)++ def test_gradcheck_axis_aligned_5867(self, device):+ """Check a sparse batch whose rows select different column cross products."""+ # Different rows select different cross products; none should differentiate an unused 0/0.+ E_mat = torch.tensor(+ [+ [[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]],+ [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]],+ [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ ],+ device=device,+ dtype=torch.float64,+ requires_grad=True,+ )+ self.gradcheck(epi.decompose_essential_matrix_no_svd, (E_mat,))++ def test_dynamo_axis_aligned_5867(self, device, dtype, torch_optimizer):+ """Compare fullgraph outputs and finite backward gradients with eager execution."""+ E_mat = torch.tensor(+ [[[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]],+ device=device,+ dtype=dtype,+ requires_grad=True,+ )+ op = epi.decompose_essential_matrix_no_svd+ compiled = torch_optimizer(op, fullgraph=True)+ expected, actual = op(E_mat), compiled(E_mat)+ for result, reference in zip(actual, expected):+ self.assert_close(result, reference)+ eager_gradient = torch.autograd.grad(sum(value.sum() for value in expected), E_mat)[0]+ compiled_gradient = torch.autograd.grad(sum(value.sum() for value in actual), E_mat)[0]+ assert torch.isfinite(compiled_gradient).all()+ self.assert_close(compiled_gradient, eager_gradient)+def test_correct_decompose(self):E_mat = torch.tensor([[[0.2057, -3.8266, 3.1615], [4.5417, -1.0707, -2.2023], [-1.0975, 1.6386, -0.6590]]])R1, R2, t = epi.decompose_essential_matrix(E_mat)