π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): prevent NaN Welsch gradients for half inputs (#5777)
Karnajeet Gosavid337dab50869
diff --git a/changelog.d/5777.fixed.md b/changelog.d/5777.fixed.mdnew file mode 100644index 000000000..43ae91299--- /dev/null+++ b/changelog.d/5777.fixed.md@@ -0,0 +1 @@+`welsch_loss` now evaluates float16 and bfloat16 inputs in float32 and returns the input dtype, like `charbonnier_loss`, `cauchy_loss` and `geman_mcclure_loss`: finite float16 inputs whose difference is outside the float16 range no longer give NaN gradients, and half-precision losses are the float32 values rounded once.diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.pyindex 2fa7e237f..9b6b966c0 100644--- a/kornia/losses/charbonnier.py+++ b/kornia/losses/charbonnier.py@@ -58,9 +58,9 @@ def charbonnier_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "n- The losses are symmetric in ``img1`` and ``img2``, which must have the same shape, without broadcasting,and the same device. The default ``reduction='none'`` returns the loss of every element, in the shape ofthe inputs.- - This loss, :func:`~kornia.losses.cauchy_loss` and :func:`~kornia.losses.geman_mcclure_loss` evaluate- float16 and bfloat16 inputs in float32, gradients included, and return the input dtype;- :func:`~kornia.losses.welsch_loss` does not upcast them.+ - This loss, :func:`~kornia.losses.cauchy_loss`, :func:`~kornia.losses.geman_mcclure_loss` and+ :func:`~kornia.losses.welsch_loss` evaluate float16 and bfloat16 inputs in float32, gradients included, and+ return the input dtype.Args:img1: the predicted torch.Tensor with shape :math:`(*)`.diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.pyindex 977f0507b..7ad91c66a 100644--- a/kornia/losses/welsch.py+++ b/kornia/losses/welsch.py@@ -78,7 +78,9 @@ def welsch_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")# 1 - exp(-s) cancels for small s = r^2 / 2. There it equals 2 t / (1 + t) with t = tanh(s / 2), which does not# cancel; torch.expm1 has only the precision of exp(x) - 1 on MPS (pytorch/pytorch#198708) and in ONNX export.# The exp form is kept for r^2 >= 1, where it is accurate and keeps the gradient of the saturating loss.- squared = (img1 - img2) ** 2+ output_dtype = torch.promote_types(img1.dtype, img2.dtype)+ diff = img1.float() - img2.float() if output_dtype in (torch.float16, torch.bfloat16) else img1 - img2+ squared = diff**2t = torch.tanh(0.25 * squared)loss = torch.where(squared < 1.0, 2.0 * t / (1.0 + t), 1.0 - (-0.5 * squared).exp())@@ -92,7 +94,7 @@ def welsch_loss(img1: torch.Tensor, img2: torch.Tensor, reduction: str = "none")else:raise NotImplementedError("Invalid reduction option.")- return loss+ return loss.to(output_dtype) if output_dtype in (torch.float16, torch.bfloat16) else lossclass WelschLoss(nn.Module):diff --git a/tests/losses/test_charbonnier.py b/tests/losses/test_charbonnier.pyindex a63adcb01..ae8590312 100644--- a/tests/losses/test_charbonnier.py+++ b/tests/losses/test_charbonnier.py@@ -262,16 +262,10 @@ class TestConventionsRobustLosses(BaseTester):def test_convention_robust_loss_half_precision_compute_dtype(self, loss_fn, device, dtype):if dtype not in (torch.float16, torch.bfloat16):pytest.skip("only half-precision inputs can be evaluated in another dtype")- # Charbonnier, Cauchy and Geman-McClure evaluate half-precision inputs in float32 and round once; their- # gradients are pinned in test_robust.py. Welsch does not upcast, so in eager mode some of these 641 values- # round differently from the float32 evaluation (46 to 68 on arm64 CPU and MPS). This pin runs eagerly:- # inductor keeps fused intermediates in float32, and compiled Welsch matches the float32 evaluation on the- # same grid (torch 2.14, CPU and MPS). All four return the input dtype.+ # All four losses evaluate half-precision inputs in float32 and round once; their gradients are pinned in+ # test_robust.py and test_welcsh.py. This pin runs eagerly and all four return the input dtype.residual = torch.linspace(-8.0, 8.0, 641, device=device, dtype=dtype)out = loss_fn(residual, torch.zeros_like(residual))assert out.dtype == dtypein_float32 = loss_fn(residual.float(), torch.zeros_like(residual, dtype=torch.float32)).to(dtype)- if loss_fn is kornia.losses.welsch_loss:- assert not torch.equal(out, in_float32)- else:- self.assert_close(out, in_float32, rtol=0, atol=0)+ self.assert_close(out, in_float32, rtol=0, atol=0)diff --git a/tests/losses/test_robust_residual.py b/tests/losses/test_robust_residual.pyindex 9343120b3..1991f9f2f 100644--- a/tests/losses/test_robust_residual.py+++ b/tests/losses/test_robust_residual.py@@ -49,7 +49,7 @@ class TestRobustResidual(BaseTester):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"])+ @pytest.mark.parametrize("loss_name", ["cauchy_loss", "charbonnier_loss", "geman_mcclure_loss", "welsch_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)@@ -57,9 +57,21 @@ class TestRobustResidual(BaseTester):"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()),+ "welsch_loss": -torch.expm1(-delta.square() / 2),}[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_pointself.assert_close(loss.cpu().double(), expected, rtol=1e-6, atol=1e-6)++ @pytest.mark.parametrize("loss_name", ["cauchy_loss", "charbonnier_loss", "geman_mcclure_loss", "welsch_loss"])+ def test_half_with_float32_returns_float32(self, device, loss_name):+ # A half-precision operand with a float32 one promotes to float32, in either order, as torch does.+ half = torch.tensor([40000.0, 1.0], device=device, dtype=torch.float16)+ single = torch.tensor([-40000.0, 0.5], device=device, dtype=torch.float32)+ loss_fn = getattr(kornia.losses, loss_name)+ expected = loss_fn(half.float(), single)+ for actual in (loss_fn(half, single), loss_fn(single, half)):+ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, rtol=0, atol=0)diff --git a/tests/losses/test_welcsh.py b/tests/losses/test_welcsh.pyindex 4e6e0d8d0..44a7628fd 100644--- a/tests/losses/test_welcsh.py+++ b/tests/losses/test_welcsh.py@@ -98,7 +98,8 @@ class TestWelschLoss(BaseTester):self.assert_close(actual, kornia.losses.welsch_loss(img2, img1, reduction), rtol=0, atol=0)grad1, grad2 = torch.autograd.grad(actual.sum(), (img1, img2))- expected_grad = img1.detach() * (-0.5 * img1.detach().square()).exp()+ grad_input = img1.detach().float() if dtype in (torch.float16, torch.bfloat16) else img1.detach()+ expected_grad = (grad_input * (-0.5 * grad_input.square()).exp()).to(dtype)if reduction == "mean":expected_grad = expected_grad / img1.numel()assert torch.isfinite(grad1).all()@@ -129,12 +130,30 @@ class TestWelschLoss(BaseTester):self.assert_close(actual, expected, rtol=4 * torch.finfo(dtype).eps, atol=0)self.assert_close(actual, kornia.losses.welsch_loss(img2, img1), rtol=0, atol=0)grad1, grad2 = torch.autograd.grad(actual.sum(), (img1, img2))- expected_grad = img1.detach() * (-0.5 * img1.detach().square()).exp()+ grad_input = img1.detach().float() if dtype in (torch.float16, torch.bfloat16) else img1.detach()+ expected_grad = (grad_input * (-0.5 * grad_input.square()).exp()).to(dtype)assert torch.isfinite(grad1).all()assert torch.isfinite(grad2).all()self.assert_close(grad1, expected_grad, rtol=4 * torch.finfo(dtype).eps, atol=0)self.assert_close(grad2, -expected_grad, rtol=4 * torch.finfo(dtype).eps, atol=0)+ def test_opposite_large_inputs(self, device, dtype):+ pred = torch.tensor([40000.0, 1.0], device=device, dtype=dtype, requires_grad=True)+ target = torch.tensor([-40000.0, 0.5], device=device, dtype=dtype, requires_grad=True)+ residual = pred.detach().cpu().double() - target.detach().cpu().double()+ expected = -torch.expm1(-0.5 * residual.square())+ expected_grad = residual * (-0.5 * residual.square()).exp()++ actual = kornia.losses.welsch_loss(pred, target)+ assert actual.dtype == dtype+ assert actual.device == device+ self.assert_close(actual, expected.to(device=device, dtype=dtype))+ grad_pred, grad_target = torch.autograd.grad(actual.sum(), (pred, target))+ assert torch.isfinite(grad_pred).all()+ assert torch.isfinite(grad_target).all()+ self.assert_close(grad_pred, expected_grad.to(device=device, dtype=dtype))+ self.assert_close(grad_target, -expected_grad.to(device=device, dtype=dtype))+@pytest.mark.parametrize("reduction", ["mean", "sum"])@pytest.mark.parametrize("shape", [(1, 2, 9, 9), (2, 4, 3, 6)])def test_perfect_prediction(self, device, dtype, reduction, shape):