Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Keep half-precision Jensen-Shannon mixtures representable (#5771)

AhmetHakanBezir15bbdb7633d1
diff --git a/changelog.d/5771.fixed.md b/changelog.d/5771.fixed.md
new file mode 100644
index 000000000..91001c1f3
--- /dev/null
+++ b/changelog.d/5771.fixed.md
@@ -0,0 +1 @@
+`js_div_loss_2d` evaluates float16 and bfloat16 inputs in float32 before forming the mixture, avoiding infinite loss and non-finite gradients for small positive probabilities while preserving the output dtype.
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index ad9bbd6f3..50ccadaa9 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -43,8 +43,14 @@ def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
# JSD(P || Q)
+ output_dtype = torch.promote_types(p.dtype, q.dtype)
+ # Halving a positive subnormal in the input dtype can make the mixture zero.
+ if p.dtype in (torch.float16, torch.bfloat16):
+ p = p.float()
+ if q.dtype in (torch.float16, torch.bfloat16):
+ q = q.float()
m = 0.5 * (p + q)
- return 0.5 * _kl_div_2d(p, m) + 0.5 * _kl_div_2d(q, m)
+ return (0.5 * _kl_div_2d(p, m) + 0.5 * _kl_div_2d(q, m)).to(output_dtype)
# TODO: add this to the main module
@@ -74,6 +80,8 @@ def js_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "m
inputs and the reductions are those of :func:`~kornia.losses.kl_div_loss_2d`; see its Convention block.
- A cell that is zero in both inputs contributes zero, including to the gradients. Both inputs must have
the same shape; unsupported reductions raise ``NotImplementedError``.
+ - Float16 and bfloat16 inputs are evaluated in float32 to avoid underflow of the mixture probabilities.
+ The returned loss retains the promoted input dtype.
Args:
pred: the input torch.Tensor with shape :math:`(B, N, H, W)`.
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 7ec15925a..f61cbd6f3 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -289,7 +289,6 @@ call builtins.AssertionError tests/geometry/liegroup/test_so3.py::TestSo3::test_
call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_normalized_coordinates[cpu-bfloat16]
call builtins.AssertionError tests/geometry/subpix/test_dsnt.py::TestRenderGaussian2d::test_pixel_coordinates[cpu-bfloat16]
call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestConvQuadInterp3dModule::test_diag[cpu-bfloat16]
-call builtins.AssertionError tests/geometry/subpix/test_spatial_softargmax.py::TestSpatialSoftArgmax2d::test_end_to_end[cpu-bfloat16]
call builtins.AssertionError tests/geometry/test_bbox.py::TestTransformBoxes2D::test_transform_boxes[cpu-bfloat16]
call builtins.AssertionError tests/geometry/test_bbox.py::TestTransformBoxes2D::test_transform_boxes_wh[cpu-bfloat16]
call builtins.AssertionError tests/geometry/test_bbox.py::TestTransformBoxes2D::test_transform_multiple_boxes[cpu-bfloat16]
diff --git a/tests/losses/test_divergence.py b/tests/losses/test_divergence.py
index acd812d4e..4f27de06e 100644
--- a/tests/losses/test_divergence.py
+++ b/tests/losses/test_divergence.py
@@ -27,6 +27,25 @@ from testing.base import BaseTester
class TestDivergenceLoss(BaseTester):
+ def test_js_div_loss_2d_small_probability(self, device, dtype):
+ # The mixture must not round a positive half-precision probability down to zero.
+ tiny = torch.finfo(dtype).tiny * torch.finfo(dtype).eps if dtype == torch.bfloat16 else 2.0**-24
+ pred = torch.tensor([[[[tiny, 0.0, 0.25, 0.75]]]], device=device, dtype=dtype, requires_grad=True)
+ target = torch.tensor([[[[0.0, tiny, 0.75, 0.25]]]], device=device, dtype=dtype, requires_grad=True)
+
+ loss = kornia.losses.js_div_loss_2d(pred, target)
+ expected = 0.25 * math.log(0.5) + 0.75 * math.log(1.5) + tiny * math.log(2.0)
+ self.assert_close(loss, torch.tensor(expected, device=device, dtype=dtype))
+ assert loss.dtype == dtype
+
+ loss.backward()
+ assert torch.isfinite(pred.grad).all()
+ assert torch.isfinite(target.grad).all()
+ # On positive cells, dJSD/dp = log(2p / (p + q)) / 2.
+ expected_grad = torch.tensor([math.log(2.0), math.log(0.5), math.log(1.5)], device=device, dtype=dtype) / 2
+ self.assert_close(pred.grad[0, 0, 0, [0, 2, 3]], expected_grad)
+ self.assert_close(target.grad[0, 0, 0, [1, 3, 2]], expected_grad)
+
@pytest.mark.parametrize(
"pred,target,expected",
[