Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): legacy exports of Boxes.to_mask, Boxes3D.to_mask and PSNR match eager (#6188)

Dmytro Mishkin8e4443a3a9f6
diff --git a/changelog.d/6188.fixed.md b/changelog.d/6188.fixed.md
new file mode 100644
index 000000000..c08027b46
--- /dev/null
+++ b/changelog.d/6188.fixed.md
@@ -0,0 +1 @@
+`Boxes.to_mask`, `Boxes3D.to_mask`, `kornia.metrics.psnr`, `kornia.losses.psnr_loss` and `kornia.losses.PSNRLoss` export correctly with the legacy (TorchScript) ONNX exporter (`torch.onnx.export(..., dynamo=False)`) on torch 2.5.1, 2.9.1 and 2.14. Before, the two `to_mask` graphs had no input and returned an all-zero mask for any box: the legacy exporter traced the CPU loop and lost its in-place writes. Under the legacy exporter and `torch.jit.trace` they now compare a coordinate grid against the box bounds, as the dynamo exporter already did (and `Boxes.to_mask` on CUDA). The PSNR graphs returned a one-element vector of shape `(1,)` where eager returns a 0-d scalar; they now return the eager shape. `Boxes.to_mask` of an image with a side of 0, and `Boxes3D.to_mask` of such a volume, return an empty mask on the loop path (CPU, and CUDA for `Boxes3D`) as the grid path does, instead of raising `RuntimeError: cannot reshape tensor of 0 elements`. Every other eager result is unchanged.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index c74483aaf..184ae27c6 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -883,7 +883,9 @@ class Boxes:
# CPU Hotpath (loop)
# -----------------
# The loop slices with data-dependent bounds, which graph capture cannot do; export takes the vectorized path.
- if device.type != "cuda" and not is_exporting():
+ # So does the legacy ONNX exporter, which traces outside ``is_exporting()``: it loses the loop's in-place
+ # writes into the mask and exports a constant all-zero mask with no graph input.
+ if device.type != "cuda" and not is_exporting() and not torch.jit.is_tracing():
if self._is_batched: # (B, N, 4, 2)
mask = torch.zeros(
(self._data.shape[0], self._data.shape[1], height, width), dtype=self.dtype, device=self.device
@@ -891,11 +893,10 @@ class Boxes:
else: # (N, 4, 2)
mask = torch.zeros((self._data.shape[0], height, width), dtype=self.dtype, device=self.device)
- # Reshape mask to (BxN, H, W) and boxes to (BxN, 4) to iterate over all of them.
+ # Flatten mask to (BxN, H, W) and boxes to (BxN, 4) to iterate over all of them. ``flatten`` rather than
+ # ``view(-1, height, width)``, which cannot infer BxN when a side of the image is 0.
# Cast boxes coordinates to be integer to use them as indexes. Use round to handle decimal values.
- for mask_channel, box_xyxy in zip(
- mask.view(-1, height, width), clipped_boxes_xyxy.view(-1, 4).round().int()
- ):
+ for mask_channel, box_xyxy in zip(mask.flatten(0, -3), clipped_boxes_xyxy.view(-1, 4).round().int()):
# Mask channel dimensions: (height, width)
mask_channel[box_xyxy[1] : box_xyxy[3], box_xyxy[0] : box_xyxy[2]] = 1
@@ -1562,9 +1563,10 @@ class Boxes3D:
# Cast boxes coordinates to be integer to use them as bounds. Use round to handle decimal values.
xyzxyz = clipped_boxes_xyzxyz.view(-1, 6).round().long()
- if is_exporting():
+ if is_exporting() or torch.jit.is_tracing():
# The loop below slices with data-dependent bounds, which graph capture cannot do; compare a
- # coordinate grid against the bounds instead.
+ # coordinate grid against the bounds instead. The legacy ONNX exporter traces outside
+ # ``is_exporting()`` and loses the loop's in-place writes, exporting a constant all-zero mask.
device = self._data.device
zs = torch.arange(depth, device=device)
ys = torch.arange(height, device=device)
@@ -1575,8 +1577,9 @@ class Boxes3D:
masks = z_mask[:, :, None, None] & y_mask[:, None, :, None] & x_mask[:, None, None, :]
return masks.to(mask.dtype).view(mask.shape)
- # Reshape mask to (BxN, D, H, W) and boxes to (BxN, 6) to iterate over all of them.
- for mask_channel, box_xyzxyz in zip(mask.view(-1, depth, height, width), xyzxyz):
+ # Flatten mask to (BxN, D, H, W) to iterate over the (BxN, 6) boxes. ``flatten`` rather than
+ # ``view(-1, depth, height, width)``, which cannot infer BxN when a side of the volume is 0.
+ for mask_channel, box_xyzxyz in zip(mask.flatten(0, -4), xyzxyz):
# Mask channel dimensions: (depth, height, width)
mask_channel[
box_xyzxyz[2] : box_xyzxyz[5], box_xyzxyz[1] : box_xyzxyz[4], box_xyzxyz[0] : box_xyzxyz[3]
diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.py
index 9e0f42841..93ec659f3 100644
--- a/kornia/metrics/psnr.py
+++ b/kornia/metrics/psnr.py
@@ -88,4 +88,8 @@ def psnr(image: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
dtype = torch.promote_types(image.dtype, target.dtype)
image, target = image.to(dtype), target.to(dtype)
- return 10.0 * torch.log10(max_val**2 / mse(image, target, reduction="mean"))
+ # The legacy (TorchScript) ONNX exporter writes ``log10`` as a division by a ``(1,)`` constant, which turns a 0-d
+ # result into a one-element vector. Reshaping to the shape of the ratio keeps the eager shape there (``()`` for a
+ # scalar ``max_val``, the shape of a tensor one) and is a no-op view eagerly.
+ ratio = max_val**2 / mse(image, target, reduction="mean")
+ return (10.0 * torch.log10(ratio)).reshape(ratio.shape)
diff --git a/testing/known_failure_xfails/onnx_conformance_torch2.14.txt b/testing/known_failure_xfails/onnx_conformance_torch2.14.txt
index 0f3da54df..0f6cde870 100644
--- a/testing/known_failure_xfails/onnx_conformance_torch2.14.txt
+++ b/testing/known_failure_xfails/onnx_conformance_torch2.14.txt
@@ -5,12 +5,3 @@
# regression to fix; add it only with a comment naming its own tracking issue.
# Entries of packages a run does not select are not checked; every node ID must name a promised case.
# Format: <exact exception type>\t<pytest node ID>
-# #6164: the legacy exporter traces the CPU loop of Boxes.to_mask / Boxes3D.to_mask and writes a
-# constant all-zero mask with no graph input.
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes.to_mask]
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes3D.to_mask]
-# #6165: the legacy exporter gives torch.log10 of a 0-d tensor the shape (1,), so the PSNR graphs
-# return (1,) instead of a scalar.
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.PSNRLoss]
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.psnr_loss]
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[metrics.psnr]
diff --git a/testing/known_failure_xfails/onnx_conformance_torch2.9.txt b/testing/known_failure_xfails/onnx_conformance_torch2.9.txt
index 2154779f6..4c81f814b 100644
--- a/testing/known_failure_xfails/onnx_conformance_torch2.9.txt
+++ b/testing/known_failure_xfails/onnx_conformance_torch2.9.txt
@@ -13,12 +13,3 @@ AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[Augment
AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[AugmentationSequential[mask]]
AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[ManyToManyAugmentationDispather]
AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[ManyToOneAugmentationDispather]
-# #6164: the legacy exporter traces the CPU loop of Boxes.to_mask / Boxes3D.to_mask and writes a
-# constant all-zero mask with no graph input.
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes.to_mask]
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes3D.to_mask]
-# #6165: the legacy exporter gives torch.log10 of a 0-d tensor the shape (1,), so the PSNR graphs
-# return (1,) instead of a scalar.
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.PSNRLoss]
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.psnr_loss]
-AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[metrics.psnr]
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 078a4d697..801f724c6 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -15,7 +15,9 @@
# limitations under the License.
#
+import io
import pickle
+import warnings
from functools import partial
import pytest
@@ -28,6 +30,21 @@ from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxes
from testing.base import BaseTester
+def _legacy_onnx_to_mask_pairs(
+ model: torch.nn.Module, vertices: list[torch.Tensor]
+) -> list[tuple[torch.Tensor, torch.Tensor]]:
+ """Export ``model`` with the legacy exporter on ``vertices[0]``; return ``(onnxruntime, eager)`` for each set."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ buffer = io.BytesIO()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(model, (vertices[0],), buffer, input_names=["vertices"], opset_version=18, dynamo=False)
+ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])
+ assert [graph_input.name for graph_input in session.get_inputs()] == ["vertices"]
+ return [(torch.from_numpy(session.run(None, {"vertices": boxes.numpy()})[0]), model(boxes)) for boxes in vertices]
+
+
def _unbatched_geometry_data(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
return torch.tensor(
[
@@ -1261,6 +1278,40 @@ class TestBoxes2D(BaseTester):
assert loop.shape == vectorized.shape
self.assert_close(loop, vectorized, atol=0.0, rtol=0.0)
+ @pytest.mark.parametrize("size", [(0, 6), (5, 0), (0, 0)])
+ @pytest.mark.parametrize("batched", [False, True])
+ def test_convention_to_mask_zero_size_image_matches_export_path(self, size, batched, device, dtype, monkeypatch):
+ # Convention pin: an image with a side of 0 gives an empty (N, H, W) or (B, N, H, W) mask on the CPU loop path
+ # as on the vectorized one. The loop used to raise in view(-1, height, width), which cannot infer B * N there.
+ data = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ if batched:
+ data = data.expand(2, 3, 4, 2).contiguous()
+ loop = Boxes(data).to_mask(*size)
+ monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ vectorized = Boxes(data).to_mask(*size)
+ assert loop.shape == vectorized.shape == (*data.shape[:-2], *size)
+ assert loop.dtype == vectorized.dtype == dtype
+
+ @pytest.mark.device_agnostic
+ def test_to_mask_legacy_onnx_export_reads_its_input_6164(self):
+ # The legacy exporter traces outside is_exporting(). It used to trace the CPU loop and lose its in-place
+ # writes: a graph with no input that returned zeros for every box (#6164). The graph must read the boxes, so
+ # boxes other than the traced ones (overlapping, fractional, partly or wholly outside the image) give their
+ # own masks.
+ class ToMask(torch.nn.Module):
+ def forward(self, vertices: torch.Tensor) -> torch.Tensor:
+ return Boxes(vertices).to_mask(9, 11)
+
+ xyxy = [
+ [[[1.0, 2.0, 6.0, 7.0], [0.0, 0.0, 2.0, 1.0]]],
+ [[[-2.0, -1.0, 4.0, 3.0], [3.0, 3.0, 14.0, 12.0]]],
+ [[[1.4, 1.6, 5.5, 4.4], [20.0, 20.0, 25.0, 25.0]]],
+ ]
+ vertices = [Boxes.from_tensor(torch.tensor(boxes), mode="xyxy_plus").data for boxes in xyxy]
+ for actual, expected in _legacy_onnx_to_mask_pairs(ToMask(), vertices):
+ assert expected.sum() > 0
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+
class TestTransformBoxes2D(BaseTester):
def test_transform_boxes(self, device, dtype):
@@ -1994,6 +2045,37 @@ class TestBbox3D(BaseTester):
assert loop.shape == vectorized.shape
self.assert_close(loop, vectorized, atol=0.0, rtol=0.0)
+ @pytest.mark.parametrize("size", [(0, 5, 6), (4, 0, 6), (4, 5, 0)])
+ @pytest.mark.parametrize("batched", [False, True])
+ def test_convention_to_mask_zero_size_volume_matches_export_path(self, size, batched, device, dtype, monkeypatch):
+ # Convention pin: a volume with a side of 0 gives an empty mask on the loop path as on the grid-comparison
+ # path. The loop used to raise in view(-1, depth, height, width), which cannot infer B * N there.
+ data = self._fractional_cuboid(device, dtype)
+ if batched:
+ data = data.expand(2, 2, 8, 3).contiguous()
+ loop = Boxes3D(data).to_mask(*size)
+ monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)
+ vectorized = Boxes3D(data).to_mask(*size)
+ assert loop.shape == vectorized.shape == (*data.shape[:-2], *size)
+ assert loop.dtype == vectorized.dtype == dtype
+
+ @pytest.mark.device_agnostic
+ def test_to_mask_legacy_onnx_export_reads_its_input_6164(self):
+ # As for Boxes.to_mask: the legacy exporter traced the loop and exported a constant all-zero mask (#6164).
+ class ToMask(torch.nn.Module):
+ def forward(self, vertices: torch.Tensor) -> torch.Tensor:
+ return Boxes3D(vertices).to_mask(5, 6, 7)
+
+ xyzxyz = [
+ [[[1.0, 1.0, 1.0, 4.0, 3.0, 2.0], [0.0, 2.0, 3.0, 6.0, 5.0, 4.0]]],
+ [[[3.0, 0.0, 2.0, 5.0, 5.0, 3.0], [-2.0, -1.0, 0.0, 2.0, 1.0, 9.0]]],
+ [[[1.4, 1.6, 0.6, 3.5, 4.4, 2.4], [20.0, 20.0, 20.0, 25.0, 25.0, 25.0]]],
+ ]
+ vertices = [Boxes3D.from_tensor(torch.tensor(boxes), mode="xyzxyz_plus").data for boxes in xyzxyz]
+ for actual, expected in _legacy_onnx_to_mask_pairs(ToMask(), vertices):
+ assert expected.sum() > 0
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+
def test_convention_transform_boxes_in_place_rebinds_data(self, device, dtype):
# Convention pin: the copy path leaves the source untouched and returns a new object; the
# in-place path returns self but rebinds the internal tensor, so an earlier data reference
diff --git a/tests/metrics/test_psnr_metric.py b/tests/metrics/test_psnr_metric.py
index ad7a4c77e..2bceeec7e 100644
--- a/tests/metrics/test_psnr_metric.py
+++ b/tests/metrics/test_psnr_metric.py
@@ -100,6 +100,19 @@ class TestPsnr(BaseTester):
assert image.grad.dtype == dtypes[0]
assert target.grad.dtype == dtypes[1]
+ def test_tensor_max_val_keeps_its_shape(self, device, dtype):
+ # A tensor max_val broadcasts against the pooled MSE, one PSNR per data range, and the result keeps its shape:
+ # (2,) stays (2,), (1,) stays (1,), and a 0-d tensor gives a 0-d result like a float.
+ generator = torch.Generator().manual_seed(0)
+ a = torch.rand(2, 3, 8, 8, generator=generator).to(device, dtype)
+ b = torch.rand(2, 3, 8, 8, generator=generator).to(device, dtype)
+ assert kornia.metrics.psnr(a, b, torch.tensor([1.0, 255.0], device=device)).shape == (2,)
+ max_val = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ expected = torch.stack([kornia.metrics.psnr(a, b, 1.0), kornia.metrics.psnr(a, b, 2.0)])
+ self.assert_close(kornia.metrics.psnr(a, b, max_val), expected)
+ assert kornia.metrics.psnr(a, b, max_val[:1]).shape == (1,)
+ assert kornia.metrics.psnr(a, b, max_val[0]).shape == ()
+
def test_exception_shape_mismatch(self, device, dtype):
a = torch.ones(4, device=device, dtype=dtype)
b = torch.ones(8, device=device, dtype=dtype)