π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Promote half inputs before robust loss subtraction (#5772)
AhmetHakanBezir74f7dfb46d71
diff --git a/changelog.d/5772.fixed.md b/changelog.d/5772.fixed.mdnew file mode 100644index 000000000..c74791913--- /dev/null+++ b/changelog.d/5772.fixed.md@@ -0,0 +1 @@+`cauchy_loss`, `charbonnier_loss`, and `geman_mcclure_loss` promote half-precision inputs before subtracting them, avoiding spurious infinite/NaN losses and NaN gradients when finite inputs have a residual outside the float16 range.diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.pyindex 7abc75c6e..58c2f8cb0 100644--- a/kornia/losses/cauchy.py+++ b/kornia/losses/cauchy.py@@ -76,8 +76,8 @@ def cauchy_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none"))# Keep the square and its backward in float32 for half-precision residuals.- diff = img1 - img2- compute_diff = diff.float() if diff.dtype in (torch.float16, torch.bfloat16) else diff+ output_dtype = torch.promote_types(img1.dtype, img2.dtype)+ compute_diff = img1.float() - img2.float() if output_dtype in (torch.float16, torch.bfloat16) else img1 - img2loss = torch.log1p(0.5 * torch.square(compute_diff))# perform reduction@@ -90,7 +90,7 @@ def cauchy_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")else:raise NotImplementedError("Invalid reduction option.")- return loss.to(diff.dtype) if diff.dtype in (torch.float16, torch.bfloat16) else loss+ return loss.to(output_dtype) if output_dtype in (torch.float16, torch.bfloat16) else lossclass CauchyLoss(nn.Module):diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.pyindex f64a1d9b4..2fa7e237f 100644--- a/kornia/losses/charbonnier.py+++ b/kornia/losses/charbonnier.py@@ -94,8 +94,8 @@ def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "n)# Keep the square and its backward in float32 for half-precision residuals.- diff = img1 - img2- compute_diff = diff.float() if diff.dtype in (torch.float16, torch.bfloat16) else diff+ output_dtype = torch.promote_types(img1.dtype, img2.dtype)+ compute_diff = img1.float() - img2.float() if output_dtype in (torch.float16, torch.bfloat16) else img1 - img2# Rationalize small residuals to avoid subtracting two nearly equal numbers.# Keep the original large-residual branch, including its behavior when the square overflows.squared = compute_diff**2@@ -117,7 +117,7 @@ def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "nelse:raise NotImplementedError("Invalid reduction option.")- return loss.to(diff.dtype) if diff.dtype in (torch.float16, torch.bfloat16) else loss+ return loss.to(output_dtype) if output_dtype in (torch.float16, torch.bfloat16) else lossclass CharbonnierLoss(nn.Module):diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.pyindex c78c32c2e..e1af1f47b 100644--- a/kornia/losses/geman_mcclure.py+++ b/kornia/losses/geman_mcclure.py@@ -76,8 +76,8 @@ def geman_mcclure_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str =)# Keep the square, doubled numerator and their backward in float32 for half-precision residuals.- diff = img1 - img2- compute_diff = diff.float() if diff.dtype in (torch.float16, torch.bfloat16) else diff+ output_dtype = torch.promote_types(img1.dtype, img2.dtype)+ compute_diff = img1.float() - img2.float() if output_dtype in (torch.float16, torch.bfloat16) else img1 - img2diff2 = torch.square(compute_diff)loss = 2.0 * diff2 / (diff2 + 4.0)@@ -91,7 +91,7 @@ def geman_mcclure_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str =else:raise NotImplementedError("Invalid reduction option.")- return loss.to(diff.dtype) if diff.dtype in (torch.float16, torch.bfloat16) else loss+ return loss.to(output_dtype) if output_dtype in (torch.float16, torch.bfloat16) else lossclass GemanMcclureLoss(nn.Module):diff --git a/tests/losses/test_robust_residual.py b/tests/losses/test_robust_residual.pynew file mode 100644index 000000000..9343120b3--- /dev/null+++ b/tests/losses/test_robust_residual.py@@ -0,0 +1,65 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++import kornia++from testing.base import BaseTester+++class TestRobustResidual(BaseTester):+ @pytest.mark.parametrize("loss_name", ["cauchy_loss", "charbonnier_loss", "geman_mcclure_loss"])+ def test_opposite_large_inputs(self, device, dtype, loss_name):+ pred = torch.tensor([40000.0, -40000.0], device=device, dtype=dtype, requires_grad=True)+ target = (-pred.detach()).requires_grad_()+ delta = pred.detach().cpu().double() - target.detach().cpu().double()+ if loss_name == "cauchy_loss":+ expected = torch.log1p(delta.square() / 2)+ expected_grad = delta / (1 + delta.square() / 2)+ elif loss_name == "charbonnier_loss":+ norm = torch.hypot(delta, torch.ones_like(delta))+ expected = norm - 1+ expected_grad = delta / norm+ else:+ expected = 2 / (1 + 4 / delta.square())+ expected_grad = 16 * delta / (delta.square() + 4).square()++ actual = getattr(kornia.losses, loss_name)(pred, target)+ self.assert_close(actual, expected.to(pred))+ assert actual.dtype == dtype+ actual.sum().backward()+ assert torch.isfinite(pred.grad).all()+ assert torch.isfinite(target.grad).all()+ self.assert_close(pred.grad, expected_grad.to(pred))+ self.assert_close(target.grad, -expected_grad.to(pred))++ @pytest.mark.parametrize("loss_name", ["cauchy_loss", "charbonnier_loss", "geman_mcclure_loss"])+ def test_integer_inputs_keep_a_floating_loss(self, device, loss_name):+ # Only half-precision losses are cast back to the input dtype; an integer residual gives a float loss.+ delta = torch.tensor([1.0, 3.0], dtype=torch.float64)+ expected = {+ "cauchy_loss": torch.log1p(delta.square() / 2),+ "charbonnier_loss": torch.hypot(delta, torch.ones_like(delta)) - 1,+ "geman_mcclure_loss": 2 / (1 + 4 / delta.square()),+ }[loss_name]+ loss = getattr(kornia.losses, loss_name)(+ torch.tensor([1, 3], device=device), torch.tensor([0, 0], device=device)+ )+ assert loss.dtype.is_floating_point+ self.assert_close(loss.cpu().double(), expected, rtol=1e-6, atol=1e-6)