π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): Keep half-precision depth normals finite (#6137)
A Aswanth Rajb43bdeac03d5
diff --git a/changelog.d/6137.fixed.md b/changelog.d/6137.fixed.mdnew file mode 100644index 000000000..29cd8de03--- /dev/null+++ b/changelog.d/6137.fixed.md@@ -0,0 +1 @@+`depth_to_normals` now widens float16 and bfloat16 inputs to float32 and runs its gradient convolution outside autocast. float16 depth maps gave NaN normals for near surfaces (closer than about 0.25 m at a 1000-pixel focal length) and inside zero-depth holes, normals off by tens of degrees at 0.5 to 1 m, and non-finite gradients; bfloat16 depth maps wider than 256 pixels gave zero normals; float32 depth maps inside an autocast region gave normals off by a median of 1 to 40 degrees (and, under float16 autocast, non-finite gradients); and float16 or bfloat16 depth maps inside a CPU autocast region of the other half dtype raised `RuntimeError`. The output dtype inside autocast now follows the inputs, as it does outside: under CPU autocast, float32 and integer inputs used to return the autocast dtype, and under CUDA autocast, half-precision inputs used to return float32.diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex 28b13a7a6..d55fc64ef 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -27,7 +27,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.core.exceptions import ShapeError-from kornia.core.utils import _torch_grid_sample+from kornia.core.utils import _autocast_disabled, _torch_grid_samplefrom kornia.filters.sobel import spatial_gradientfrom kornia.geometry.grid import create_meshgrid@@ -241,6 +241,9 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalizethe columns tilts it towards ``-x``, one growing along the rows towards ``-y``.- the arguments mean what they mean for :func:`~kornia.geometry.depth.depth_to_3d`, and the resulthas its :math:`(B, 3, H, W)` layout.+ - float16 and bfloat16 inputs are widened to float32 first. The result has the promoted dtype of ``depth`` and+ ``camera_matrix``, or the default floating dtype when both are integer, and it does not follow an+ enclosing autocast region: its dtype and values are the same inside autocast as outside.Args:depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`, with@@ -275,11 +278,21 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalizeexpected_shape=["B", "1", "H >= 2", "W >= 2"],)+ dtype = torch.promote_types(depth.dtype, camera_matrix.dtype)+ # Compute in float32 when either input is half precision: bfloat16 cannot hold the pixel grid past 256 and the+ # float16 cross product of small pixel tangents underflows. The grid takes ``depth``'s dtype, so cast each input.+ if depth.dtype in (torch.float16, torch.bfloat16):+ depth = depth.float()+ if camera_matrix.dtype in (torch.float16, torch.bfloat16):+ camera_matrix = camera_matrix.float()+# compute the 3d points from depth; permute to channel-first for spatial_gradientxyz: torch.Tensor = depth_to_3d_v2(depth.squeeze(1), camera_matrix, normalize_points).permute(0, 3, 1, 2) # Bx3xHxW+ dtype = dtype if dtype.is_floating_point else xyz.dtype- # compute the pointcloud spatial gradients- gradients: torch.Tensor = spatial_gradient(xyz) # Bx3x2xHxW+ # Keep the gradient convolution in the point-cloud dtype under autocast.+ with _autocast_disabled(xyz.device.type):+ gradients: torch.Tensor = spatial_gradient(xyz) # Bx3x2xHxW# Rearrange to (B, H, W, 3) before cross product so the 3 XYZ components are# contiguous in memory. Cross product along dim=1 on a (B,3,H,W) tensor strides@@ -288,7 +301,7 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalizeb: torch.Tensor = gradients[:, :, 1].permute(0, 2, 3, 1).contiguous() # BxHxWx3normals: torch.Tensor = torch.linalg.cross(a, b, dim=-1) # BxHxWx3- return F.normalize(normals, dim=-1, p=2).permute(0, 3, 1, 2) # Bx3xHxW+ return F.normalize(normals, dim=-1, p=2).to(dtype).permute(0, 3, 1, 2) # Bx3xHxWdef depth_from_plane_equation(diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex c5e16cfab..52211377e 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -183,7 +183,6 @@ call builtins.AssertionError tests/geometry/test_conversions.py::TestRotationMatcall builtins.AssertionError tests/geometry/test_conversions.py::TestRotationMatrixToAngleAxis::test_rotation_matrix_to_axis_angle[cpu-bfloat16]call builtins.AssertionError tests/geometry/test_conversions.py::TestRotationMatrixToQuaternion::test_corner_case[cpu-bfloat16]call builtins.AssertionError tests/geometry/test_depth.py::TestDepthTo3d::test_unproject_normalized[cpu-bfloat16]-call builtins.AssertionError tests/geometry/test_depth.py::TestDepthToNormals::test_simple_normalized[cpu-bfloat16]call builtins.AssertionError tests/geometry/test_depth.py::TestWarpFrameDepth::test_translation_normalized[cpu-bfloat16]call builtins.AssertionError tests/geometry/test_depth_warper.py::TestDepthWarper::test_compute_subpixel_step[cpu-bfloat16-1]call builtins.AssertionError tests/geometry/test_depth_warper.py::TestDepthWarper::test_compute_subpixel_step[cpu-bfloat16-2]diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex 3ff8830e1..828f187de 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -169,7 +169,6 @@ call builtins.AssertionError tests/geometry/test_conversions.py::TestRadDegConvecall builtins.AssertionError tests/geometry/test_conversions.py::TestRotationMatrixToAngleAxis::test_rand_quaternion_gradcheck[cpu-float16-5]call builtins.AssertionError tests/geometry/test_conversions.py::TestRotationMatrixToAngleAxis::test_rotation_matrix_to_axis_angle[cpu-float16]call builtins.AssertionError tests/geometry/test_conversions.py::TestRotationMatrixToQuaternion::test_corner_case[cpu-float16]-call builtins.AssertionError tests/geometry/test_depth.py::TestDepthToNormals::test_simple_normalized[cpu-float16]call builtins.AssertionError tests/geometry/test_depth.py::TestWarpFrameDepth::test_translation_normalized[cpu-float16]call builtins.AssertionError tests/geometry/test_depth_warper.py::TestDepthWarper::test_compute_subpixel_step[cpu-float16-1]call builtins.AssertionError tests/geometry/test_depth_warper.py::TestDepthWarper::test_compute_subpixel_step[cpu-float16-2]diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex d93c4dc40..f8faa10f0 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -336,6 +336,61 @@ class TestUnprojectMeshgrid(BaseTester):class TestDepthToNormals(BaseTester):+ @pytest.mark.parametrize("depth_value", [0.125, 0.25])+ def test_small_depth_plane(self, depth_value, device, dtype):+ depth = torch.full((1, 1, 16, 16), depth_value, device=device, dtype=dtype)+ camera_matrix = torch.tensor(+ [[[1000.0, 0.0, 7.5], [0.0, 1000.0, 7.5], [0.0, 0.0, 1.0]]], device=device, dtype=dtype+ )++ normals = depth_to_normals(depth, camera_matrix)++ expected = torch.zeros_like(normals)+ expected[:, 2] = 1.0+ assert normals.dtype == dtype+ assert normals.device == device+ self.assert_close(normals, expected)++ @pytest.mark.parametrize("depth_value", [0.125, 1e-5])+ def test_autocast_small_depth_plane(self, depth_value, device, dtype):+ depth = torch.full((1, 1, 16, 16), depth_value, device=device, dtype=dtype)+ camera_matrix = torch.tensor(+ [[[1000.0, 0.0, 7.5], [0.0, 1000.0, 7.5], [0.0, 0.0, 1.0]]], device=device, dtype=dtype+ )+ expected = depth_to_normals(depth, camera_matrix)++ with torch.autocast(device.type):+ normals = depth_to_normals(depth, camera_matrix)++ self.assert_close(normals, expected, rtol=0, atol=0)++ @pytest.mark.parametrize("camera_dtype", [torch.bfloat16, torch.float32], ids=["bfloat16", "float32"])+ def test_bfloat16_depth_wider_than_256_pixels(self, camera_dtype, device):+ # The pixel grid takes the depth dtype, and bfloat16 cannot hold column indices above 256.+ depth = torch.full((1, 1, 4, 320), 2.0, device=device, dtype=torch.bfloat16)+ camera_matrix = torch.tensor(+ [[[500.0, 0.0, 159.5], [0.0, 500.0, 1.5], [0.0, 0.0, 1.0]]], device=device, dtype=camera_dtype+ )++ normals = depth_to_normals(depth, camera_matrix)++ expected = torch.zeros_like(normals)+ expected[:, 2] = 1.0+ assert normals.dtype == torch.promote_types(torch.bfloat16, camera_dtype)+ self.assert_close(normals, expected)++ @pytest.mark.parametrize("input_dtype", [torch.int32, torch.int64])+ def test_integer_depth_plane(self, input_dtype, device):+ depth = torch.tensor([[[[12, 6, 4, 3]]]], device=device, dtype=input_dtype).expand(1, 1, 4, 4)+ camera_matrix = torch.eye(3, device=device, dtype=input_dtype)[None]++ normals = depth_to_normals(depth, camera_matrix)++ # These points lie on X + Z = 12, with normal (1, 0, 1) / sqrt(2) pointing away from the camera.+ expected = torch.tensor([1.0, 0.0, 1.0], device=device, dtype=torch.get_default_dtype()) / 2**0.5+ assert normals.dtype == expected.dtype+ self.assert_close(normals, expected.view(1, 3, 1, 1).expand_as(normals))+@pytest.mark.parametrize(("height", "width"), [(1, 3), (3, 1), (1, 1), (0, 3), (3, 0), (0, 0)])@pytest.mark.parametrize("normalize_points", [False, True])def test_convention_normals_require_two_spatial_axes_4398(self, height, width, normalize_points, device, dtype):