Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(calibration): avoid data-dependent tilt checks during compile (#4391)

UnbearableFatede2f35fdd7da
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 597011c7a..76bb0827d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -369,6 +369,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Make calibration `distort_points` and `undistort_points` tilt checks compatible with
+ `torch.compile(fullgraph=True)`, preserving eager behavior. (#4391)
* Canny hysteresis preserves the input dtype, avoiding a convolution dtype mismatch for half-precision images. (#4393)
* `rad2deg` and `deg2rad` now handle integer tensor inputs correctly and preserve
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index 1e36b8bf1..14badb839 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -20,7 +20,7 @@ from typing import Optional
import torch
import torch.nn.functional as F
-from kornia.core.utils import is_exporting
+from kornia.core.utils import is_compiling, is_exporting
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/distortion_model.hpp#L75
@@ -125,18 +125,13 @@ def distort_points(
coefficient layout, with the two intrinsics in the mirrored roles.
- In eager execution, arbitrary matching leading dimensions work while the tilt path is inactive.
With non-zero tilt, only unbatched inputs or one leading batch dimension are supported; two or more leading
- dimensions are flattened by :func:`~kornia.geometry.calibration.tilt_projection`. ONNX export always
- takes that path, including for zero tilt. Tracked as `#4324 <https://github.com/kornia/kornia/issues/4324>`_.
+ dimensions are flattened by :func:`~kornia.geometry.calibration.tilt_projection`. Compilation and ONNX export
+ always take that path, including for zero tilt. Tracked as `#4324 <https://github.com/kornia/kornia/issues/4324>`_.
.. warning::
Non-zero tilt uses the forward branch of :func:`tilt_projection` and breaks the inverse round trip;
see that function and `#4276 <https://github.com/kornia/kornia/issues/4276>`_ for the explanation.
- .. warning::
- ``torch.compile(fullgraph=True)`` fails on this function because the tilt test reads the coefficient
- values on the host; ONNX export is already routed around it by ``is_exporting()``. Tracked as
- `#4286 <https://github.com/kornia/kornia/issues/4286>`_.
-
Args:
points: Input image points with shape :math:`(*, N, 2)`.
K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.
@@ -210,9 +205,12 @@ def distort_points(
+ dist[..., 11:12] * r4
)
- # Compensate for tilt distortion. The zero test reads the data, which graph capture cannot do, so the
- # exported graph always applies the tilt (an identity when both tau coefficients are zero).
- if is_exporting() or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
+ # Graph capture cannot read the coefficient values on the host. Apply the tilt unconditionally
+ # while compiling or exporting; zero angles give the identity. Keep eager and scripted behavior.
+ capture = is_exporting()
+ if not torch.jit.is_scripting():
+ capture = capture or is_compiling()
+ if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
tilt = tilt_projection(dist[..., 12], dist[..., 13])
# Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 39f7dc8ed..b33138f5e 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -23,7 +23,7 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK_SHAPE
-from kornia.core.utils import is_exporting
+from kornia.core.utils import is_compiling, is_exporting
from kornia.geometry.grid import create_meshgrid
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import remap
@@ -56,7 +56,7 @@ def undistort_points(
default count, while ``float32`` and ``float64`` can continue to improve.
- In eager execution, arbitrary matching leading dimensions work while the tilt path is inactive.
With non-zero tilt, use one explicit leading batch dimension; multiple leading dimensions and
- unbatched intrinsics can fail. ONNX export always takes that path, including for zero tilt, so
+ unbatched intrinsics can fail. Compilation and ONNX export always take that path, including for zero tilt, so
even unbatched inputs with four coefficients can fail. Tracked as `#4324 <https://github.com/kornia/kornia/issues/4324>`_.
.. warning::
@@ -69,11 +69,6 @@ def undistort_points(
:func:`~kornia.geometry.calibration.tilt_projection` and
`#4276 <https://github.com/kornia/kornia/issues/4276>`_ for the explanation.
- .. warning::
- This function has the same ``torch.compile(fullgraph=True)`` limitation as
- :func:`~kornia.geometry.calibration.distort_points`; see that function for the explanation. Tracked as
- `#4286 <https://github.com/kornia/kornia/issues/4286>`_.
-
Args:
points: Input image points with shape :math:`(*, N, 2)`.
K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.
@@ -131,9 +126,12 @@ def undistort_points(
x: torch.Tensor = (points[..., 0] - cx) / fx # (BxN - Bx1)/Bx1 -> BxN
y: torch.Tensor = (points[..., 1] - cy) / fy # (BxN - Bx1)/Bx1 -> BxN
- # Compensate for tilt distortion. The zero test reads the data, which graph capture cannot do, so the
- # exported graph always applies the tilt (an identity when both tau coefficients are zero).
- if is_exporting() or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
+ # Graph capture cannot read the coefficient values on the host. Apply the tilt unconditionally
+ # while compiling or exporting; zero angles give the identity. Keep eager and scripted behavior.
+ capture = is_exporting()
+ if not torch.jit.is_scripting():
+ capture = capture or is_compiling()
+ if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
inv_tilt = tilt_projection(dist[..., 12], dist[..., 13], True)
# Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])
@@ -187,7 +185,7 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
front of its ``n`` coefficients) must match exactly. They may be empty, a single batch axis, or
several axes deep. The one exception is the legacy unbatched call -- a :math:`(1, C, H, W)` image
with a :math:`(3, 3)` ``K`` and an :math:`(n,)` ``dist``. With non-zero tilt, at most one leading batch
- axis is supported; ONNX export always takes the tilt path, including for zero tilt. Tracked as
+ axis is supported; compilation and ONNX export always take the tilt path, including for zero tilt. Tracked as
`#4324 <https://github.com/kornia/kornia/issues/4324>`_.
- the sampling map is built by applying :func:`~kornia.geometry.calibration.distort_points` to the
grid of integer pixel centres that :func:`~kornia.geometry.grid.create_meshgrid` enumerates: the
diff --git a/tests/geometry/calibration/test_compile.py b/tests/geometry/calibration/test_compile.py
new file mode 100644
index 000000000..00604524d
--- /dev/null
+++ b/tests/geometry/calibration/test_compile.py
@@ -0,0 +1,46 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+from torch._dynamo.testing import CompileCounter
+
+from kornia.geometry.calibration import distort_points, undistort_points
+
+from testing.base import BaseTester
+
+
+class TestCalibrationCompile(BaseTester):
+ @pytest.mark.parametrize("op", [distort_points, undistort_points])
+ @pytest.mark.parametrize("num_coefficients", [4, 14])
+ def test_dynamo_fullgraph(self, device, dtype, torch_optimizer, op, num_coefficients):
+ # #4286: tensor-dependent tilt checks must not break capture or specialize on coefficient values.
+ points = torch.tensor([[[1.0, 2.0], [6.0, 5.0]]], device=device, dtype=dtype)
+ camera = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ dist = torch.zeros(1, num_coefficients, device=device, dtype=dtype)
+ dist[:, :4] = torch.tensor([0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)
+ counter = CompileCounter()
+ counted = torch.compile(op, backend=counter, fullgraph=True)
+ compiled = torch_optimizer(op, fullgraph=True)
+ for tilt in [0.0, 0.1]:
+ if num_coefficients == 14:
+ dist[:, 12] = tilt
+ dist[:, 13] = -2 * tilt
+ expected = op(points, camera, dist)
+ self.assert_close(counted(points, camera, dist), expected)
+ self.assert_close(compiled(points, camera, dist), expected)
+ assert counter.frame_count == 1