diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 63c581fd6dac..06a9de465bdb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -224,6 +224,7 @@ Guidelines for modifications: * Stefan Van de Mosselaer * Stephan Pleines * Sujal +* Sylvester Kaczmarek * Tiffany Chen * Trushant Adeshara * Tsz Ki GAO diff --git a/source/isaaclab/changelog.d/axis-angle-identity-gradients.fixed.rst b/source/isaaclab/changelog.d/axis-angle-identity-gradients.fixed.rst new file mode 100644 index 000000000000..b91ab338e0d2 --- /dev/null +++ b/source/isaaclab/changelog.d/axis-angle-identity-gradients.fixed.rst @@ -0,0 +1 @@ +* Fixed nonfinite gradients when converting identity quaternions to axis-angle rotation vectors. diff --git a/source/isaaclab/isaaclab/utils/math.py b/source/isaaclab/isaaclab/utils/math.py index 3248a027656d..60bb0c41b4a5 100644 --- a/source/isaaclab/isaaclab/utils/math.py +++ b/source/isaaclab/isaaclab/utils/math.py @@ -493,10 +493,11 @@ def axis_angle_from_quat(quat: torch.Tensor, eps: float = 1.0e-6) -> torch.Tenso mag = torch.linalg.norm(quat[..., :3], dim=-1) half_angle = torch.atan2(mag, quat[..., 3]) angle = 2.0 * half_angle - # check whether to apply Taylor approximation - sin_half_angles_over_angles = torch.where( - angle.abs() > eps, torch.sin(half_angle) / angle, 0.5 - angle * angle / 48 - ) + # Avoid dividing by zero even in the unselected branch of torch.where: + # autograd can otherwise propagate NaN gradients at the identity. + use_exact = angle.abs() > eps + safe_angle = torch.where(use_exact, angle, 1.0) + sin_half_angles_over_angles = torch.where(use_exact, torch.sin(half_angle) / safe_angle, 0.5 - angle * angle / 48) return quat[..., :3] / sin_half_angles_over_angles.unsqueeze(-1) diff --git a/source/isaaclab/test/utils/test_math.py b/source/isaaclab/test/utils/test_math.py index 60192840632e..37a6b828c138 100644 --- a/source/isaaclab/test/utils/test_math.py +++ b/source/isaaclab/test/utils/test_math.py @@ -149,6 +149,19 @@ def test_is_identity_pose(device): assert math_utils.is_identity_pose(identity_pos, identity_rot) is False +@pytest.mark.kitless +def test_axis_angle_from_quat_identity_gradients() -> None: + """Both quaternion signs of the identity rotation have finite local derivatives.""" + quats = torch.tensor([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, -1.0]], dtype=torch.float64) + quats.requires_grad_() + rotation = math_utils.axis_angle_from_quat(quats) + torch.testing.assert_close(rotation, torch.zeros_like(rotation)) + # Near identity, the rotation vector is 2 * xyz after canonicalizing the quaternion sign. + (grad,) = torch.autograd.grad(rotation.sum(), quats) + expected = torch.tensor([[2.0, 2.0, 2.0, 0.0], [-2.0, -2.0, -2.0, 0.0]], dtype=quats.dtype) + torch.testing.assert_close(grad, expected) + + @pytest.mark.parametrize("device", test_devices()) def test_axis_angle_from_quat_approximation(device): """Test the Taylor approximation from axis_angle_from_quat method.