Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): preserve KL logarithms under autocast (#6387)

AhmetHakanBezir104112464c5b
diff --git a/changelog.d/6387.fixed.md b/changelog.d/6387.fixed.md
new file mode 100644
index 000000000..024ea139b
--- /dev/null
+++ b/changelog.d/6387.fixed.md
@@ -0,0 +1 @@
+Under CPU autocast, `kl_div_loss_2d` took the logarithm of a float16/bfloat16 `pred` in half precision before `F.kl_div` promoted to float32, so two identical bfloat16 heatmaps gave a divergence of about `1e-3` instead of `0`, and other values were off by a similar amount. The logarithm is now taken in float32 there, as CUDA and MPS autocast already did. Results outside autocast and on other devices are unchanged.
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index c99db9278..00adf21ba 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -36,7 +36,16 @@ def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
empty = (p == 0) & (q >= 0) & torch.isfinite(q)
p = p.masked_fill(empty, 1.0)
q = q.masked_fill(empty, 1.0)
- unsummed_kl = F.kl_div(q.log(), p, reduction="none")
+ # CPU autocast runs kl_div in float32 but leaves log in half precision, so the logarithm of a half q would be
+ # rounded before kl_div promotes it. CUDA and MPS autocast already run log in float32.
+ if torch.jit.is_scripting():
+ # Keep the original scripted graph; its autocast state queries have no device argument.
+ log_q = q.log()
+ else:
+ if q.dtype in (torch.float16, torch.bfloat16) and q.device.type == "cpu" and torch.is_autocast_enabled("cpu"):
+ q = q.float()
+ log_q = q.log()
+ unsummed_kl = F.kl_div(log_q, p, reduction="none")
return unsummed_kl.sum(-1).view(batch, chans)
@@ -119,6 +128,8 @@ def kl_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "m
- Both inputs must have the same shape. Unsupported reductions, including torch's ``'batchmean'``, raise
``NotImplementedError``. A zero in ``target`` with a finite nonnegative ``pred`` contributes zero to the
value and gradients, including when both entries are zero.
+ - Under CPU autocast, the logarithm of a float16/bfloat16 ``pred`` is taken in float32, as CUDA and MPS
+ autocast already do; ``F.kl_div`` alone would promote to float32 only after that logarithm had been rounded.
Args:
pred: the input torch.Tensor with shape ``(B, N, H, W)``.
diff --git a/tests/losses/test_divergence.py b/tests/losses/test_divergence.py
index 4f27de06e..19932c90d 100644
--- a/tests/losses/test_divergence.py
+++ b/tests/losses/test_divergence.py
@@ -27,6 +27,52 @@ from testing.base import BaseTester
class TestDivergenceLoss(BaseTester):
+ @pytest.mark.parametrize("amp_dtype", [torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("identical", [False, True])
+ def test_kl_autocast(self, amp_dtype, identical, device):
+ """Evaluate half heatmap logarithms at the precision used by autocast KL divergence."""
+ if device.type != "cpu":
+ pytest.skip("only CPU autocast leaves log in half precision; CUDA and MPS autocast run it in float32")
+ generator = torch.Generator().manual_seed(0)
+ target = torch.randn(1, 2, 49, generator=generator).softmax(-1).reshape(1, 2, 7, 7)
+ target = target.to(device=device, dtype=amp_dtype)
+ pred = target.clone() if identical else target.roll(1, -1)
+ pred = pred.detach().requires_grad_()
+ target = target.detach().requires_grad_()
+ pred_ref = pred.detach().double().requires_grad_()
+ target_ref = target.detach().double().requires_grad_()
+ expected = (target_ref * (target_ref.log() - pred_ref.log())).sum((-2, -1)).mean()
+ with torch.autocast(device.type, dtype=amp_dtype):
+ actual = kornia.losses.kl_div_loss_2d(pred, target)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected.float(), rtol=1e-6, atol=1e-6)
+ gradients = torch.autograd.grad(actual, (pred, target))
+ references = torch.autograd.grad(expected, (pred_ref, target_ref))
+ for gradient, reference in zip(gradients, references):
+ self.assert_close(gradient, reference.to(amp_dtype))
+
+ @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64])
+ def test_kl_autocast_keeps_full_precision_inputs(self, input_dtype, device):
+ """Leave float32/float64 heatmaps untouched by the CPU autocast logarithm lift."""
+ if device.type != "cpu":
+ pytest.skip("checks the CPU autocast logarithm lift")
+ generator = torch.Generator().manual_seed(0)
+ target = torch.randn(1, 2, 49, generator=generator, dtype=input_dtype).softmax(-1).reshape(1, 2, 7, 7)
+ pred = target.roll(1, -1)
+ expected = kornia.losses.kl_div_loss_2d(pred, target)
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ actual = kornia.losses.kl_div_loss_2d(pred, target)
+ assert actual.dtype == input_dtype
+ assert torch.equal(actual, expected)
+
+ @pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])
+ def test_jit(self, loss, device, dtype):
+ """Keep both public divergence losses scriptable, including their empty-cell handling."""
+ pred = torch.tensor([0.0, 0.5, 0.25, 0.25], device=device, dtype=dtype).view(1, 1, 2, 2)
+ target = torch.tensor([0.0, 0.25, 0.75, 0.0], device=device, dtype=dtype).view(1, 1, 2, 2)
+ scripted = torch.jit.script(loss)
+ self.assert_close(scripted(pred, target), loss(pred, target))
+
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