Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(metrics): skip the data-dependent checks under any capture (#5704)

Adarsh Mishra2d32b21cfe81
diff --git a/changelog.d/5704.fixed.md b/changelog.d/5704.fixed.md
new file mode 100644
index 000000000..67f2175d5
--- /dev/null
+++ b/changelog.d/5704.fixed.md
@@ -0,0 +1 @@
+`confusion_matrix`, `mean_iou` and `mean_iou_bbox` now trace under `torch.compile(fullgraph=True)` on torch 2.14: their data-dependent label-range and box checks are skipped wherever `torch.compile` traces them, as they already were under `torch.export`. Eager calls still raise on an out-of-range label or an invalid box; a compiled `mean_iou_bbox` now gives an invalid box an IoU of 0 or NaN instead of raising.
diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.py
index 55ca219af..96596aff5 100644
--- a/kornia/metrics/confusion_matrix.py
+++ b/kornia/metrics/confusion_matrix.py
@@ -18,7 +18,7 @@
import torch
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
-from kornia.core.utils import is_exporting
+from kornia.core.utils import is_compiling
# Inspired by:
# https://github.com/pytorch/tnt/blob/master/torchnet/meter/confusionmeter.py#L68-L73
@@ -49,16 +49,15 @@ def confusion_matrix(
Convention:
- ``pred`` and ``target`` are class labels of the same shape, prediction first, in ``uint8`` or any signed
integer dtype; a bool tensor counts as the labels 0 and 1. A floating-point label tensor raises, and so does
- a label outside :math:`[0, K)`, unless the call is exported or compiled, which may skip the range check.
+ a label outside :math:`[0, K)`, unless graph capture traces the range check (``torch.export``,
+ ``torch.compile(fullgraph=True)``), which skips it: an out-of-range label is then counted in another cell
+ or makes the call fail.
- The first axis is always the batch: the result holds one :math:`(K, K)` float32 count matrix per sample,
:math:`(B, K, K)`, and is never pooled over the batch, so a flat :math:`(N,)` label vector gives :math:`N`
matrices that count one label each. Sum over the first axis for the matrix of a whole batch or dataset.
- Rows are the target and columns the prediction, ``cm[b, target, pred]``; swapping the two arguments
transposes every count matrix. :ref:`Losses and metrics <losses-metrics-conventions>` maps the matrix and
``normalized`` onto scikit-learn.
- - Known defect: the range check follows ``is_exporting()``, whose meaning under ``torch.compile`` depends on
- the torch version, so a compiled call can skip it and count an out-of-range prediction in another cell
- (`#5037 <https://github.com/kornia/kornia/issues/5037>`_).
Args:
pred: tensor with estimated targets returned by a
@@ -100,8 +99,8 @@ def confusion_matrix(
if batch_size == 0:
return torch.zeros(0, num_classes, num_classes, device=pred.device, dtype=torch.float32)
- # The range check reads the data, which graph capture cannot do; skip it under export.
- if not is_exporting() and pred.numel() > 0:
+ # The range check reads the data, which graph capture cannot do; skip it under any capture.
+ if not is_compiling() and pred.numel() > 0:
_check_label_range("pred", pred, num_classes)
_check_label_range("target", target, num_classes)
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index 1d0fd37aa..8d8eb6e00 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -17,7 +17,7 @@
import torch
-from kornia.core.utils import is_exporting
+from kornia.core.utils import is_compiling
from .confusion_matrix import confusion_matrix
@@ -116,11 +116,10 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str
nothing is averaged, and swapping the two sets transposes it.
- Boxes are exclusive in every ``box_format``: the area of ``(x1, y1, x2, y2)`` is
:math:`(x_2 - x_1)(y_2 - y_1)`, with no ``+ 1``, as in :func:`~kornia.geometry.bbox.nms`. A box with a
- non-positive width or height raises ``AssertionError``, unless the call is exported or compiled, which may
- skip the check. A :class:`~kornia.geometry.boxes.Boxes` gives the same IoU through ``to_tensor('xyxy')``,
- not through its inclusive ``'xyxy_plus'`` export.
- - Known defect: a compiled call can skip that check, and an invalid box then gives an IoU of 0 or NaN instead
- of raising (`#5037 <https://github.com/kornia/kornia/issues/5037>`_).
+ non-positive width or height raises ``AssertionError``, unless the call captures a graph
+ (``torch.compile`` or ``torch.export``), which skips the check and gives such a box an IoU of 0 or NaN. A
+ :class:`~kornia.geometry.boxes.Boxes` gives the same IoU through ``to_tensor('xyxy')``, not through its
+ inclusive ``'xyxy_plus'`` export.
Args:
boxes_1: a tensor of bounding boxes in :math:`(B1, 4)`.
@@ -178,8 +177,8 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str
boxes_2_xyxy = boxes_2_xyxy.float()
# Validate boxes are in proper xyxy format. The checks read the data, which graph capture cannot do;
- # skip them under export.
- if not is_exporting():
+ # skip them under any capture. TorchScript cannot call is_compiling(), and a scripted call keeps the checks.
+ if torch.jit.is_scripting() or not is_compiling():
if not (
((boxes_1_xyxy[:, 2] - boxes_1_xyxy[:, 0]) > 0).all()
and ((boxes_1_xyxy[:, 3] - boxes_1_xyxy[:, 1]) > 0).all()
diff --git a/tests/metrics/test_confusion.py b/tests/metrics/test_confusion.py
index 5ca98be28..566d87f3f 100644
--- a/tests/metrics/test_confusion.py
+++ b/tests/metrics/test_confusion.py
@@ -17,6 +17,7 @@
import pytest
import torch
+from torch._dynamo.testing import CompileCounter
import kornia
from kornia.core._compat import torch_version_lt
@@ -267,6 +268,20 @@ class TestConfusionMatrix(BaseTester):
for p, t in ((pred, target), (target, pred.flip(-1))):
self.assert_close(exported(p, t), kornia.metrics.confusion_matrix(p, t, num_classes=3), rtol=0, atol=0)
+ @pytest.mark.skipif(
+ torch_version_lt(2, 14, 0), reason="fullgraph tracing cannot capture the bincount before torch 2.14"
+ )
+ def test_trace_counts_like_eager(self, device, dtype):
+ # The range check reads the data, so any capture has to skip it, not only export (#5037).
+ pred = torch.tensor([[0, 1, 2, 2], [1, 1, 0, 2]], device=device)
+ target = torch.tensor([[0, 2, 2, 1], [1, 0, 0, 2]], device=device)
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(kornia.metrics.confusion_matrix, backend=counter, fullgraph=True)
+ actual = traced(pred, target, num_classes=3)
+ self.assert_close(actual, kornia.metrics.confusion_matrix(pred, target, num_classes=3), rtol=0, atol=0)
+ assert counter.frame_count == 1
+
class TestConventionsConfusionMatrix(BaseTester):
# Two (H, W) = (3, 4) label maps, three classes; the class counts differ between target and prediction (rows 3, 5,
diff --git a/tests/metrics/test_mean_iou.py b/tests/metrics/test_mean_iou.py
index 50cc46bec..ab22e82ac 100644
--- a/tests/metrics/test_mean_iou.py
+++ b/tests/metrics/test_mean_iou.py
@@ -17,11 +17,13 @@
import pytest
import torch
+from torch._dynamo.testing import CompileCounter
import kornia
+from kornia.core._compat import torch_version_lt
from kornia.core.exceptions import BaseError
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
class TestMeanIoU(BaseTester):
@@ -134,6 +136,20 @@ class TestMeanIoU(BaseTester):
assert mean_iou.dtype == torch.float32
assert mean_iou.device == pred.device
+ @pytest.mark.skipif(
+ torch_version_lt(2, 14, 0), reason="fullgraph tracing cannot capture the bincount before torch 2.14"
+ )
+ def test_trace_counts_like_eager(self, device, dtype):
+ # mean_iou counts through confusion_matrix, whose range check reads the data (#5037).
+ pred = torch.tensor([[0, 1, 2, 2], [1, 1, 0, 2]], device=device)
+ target = torch.tensor([[0, 2, 2, 1], [1, 0, 0, 2]], device=device)
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(kornia.metrics.mean_iou, backend=counter, fullgraph=True)
+ actual = traced(pred, target, num_classes=3)
+ self.assert_close(actual, kornia.metrics.mean_iou(pred, target, num_classes=3), rtol=0, atol=0)
+ assert counter.frame_count == 1
+
class TestMeanIoUBBox(BaseTester):
"""Tests for mean_iou_bbox with different box formats."""
@@ -326,6 +342,27 @@ class TestMeanIoUBBox(BaseTester):
assert actual.dtype == torch.float32
self.assert_close(actual, torch.tensor([[1.0]], device=device))
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_trace_boxes_like_eager(self, device, dtype):
+ # The box-validity check reads the data, so any capture has to skip it, not only export (#5037).
+ boxes_1 = torch.tensor([[0.0, 0.0, 4.0, 4.0], [1.0, 1.0, 3.0, 6.0]], device=device, dtype=dtype)
+ boxes_2 = torch.tensor([[2.0, 2.0, 6.0, 6.0]], device=device, dtype=dtype)
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(kornia.metrics.mean_iou_bbox, backend=counter, fullgraph=True)
+ actual = traced(boxes_1, boxes_2)
+ self.assert_close(actual, kornia.metrics.mean_iou_bbox(boxes_1, boxes_2))
+ assert counter.frame_count == 1
+
+ def test_jit_keeps_the_box_check(self, device, dtype):
+ # TorchScript cannot call is_compiling(); a scripted call keeps the box check, as an eager call does.
+ boxes_1 = torch.tensor([[0.0, 0.0, 4.0, 4.0], [1.0, 1.0, 3.0, 6.0]], device=device, dtype=dtype)
+ boxes_2 = torch.tensor([[2.0, 2.0, 6.0, 6.0]], device=device, dtype=dtype)
+ scripted = torch.jit.script(kornia.metrics.mean_iou_bbox)
+ self.assert_close(scripted(boxes_1, boxes_2), kornia.metrics.mean_iou_bbox(boxes_1, boxes_2))
+ with pytest.raises(torch.jit.Error, match="Boxes_1 contains invalid boxes"):
+ scripted(boxes_1.flip(-1), boxes_2)
+
class TestConventionsMeanIoU(BaseTester):
# The label maps of TestConventionsConfusionMatrix: confusion matrices [[2, 0, 1], [1, 3, 1], [0, 1, 3]] and