π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): skip the Hausdorff range check under any capture (#5712)
Adarsh Mishrafa65b7cc5940
diff --git a/changelog.d/5712.fixed.md b/changelog.d/5712.fixed.mdnew file mode 100644index 000000000..1f1a10b89--- /dev/null+++ b/changelog.d/5712.fixed.md@@ -0,0 +1 @@+`HausdorffERLoss` and `HausdorffERLoss3D` now trace under `torch.compile(fullgraph=True)` on torch 2.14: their data-dependent label-range check is skipped wherever a graph captures the call, as it already was under `torch.export`. Eager calls still raise on an out-of-range label; a captured call now scores such a voxel in no class and returns a finite loss instead of raising.diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.pyindex cdbf45585..521a5f55f 100644--- a/kornia/losses/hausdorff.py+++ b/kornia/losses/hausdorff.py@@ -22,7 +22,7 @@ from typing import Callableimport torchfrom torch import nn-from kornia.core.utils import is_exporting+from kornia.core.utils import is_compilingclass _HausdorffERLossBase(nn.Module):@@ -115,8 +115,9 @@ class _HausdorffERLossBase(nn.Module):if target.dtype != torch.long:raise ValueError(f"Expect long type target value in range [0, {pred.size(1)}). Got {target.dtype}.")- # The range check reads the data, which graph capture cannot do; skip it under export.- if not is_exporting() and not (target.max() < pred.size(1) and target.min() >= 0):+ # The range check reads the data, which graph capture cannot do; skip it under any capture.+ # Neither Hausdorff loss scripts on main (its ``super().forward``), so no TorchScript guard is needed.+ if not is_compiling() and not (target.max() < pred.size(1) and target.min() >= 0):raise ValueError(f"Expect long type target value in range [0, {pred.size(1)}). ({target.min()}, {target.max()})")@@ -173,6 +174,9 @@ class HausdorffERLoss(_HausdorffERLossBase):- ``pred`` holds per-class probabilities ``(B, C, H, W)`` and nothing is applied to it, unlike the logits of:func:`~kornia.losses.focal_loss`: pass a softmax. ``target`` holds int64 labels ``(B, 1, H, W)`` in``[0, C)``. Channel ``c`` is compared with ``target == c``, class 0 included.+ - The ``[0, C)`` check reads the data, so it is skipped wherever the call captures a graph+ (``torch.compile`` or ``torch.export``). A captured call whose target holds an out-of-range label scores+ those voxels in no class and returns a finite loss instead of raising; an eager call still raises.- ``reduction='none'`` returns ``(C, B, 1, H, W)``, class axis first; the default ``'mean'`` is the plainmean of that tensor.- Each of the ``k`` erosions is min-max normalised per image and class and weighted bydiff --git a/tests/losses/test_hd.py b/tests/losses/test_hd.pyindex dbc368603..b38e5ede2 100644--- a/tests/losses/test_hd.py+++ b/tests/losses/test_hd.py@@ -19,8 +19,17 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_version_lt-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available++# The guard these tests pin (#5037) is only exercised where the two capture flags differ: from torch 2.14, Dynamo+# no longer folds the export flag to True inside torch.compile. On older releases it already did, as on 2.5.1 where+# kornia's helper falls back to is_compiling().+_CAPTURE_UNAVAILABLE_REASON = (+ f"{DYNAMO_UNAVAILABLE_REASON}, and before torch 2.14 the export flag was already True under torch.compile, "+ "so the guard made no difference there (#5037)"+)class TestHausdorffLoss(BaseTester):@@ -179,6 +188,37 @@ class TestHausdorffLoss(BaseTester):self.gradcheck(loss, (logits, labels), dtypes=[torch.float64, torch.int64])+ @pytest.mark.skipif(not dynamo_is_available() or torch_version_lt(2, 14, 0), reason=_CAPTURE_UNAVAILABLE_REASON)+ @pytest.mark.parametrize(+ "hd,shape", [(kornia.losses.HausdorffERLoss, (10, 10)), (kornia.losses.HausdorffERLoss3D, (5, 5, 5))]+ )+ def test_trace_labels_like_eager(self, hd, shape, device, dtype):+ # The range check reads the data, so any capture has to skip it, not only export (#5037).+ from torch._dynamo.testing import CompileCounter++ num_classes = 3+ logits = torch.rand(2, num_classes, *shape, device=device, dtype=dtype)+ labels = (torch.rand(2, 1, *shape, device=device) * (num_classes - 1)).long()+ counter = CompileCounter()+ torch._dynamo.reset()+ traced = torch.compile(hd(), backend=counter, fullgraph=True)+ self.assert_close(traced(logits, labels), hd()(logits, labels), rtol=0, atol=0)+ assert counter.frame_count == 1++ @pytest.mark.skipif(not dynamo_is_available() or torch_version_lt(2, 14, 0), reason=_CAPTURE_UNAVAILABLE_REASON)+ def test_trace_scores_out_of_range_like_export(self, device, dtype):+ # Export already scored an out-of-range label in no class, and a traced call now does the same instead of+ # raising; that is the behaviour change #5037 accepts. An eager call keeps raising.+ num_classes = 3+ logits = torch.rand(2, num_classes, 10, 10, device=device, dtype=dtype)+ labels = torch.full((2, 1, 10, 10), num_classes, dtype=torch.long, device=device)+ with pytest.raises(ValueError, match="Expect long type target value in range"):+ kornia.losses.HausdorffERLoss()(logits, labels)+ exported = torch.export.export(kornia.losses.HausdorffERLoss(), (logits, labels)).module()(logits, labels)+ torch._dynamo.reset()+ traced = torch.compile(kornia.losses.HausdorffERLoss(), backend="eager", fullgraph=True)(logits, labels)+ self.assert_close(traced, exported, rtol=0, atol=0)+class TestConventionsHausdorffERLoss(BaseTester):"""Pins for the input form, output layout and per-image scoring of the Hausdorff erosion losses."""