Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(camera): Avoid float16 reciprocal backward overflow (#5708)

A Aswanth Raj50180de2127d
diff --git a/changelog.d/5708.fixed.md b/changelog.d/5708.fixed.md
new file mode 100644
index 000000000..1c3150b39
--- /dev/null
+++ b/changelog.d/5708.fixed.md
@@ -0,0 +1 @@
+`distort_points_kannala_brandt` no longer returns -inf/NaN float16 point gradients for points at a small nonzero normalized radius (below about 4e-3). Its outputs, its camera-parameter gradients and the other dtypes are unchanged.
diff --git a/kornia/geometry/camera/distortion_kannala_brandt.py b/kornia/geometry/camera/distortion_kannala_brandt.py
index 5fb3c1d60..a4f1bf59a 100644
--- a/kornia/geometry/camera/distortion_kannala_brandt.py
+++ b/kornia/geometry/camera/distortion_kannala_brandt.py
@@ -46,7 +46,8 @@ def _distort_points_kannala_brandt_impl(
# Their radius is moved to about 1 and their angle zeroed. The active lanes add 0 and multiply by 1,
# so they are unchanged, and this avoids two torch.where calls (slow on MPS).
radius = (radius_sq + ~nonlinear_mask).sqrt()
- radius_inverse = 1.0 / radius
+ # The reciprocal's backward squares its value, which can overflow float16.
+ radius_inverse = (1.0 / radius.float()).to(radius.dtype) if radius.dtype == torch.float16 else 1.0 / radius
theta = radius.atan2(torch.ones_like(radius)) * nonlinear_mask
theta2 = theta**2
theta4 = theta2**2
diff --git a/tests/geometry/camera/test_distortion.py b/tests/geometry/camera/test_distortion.py
index f5b1e54ba..941e86d65 100644
--- a/tests/geometry/camera/test_distortion.py
+++ b/tests/geometry/camera/test_distortion.py
@@ -239,6 +239,56 @@ class TestDistortionKannalaBrandt(BaseTester):
)
self.assert_close(dx_distort_points_kannala_brandt(points, params), expected)
+ @pytest.mark.parametrize("radius", [2e-4, 1e-3, 3e-3, 4e-3])
+ @pytest.mark.parametrize("shared_params", [True, False])
+ def test_small_radius_gradients(self, device, dtype, radius, shared_params) -> None:
+ points = torch.tensor([[radius, 0.0], [0.0, radius], [-radius, radius]], device=device, dtype=dtype)
+ params = torch.tensor([600.0, 500.0, 320.0, 240.0, 0.1, -0.05, 0.01, -0.001], device=device, dtype=dtype)
+ if not shared_params:
+ params = params.repeat(3, 1)
+ points.requires_grad_()
+ params.requires_grad_()
+
+ output = distort_points_kannala_brandt(points, params)
+ point_grad, params_grad = torch.autograd.grad(output.sum(), (points, params))
+
+ reference_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ reference_points = points.detach().to(reference_dtype).requires_grad_()
+ reference_params = params.detach().to(reference_dtype).requires_grad_()
+ reference_output = distort_points_kannala_brandt(reference_points, reference_params)
+ _, expected_params_grad = torch.autograd.grad(reference_output.sum(), (reference_points, reference_params))
+ expected_point_grad = dx_distort_points_kannala_brandt(
+ reference_points.detach(), reference_params.detach()
+ ).sum(-2)
+
+ assert output.dtype == dtype
+ assert output.device == device
+ assert torch.isfinite(point_grad).all()
+ assert torch.isfinite(params_grad).all()
+ self.assert_close(output, reference_output.to(dtype))
+ self.assert_close(point_grad, expected_point_grad.to(dtype))
+ self.assert_close(params_grad, expected_params_grad.to(dtype))
+
+ def test_small_radius_gradients_dynamo(self, device, dtype, torch_optimizer) -> None:
+ points = torch.tensor([[1e-3, 0.0], [0.0, 1e-3]], device=device, dtype=dtype, requires_grad=True)
+ params = torch.tensor([600.0, 500.0, 320.0, 240.0, 0.1, -0.05, 0.01, -0.001], device=device, dtype=dtype)
+ compiled = torch_optimizer(distort_points_kannala_brandt)
+ point_grad = torch.autograd.grad(compiled(points, params).sum(), points)[0]
+ self.assert_close(point_grad, params[:2].expand_as(points))
+
+ def test_shared_calibration_gradient(self, device, dtype) -> None:
+ points = torch.tensor([0.25, -0.4], device=device, dtype=dtype).expand(2, 3, 2)
+ params = torch.tensor(
+ [600.0, 500.0, 320.0, 240.0, 0.1, -0.05, 0.01, -0.001], device=device, dtype=dtype, requires_grad=True
+ )
+ actual = torch.autograd.grad(distort_points_kannala_brandt(points, params).sum(), params)[0]
+ reference_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ reference_params = params.detach().to(reference_dtype).requires_grad_()
+ reference_output = distort_points_kannala_brandt(points.to(reference_dtype), reference_params)
+ expected = torch.autograd.grad(reference_output.sum(), reference_params)[0]
+ # The small k1 derivative exposes extra rounding during accumulation.
+ self.assert_close(actual[5], expected[5].to(dtype))
+
def test_exception(self, device, dtype) -> None:
from kornia.core.exceptions import ShapeError