π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix rad2deg and deg2rad precision for integer and float64 inputs (#4358)
Hrithik Sharma315be7cccb5f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fadb79bcf..4e03671a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -364,6 +364,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `rad2deg` and `deg2rad` now handle integer tensor inputs correctly and preserve+ float64 precision. `angle_to_rotation_matrix` inherits the corrected conversion,+ while the implementation preserves ONNX export compatibility. (#4358)* `CameraModelBase.__init__` now validates `params` against the shape it documents, instead of storingwhatever it is given. The typed constructors (`PinholeModel`, `BrownConradyModel`, `KannalaBrandtK3`,`Orthographic`) each apply the same two comparisons, so only the direct-construction path -- which isdiff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 679e11791..d555b5b67 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -22,10 +22,10 @@ import torchimport torch.nn.functional as Ffrom torch import nn+from kornia.constants import pifrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.utils import _l2_normalizefrom kornia.filters import get_gaussian_kernel2d, spatial_gradient-from kornia.geometry.conversions import pidef _get_reshape_kernel(kd: int, ky: int, kx: int) -> torch.Tensor:diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex d6ccf1405..a1a06d05d 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -17,13 +17,13 @@from __future__ import annotations+import mathimport warningsfrom typing import Optionalimport torchimport torch.nn.functional as F-from kornia.constants import pifrom kornia.core._compat import deprecatedfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.core.utils import _inverse_3x3_closed_form, _torch_inverse_cast, is_compiling@@ -84,20 +84,6 @@ def rad2deg(tensor: torch.Tensor) -> torch.Tensor:- the input is in **radians** and the output in **degrees**; theconversion is elementwise and preserves shape, device and float dtype- .. warning::- Two distinct defects, tracked in- `#3937 <https://github.com/kornia/kornia/issues/3937>`_. A ``float64``- input is left with only about seven correct significant digits- (``rad2deg(torch.tensor(math.pi, dtype=torch.float64)) - 180`` is- ``-5.0e-06``, not ``0``) because ``kornia.constants.pi`` is a- **float32** tensor β a defect in the constant itself, which several- other kornia modules also consume (the issue tracks the current- inventory). Separately, ``rad2deg``/``deg2rad``- themselves cast that constant to the input dtype, so an integer input- truncates ``pi`` to ``3``: ``rad2deg(torch.tensor([1, 2, 3]))`` returns- ``[60., 120., 180.]`` instead of ``[57.2958, 114.5916, 171.8873]``, and- a ``float64`` constant alone would not fix it.-Args:tensor: torch.Tensor of arbitrary shape.@@ -113,7 +99,7 @@ def rad2deg(tensor: torch.Tensor) -> torch.Tensor:if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")- return 180.0 * tensor / pi.to(tensor.device).type(tensor.dtype)+ return tensor * (180.0 / math.pi)def deg2rad(tensor: torch.Tensor) -> torch.Tensor:@@ -124,13 +110,6 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:performs the opposite conversion to:func:`~kornia.geometry.conversions.rad2deg`- .. warning::- Inherits both defects of :func:`~kornia.geometry.conversions.rad2deg`- β the float32 ``kornia.constants.pi`` and the cast to the input dtype- (``deg2rad(torch.tensor([180, 90]))`` returns ``[3.0000, 1.5000]``).- See its warning and- `#3937 <https://github.com/kornia/kornia/issues/3937>`_.-Args:tensor: torch.Tensor of arbitrary shape.@@ -146,7 +125,7 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")- return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.0+ return tensor * (math.pi / 180.0)def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:@@ -1760,13 +1739,6 @@ def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor::func:`~kornia.geometry.conversions.cart2pol`, whose Convention blockspells out the modulo-:math:`2\pi` relation between the two ops- .. warning::- The degrees-to-radians step is- :func:`~kornia.geometry.conversions.deg2rad`, so it inherits both- defects of :func:`~kornia.geometry.conversions.rad2deg` β the float32- ``kornia.constants.pi`` and the cast to the input dtype. See its- warning and `#3937 <https://github.com/kornia/kornia/issues/3937>`_.-Args:angle: tensor of angles in degrees, any shape :math:`(*)`.diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex 1e2026d30..88a2adb40 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -413,8 +413,6 @@ call builtins.AssertionError tests/geometry/test_conversions.py::TestNormalizePicall builtins.AssertionError tests/geometry/test_conversions.py::TestNormalizePixelCoordinates::test_tensor_bhw2[cpu-bfloat16]call builtins.AssertionError tests/geometry/test_conversions.py::TestQuaternionExpToLog::test_back_and_forth[cpu-bfloat16]call builtins.AssertionError tests/geometry/test_conversions.py::TestQuaternionFromEuler::test_values[cpu-bfloat16]-call builtins.AssertionError tests/geometry/test_conversions.py::TestRadDegConversions::test_deg2rad[cpu-bfloat16-batch_shape0]-call builtins.AssertionError tests/geometry/test_conversions.py::TestRadDegConversions::test_deg2rad[cpu-bfloat16-batch_shape1]call builtins.AssertionError tests/geometry/test_conversions.py::TestRadDegConversions::test_deg2rad[cpu-bfloat16-batch_shape2]call builtins.AssertionError tests/geometry/test_conversions.py::TestRadDegConversions::test_deg2rad[cpu-bfloat16-batch_shape3]call builtins.AssertionError tests/geometry/test_conversions.py::TestRotationMatrixToAngleAxis::test_rand_quaternion_gradcheck[cpu-bfloat16-1]diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex ecaa4c23a..1f6fea7d3 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -503,7 +503,6 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotatcall builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-float16-2]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestRotationMatrix2d::test_rotation_90deg_and_scale[cpu-float16-5]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_fill_padding_translation[cpu-float16]-call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_rotation_inverse[cpu-float16]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpAffine::test_translation[cpu-float16]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_convention_normalize_invert_equivalence[cpu-float16]call builtins.AssertionError tests/geometry/transform/test_imgwarp.py::TestWarpPerspective::test_fill_padding_translation[cpu-float16]diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 84f7b50a6..c3d5340de 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -2542,12 +2542,6 @@ class TestRadDegConversions(BaseTester):x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=torch.float64)self.gradcheck(kornia.geometry.conversions.deg2rad, (x_deg,))- @pytest.mark.xfail(- raises=AssertionError,- reason="kornia.constants.pi is float32, so f64 loses ~7 digits (angle_to_rotation_matrix "- "inherits it via deg2rad) β kornia#3937",- strict=True,- )@pytest.mark.parametrize(("op_name", "arg", "expected"),[@@ -2557,24 +2551,12 @@ class TestRadDegConversions(BaseTester):],)def test_convention_float64_results_are_exact_3937(self, device, op_name, arg, expected):- # Intended behavior: each op is exact to the precision of its input dtype, like- # torch.rad2deg / torch.deg2rad; angle_to_rotation_matrix(90) is then the exact quarter- # turn. It is not: all three multiply by kornia.constants.pi, a *float32* tensor merely- # cast to the input dtype, so a float64 input carries a systematic ~2.8e-8 relative- # error (#3937). float64 is hardcoded (like test_rad2deg_gradcheck above) because at- # float32 the biased constant *is* the correctly rounded pi; MPS is skipped visibly- # below because it has no float64 at all, so without the skip the xfail would be- # satisfied by a TypeError instead of the precision assert it documents (hence also- # raises=AssertionError on the mark). Marked xfail(strict=True) so fixing #3937 makes- # every case XPASS and forces this mark out β a one-place edit.- # Snippet used to generate expected (stdlib + torch):- # math.degrees(math.pi) == 180.0 and (180.0 * math.pi) / 180.0 == math.pi exactly- # kornia rad2deg(tensor(pi, f64)).item() -> 179.99999499104382- # kornia deg2rad(tensor(180., f64)).item() -> 3.1415927410125732 (math.pi + 8.7e-08)- # kornia angle_to_rotation_matrix(tensor(90., f64)).flatten().tolist() ->- # [-4.371139000186241e-08, 0.999999999999999, -0.999999999999999, -4.371139e-08]- # atol/rtol 1e-12 sits between the current ~4.4e-8 cosine error and the 6.123234e-17- # an unbiased constant would give.+ # Regression for #3937: rad2deg and deg2rad must preserve float64 precision.+ # angle_to_rotation_matrix inherits the corrected conversion through deg2rad,+ # so a 90-degree input should produce the expected quarter-turn matrix without+ # the previous float32 pi bias.+ # float64 is hardcoded because this regression specifically checks double precision.+if device.type == "mps":pytest.skip("MPS has no float64, and this pin is float64-only by construction")@@ -2612,36 +2594,22 @@ class TestRadDegConversions(BaseTester):@pytest.mark.parametrize(("op_name", "arg", "expected"),[- ("rad2deg", [1, 2, 3], [60.0, 120.0, 180.0]),- ("deg2rad", [180, 90], [3.0, 1.5]),- ("angle_to_rotation_matrix", [90], [[[0.07073720, 0.99749500], [-0.99749500, 0.07073720]]]),+ ("rad2deg", [1, 2, 3], [57.29577951308232, 114.59155902616465, 171.88733853924697]),+ ("deg2rad", [180, 90], [3.141592653589793, 1.5707963267948966]),+ ("angle_to_rotation_matrix", [90], [[[0.0, 1.0], [-1.0, 0.0]]]),],)- def test_wart_integer_input_truncates_pi_to_3_3937(self, device, op_name, arg, expected):- # Wart pins for #3937: assert the CURRENT broken outputs the docstring warnings document.- # kornia.constants.pi is cast to the *integer* input dtype and truncates to 3, so rad2deg- # divides by 3, deg2rad multiplies by 3 (90 degrees -> 1.5 radians), and the downstream- # angle_to_rotation_matrix([90]) is nowhere near the quarter turn. If a case fails, #3937- # was (partly) fixed -- update or remove the warnings in rad2deg, deg2rad and- # angle_to_rotation_matrix and flip/remove the strict xfail above. NOT a contract that- # int inputs must keep these values: what they *should* do (promote to float like- # torch.rad2deg, or raise) is a maintainer decision, and a strict xfail asserting the- # promoted-float answer would stay silently XFAIL forever if the fix chose to raise;- # a wart pin flips loudly under either polarity.- # Snippet used to generate expected (torch only):- # kornia rad2deg(torch.tensor([1, 2, 3])) -> tensor([ 60., 120., 180.]), dtype float32- # (torch.rad2deg gives [ 57.2958, 114.5916, 171.8873])- # kornia deg2rad(torch.tensor([180, 90])) -> tensor([3.0000, 1.5000]), dtype float32- # (torch.deg2rad gives [3.1416, 1.5708])- # kornia angle_to_rotation_matrix(torch.tensor([90])).flatten().tolist() ->- # [0.07073719799518585, 0.9974949955940247, -0.9974949955940247, 0.07073719799518585]- # (math.cos(1.5), math.sin(1.5) -> (0.0707372016677029, 0.9974949866040544))+ def test_integer_input_promotes_to_float_3937(self, device, op_name, arg, expected):op = getattr(kornia.geometry.conversions, op_name)-out = op(torch.tensor(arg, device=device))assert out.dtype == torch.float32- self.assert_close(out, torch.tensor(expected, device=device, dtype=torch.float32), atol=1e-4, rtol=1e-4)+ self.assert_close(+ out,+ torch.tensor(expected, device=device, dtype=torch.float32),+ atol=1e-6,+ rtol=1e-6,+ )class TestPolCartConversions(BaseTester):