Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: replace isinstance unions with tuples for dynamo fullgraph trace… (#5394)

Prakhar Sainif7bb3733fe8b
diff --git a/changelog.d/5394.fixed.md b/changelog.d/5394.fixed.md
new file mode 100644
index 000000000..df0b59dba
--- /dev/null
+++ b/changelog.d/5394.fixed.md
@@ -0,0 +1 @@
+`Vector3.from_coords`, `Vector2.from_coords` and `Hyperplane.signed_distance` compile with `torch.compile(..., fullgraph=True)` on torch 2.5.1: their `isinstance` checks, and the five others left in `kornia/`, use tuples of classes instead of `X | Y` unions, which that version of Dynamo cannot trace.
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 0e0dfbc8a..91cc96a0d 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -155,7 +155,7 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
"""
output = self.pre_processor(images)
- if isinstance(output, list | tuple):
+ if isinstance(output, (list, tuple)):
images = output[0]
else:
images = output
diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.py
index 81d42e228..ec73a4d2c 100644
--- a/kornia/core/tensor_wrapper.py
+++ b/kornia/core/tensor_wrapper.py
@@ -222,7 +222,7 @@ class TensorWrapper:
for a in args:
if isinstance(a, cls):
args_of_this_cls.append(a)
- elif isinstance(a, collections.abc.Sequence) and not isinstance(a, str | bytes):
+ elif isinstance(a, collections.abc.Sequence) and not isinstance(a, (str, bytes)):
args_of_this_cls.extend(el for el in a if isinstance(el, cls))
# Track function usage
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 7ffe01278..8adce0563 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -508,7 +508,7 @@ def dataclass_to_dict(obj: Any) -> Any:
"""Recursively convert dataclass instances to dictionaries."""
if is_dataclass(obj) and not isinstance(obj, type):
return {key: dataclass_to_dict(value) for key, value in asdict(obj).items()}
- if isinstance(obj, list | tuple):
+ if isinstance(obj, (list, tuple)):
return type(obj)(dataclass_to_dict(item) for item in obj)
if isinstance(obj, dict):
return {key: dataclass_to_dict(value) for key, value in obj.items()}
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 0214979d5..341bc987b 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -126,7 +126,7 @@ class Hyperplane(nn.Module):
:class:`~kornia.geometry.vector.Scalar` containing signed distance
values for each input point.
"""
- KORNIA_CHECK(isinstance(p, Vector3 | torch.Tensor))
+ KORNIA_CHECK(isinstance(p, (Vector3, torch.Tensor)))
return self.normal.dot(p) + self.offset
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L154
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index 6096317be..073188f35 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -187,7 +187,7 @@ class Vector3(TensorWrapper):
:class:`Vector3` containing the assembled coordinates.
"""
KORNIA_CHECK(type(x) is type(y) is type(z))
- KORNIA_CHECK(isinstance(x, torch.Tensor | float))
+ KORNIA_CHECK(isinstance(x, (torch.Tensor, float)))
if isinstance(x, float):
return _wrap(torch.as_tensor((x, y, z), device=device, dtype=dtype), Vector3)
# TODO: this is totally insane ...
@@ -301,7 +301,7 @@ class Vector2(TensorWrapper):
:class:`Vector2` containing the assembled coordinates.
"""
KORNIA_CHECK(type(x) is type(y))
- KORNIA_CHECK(isinstance(x, torch.Tensor | float))
+ KORNIA_CHECK(isinstance(x, (torch.Tensor, float)))
if isinstance(x, float):
return _wrap(torch.as_tensor((x, y), device=device, dtype=dtype), Vector2)
# TODO: this is totally insane ...
diff --git a/kornia/models/siglip2/preprocessor.py b/kornia/models/siglip2/preprocessor.py
index c207bbc85..11df73572 100644
--- a/kornia/models/siglip2/preprocessor.py
+++ b/kornia/models/siglip2/preprocessor.py
@@ -62,8 +62,8 @@ class SigLip2ImagePreprocessor(nn.Module):
) -> None:
super().__init__()
self.image_size = image_size
- self.mean = torch.tensor([mean]) if isinstance(mean, list | tuple) else mean
- self.std = torch.tensor([std]) if isinstance(std, list | tuple) else std
+ self.mean = torch.tensor([mean]) if isinstance(mean, (list, tuple)) else mean
+ self.std = torch.tensor([std]) if isinstance(std, (list, tuple)) else std
self.rescale_factor = rescale_factor
# build preprocessing pipeline
diff --git a/tests/geometry/test_dynamo_traces.py b/tests/geometry/test_dynamo_traces.py
new file mode 100644
index 000000000..1c2952caa
--- /dev/null
+++ b/tests/geometry/test_dynamo_traces.py
@@ -0,0 +1,57 @@
+# 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 kornia.geometry.plane import Hyperplane
+from kornia.geometry.vector import Scalar, Vector2, Vector3
+
+from testing.base import BaseTester, dynamo_is_available
+
+
[email protected](not dynamo_is_available(), reason="no Dynamo on this torch/python pair")
+class TestGeometryEagerBackendTraces(BaseTester):
+ # Dynamo on torch 2.5.1 cannot trace ``isinstance`` against a ``A | B`` union (#5371). The test names keep
+ # "compile" and "dynamo" out, so the ordinary jobs, including the torch 2.5.1 legs that have Dynamo, run them.
+
+ def test_eager_backend_traces_vector3_from_coords(self, device, dtype):
+ def fn(x):
+ return Vector3.from_coords(x, 2 * x, -x).data
+
+ torch._dynamo.reset()
+ x = torch.tensor([0.5, -1.0, 2.0, 3.0], device=device, dtype=dtype)
+ self.assert_close(torch.compile(fn, backend="eager", fullgraph=True)(x), fn(x))
+
+ def test_eager_backend_traces_vector2_from_coords(self, device, dtype):
+ def fn(x):
+ return Vector2.from_coords(x, 2 * x).data
+
+ torch._dynamo.reset()
+ x = torch.tensor([0.5, -1.0, 2.0, 3.0], device=device, dtype=dtype)
+ self.assert_close(torch.compile(fn, backend="eager", fullgraph=True)(x), fn(x))
+
+ def test_eager_backend_traces_hyperplane_signed_distance(self, device, dtype):
+ normal = Vector3(torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype))
+ plane = Hyperplane(normal, Scalar(torch.tensor(0.5, device=device, dtype=dtype)))
+
+ def fn(p):
+ return plane.signed_distance(p).data
+
+ torch._dynamo.reset()
+ p = torch.tensor([[1.0, 2.0, 3.0], [0.0, -1.0, -0.5]], device=device, dtype=dtype)
+ self.assert_close(torch.compile(fn, backend="eager", fullgraph=True)(p), fn(p))