Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): preserve dynamic ONNX output sizes (#5883)

Karnajeet Gosavid6c5b9461590
diff --git a/changelog.d/5883.fixed.md b/changelog.d/5883.fixed.md
new file mode 100644
index 000000000..8d5b5247c
--- /dev/null
+++ b/changelog.d/5883.fixed.md
@@ -0,0 +1 @@
+ONNX exports of `pyrdown`, `PyrDown`, `build_pyramid` and `rescale` with a dynamic height or width now follow the input size instead of returning the output size of the traced input. Where the exported graph computes the size in float32 (`rescale` under both exporters, `pyrdown` under the dynamo exporter), a factor that is not a power of two can be one pixel off eager (`rescale` 0.7 at a side of 90, `pyrdown` 1.1 at a side of 33); the `rescale` modes that stay static are listed in its docstring.
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index f22407603..8722ff559 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -786,6 +786,10 @@ def rescale(
- ``factor`` is ``(factor_h, factor_w)`` when a pair β€” height first (contrast
:func:`scale`, whose ``scale_factor`` is x-first)
- delegates to :func:`resize` after converting ``factor`` to an output ``size``
+ - ONNX: an export with a dynamic height or width keeps it dynamic for the ``'nearest'``,
+ ``'bilinear'`` and ``'bicubic'`` modes without ``antialias``; the other modes keep the output size of
+ the traced input. The exported graph computes the size in float32, which can be one pixel off eager
+ when ``factor`` is not a power of two (``0.7`` at a side of 90 gives 63, eager 62)
Args:
input: The image tensor to be scale with shape of :math:`(B, C, H, W)`.
@@ -812,6 +816,25 @@ def rescale(
else:
factor_vert, factor_horz = factor
+ if (
+ torch.onnx.is_in_onnx_export()
+ and not antialias
+ and interpolation in ("nearest", "bilinear", "bicubic")
+ and factor_vert > 0
+ and factor_horz > 0
+ and input.ndim == 4
+ ):
+ # ONNX export: keep the scale in the graph, so a dynamic height or width stays dynamic instead of freezing
+ # the traced output size. ``is_exporting()`` is not used: it is also true inside ``torch.compile`` on torch
+ # 2.5.1 and 2.9.1, where this path would skip ``resize``.
+ return torch.nn.functional.interpolate(
+ input,
+ scale_factor=(factor_vert, factor_horz),
+ mode=interpolation,
+ align_corners=align_corners,
+ recompute_scale_factor=True,
+ )
+
height, width = input.size()[-2:]
size = (int(height * factor_vert), int(width * factor_horz))
return resize(input, size, interpolation=interpolation, align_corners=align_corners, antialias=antialias)
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 4b1976f48..389b60b54 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -414,6 +414,8 @@ def pyrdown(
- output spatial size is ``floor(side / factor)`` per dimension
(:math:`5 \times 5 \to 2 \times 2` at the default ``factor=2.0`` β€”
note OpenCV's ``pyrDown`` rounds up instead)
+ - Dynamo ONNX uses float32 reciprocal-scale arithmetic for dynamic sides, which can differ from eager by one
+ pixel for some fractional factors (for example, side 33 and factor 1.1)
- border_type: ``'reflect'`` by default (blur before downsample)
- align_corners: ``False`` by default
@@ -438,18 +440,23 @@ def pyrdown(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
- _, _, height, width = input.shape
# blur image
x_blur: torch.Tensor = filter2d(input, kernel, border_type)
- # TODO: use kornia.geometry.resize/rescale
- # downsample.
- out: torch.Tensor = F.interpolate(
- x_blur,
- size=(int(float(height) / factor), int(float(width) / factor)),
- mode="bilinear",
- align_corners=align_corners,
- )
+ # Keep the output size dynamic in ONNX while preserving eager's floor rule.
+ _, _, height, width = input.shape
+ if isinstance(height, torch.Tensor):
+ # The TorchScript tracer represents sizes as tensors; float64 avoids
+ # rounding a fractional quotient before truncating it.
+ divisor = torch.tensor([factor], dtype=torch.float64)
+ size = [torch.floor(side.reshape(1).double() / divisor).long()[0] for side in (height, width)]
+ elif isinstance(height, torch.SymInt) and torch.onnx.is_in_onnx_export():
+ # Dynamo ONNX lowering supports dynamic SymInt sizes through reciprocal
+ # scale. Its float32 arithmetic may differ from eager for some factors.
+ size = [torch.sym_int(side * (1.0 / factor)) for side in (height, width)]
+ else:
+ size = [int(float(height) / factor), int(float(width) / factor)]
+ out: torch.Tensor = F.interpolate(x_blur, size=size, mode="bilinear", align_corners=align_corners)
return out
diff --git a/tests/geometry/transform/test_pyramid.py b/tests/geometry/transform/test_pyramid.py
index 2dc2f76f9..de562d3ef 100644
--- a/tests/geometry/transform/test_pyramid.py
+++ b/tests/geometry/transform/test_pyramid.py
@@ -19,9 +19,10 @@ import pytest
import torch
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 BaseTester, dynamo_is_available
class TestPyrUp(BaseTester):
@@ -41,6 +42,118 @@ class TestPyrUp(BaseTester):
class TestPyrDown(BaseTester):
+ @pytest.mark.parametrize("dynamo", [False, True])
+ @pytest.mark.parametrize("operation", ["pyrdown", "build_pyramid", "rescale"])
+ def test_onnx_dynamic_spatial_shape(self, operation, dynamo, tmp_path):
+ import numpy as np
+
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ if dynamo:
+ if not dynamo_is_available():
+ pytest.skip("Dynamo ONNX export is unavailable on this torch/python pair")
+ if torch_version_lt(2, 9, 0):
+ pytest.skip("Dynamo ONNX export of a dynamic height or width needs torch >= 2.9")
+ pytest.importorskip("onnxscript")
+
+ class Wrapper(torch.nn.Module):
+ def forward(self, x):
+ if operation == "pyrdown":
+ return kornia.geometry.transform.pyrdown(x)
+ if operation == "build_pyramid":
+ return kornia.geometry.transform.build_pyramid(x, 3)[-1]
+ return kornia.geometry.transform.rescale(x, 0.5)
+
+ model = Wrapper().eval()
+ path = tmp_path / "model.onnx"
+ export_kwargs = {
+ "input_names": ["x"],
+ "output_names": ["y"],
+ "opset_version": 18,
+ "dynamo": dynamo,
+ }
+ if dynamo:
+ export_kwargs["dynamic_shapes"] = (
+ {
+ 0: torch.export.Dim("batch"),
+ 2: torch.export.Dim("height", min=6),
+ 3: torch.export.Dim("width", min=6),
+ },
+ )
+ else:
+ export_kwargs["dynamic_axes"] = {
+ "x": {0: "batch", 2: "height", 3: "width"},
+ "y": {0: "out_batch", 2: "out_height", 3: "out_width"},
+ }
+ torch.onnx.export(model, (torch.rand(2, 1, 22, 44),), path, **export_kwargs)
+
+ x = torch.rand(3, 1, 33, 64)
+ actual = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]).run(None, {"x": x.numpy()})[0]
+ np.testing.assert_allclose(actual, model(x).numpy(), rtol=1e-5, atol=1e-6)
+
+ def test_area_rescale_static_torchscript_export(self, tmp_path):
+ import numpy as np
+
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+
+ class Wrapper(torch.nn.Module):
+ def forward(self, x):
+ return kornia.geometry.transform.rescale(x, 0.5, interpolation="area")
+
+ model = Wrapper().eval()
+ path = tmp_path / "model.onnx"
+ x = torch.rand(1, 1, 22, 44)
+ torch.onnx.export(model, (x,), path, input_names=["x"], output_names=["y"], opset_version=18, dynamo=False)
+ actual = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]).run(None, {"x": x.numpy()})[0]
+ np.testing.assert_allclose(actual, model(x).numpy(), rtol=1e-5, atol=1e-6)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason="torch.compile is unavailable on this torch/python pair")
+ def test_eager_backend_trace_keeps_rescales_empty_output(self):
+ # kornia's is_exporting() is also true inside torch.compile on torch 2.5.1 and 2.9.1.
+ x = torch.rand(1, 1, 22, 44)
+ actual = torch.compile(lambda t: kornia.geometry.transform.rescale(t, 0.01), backend="eager", fullgraph=True)(x)
+ assert actual.shape == kornia.geometry.transform.rescale(x, 0.01).shape == (1, 1, 0, 0)
+
+ @pytest.mark.parametrize("dynamo", [False, True])
+ def test_onnx_fractional_factor_preserves_truncation(self, dynamo, tmp_path):
+ import numpy as np
+
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ if dynamo:
+ if not dynamo_is_available():
+ pytest.skip("Dynamo ONNX export is unavailable on this torch/python pair")
+ pytest.importorskip("onnxscript")
+
+ class Wrapper(torch.nn.Module):
+ def forward(self, x):
+ return kornia.geometry.transform.pyrdown(x, factor=1.1)
+
+ model = Wrapper().eval()
+ path = tmp_path / "model.onnx"
+ torch.onnx.export(
+ model,
+ (torch.rand(1, 1, 33, 55),),
+ path,
+ input_names=["x"],
+ output_names=["y"],
+ opset_version=18,
+ dynamo=dynamo,
+ )
+ x = torch.rand(1, 1, 33, 55)
+ expected = model(x)
+ assert expected.shape[-2:] == (29, 49)
+ actual = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]).run(None, {"x": x.numpy()})[0]
+ np.testing.assert_allclose(actual, expected.numpy(), rtol=1e-5, atol=1e-6)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason="torch.compile is unavailable on this torch/python pair")
+ def test_fractional_factor_compile_shape(self):
+ model = torch.compile(
+ lambda x: kornia.geometry.transform.pyrdown(x, factor=1.1), backend="eager", fullgraph=True
+ )
+ assert model(torch.rand(1, 1, 33, 55)).shape[-2:] == (29, 49)
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 2, 4, 4, device=device, dtype=dtype)
pyr = kornia.geometry.PyrDown()
@@ -55,7 +168,14 @@ class TestPyrDown(BaseTester):
@pytest.mark.parametrize("align_corners", [False, True])
@pytest.mark.parametrize(
"height, width, factor, expected_size",
- [(11, 22, 1.1, (10, 20)), (9, 18, 1.8, (5, 10)), (9, 15, 1.2, (7, 12)), (11, 15, 2.0, (5, 7))],
+ [
+ (11, 22, 1.1, (10, 20)),
+ (9, 18, 1.8, (5, 10)),
+ (9, 15, 1.2, (7, 12)),
+ (11, 15, 2.0, (5, 7)),
+ (33, 55, 1.1, (29, 49)),
+ (39, 65, 1.3, (30, 50)),
+ ],
)
def test_fractional_factor_axis_symmetry(
self, device, dtype, as_module, align_corners, height, width, factor, expected_size