Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Drop JIT support for `core.check`, `Boxes`, and others (#2219)

João Gustavo A. Amorimaffabaf48dd0
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 26219b93f..8c569103c 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -1,5 +1,7 @@
"""The testing package contains testing-specific utilities."""
-from typing import List, Optional, Sequence, cast
+from __future__ import annotations
+
+from typing import Any, Sequence, TypeVar, cast
from typing_extensions import TypeGuard
@@ -22,11 +24,9 @@ __all__ = [
# Logger api
-# TODO: add somehow type check, or enforce to do it before
-# TODO: get rid of torchscript test because prevents us to have type safe code
-
-def KORNIA_CHECK_SHAPE(x: Tensor, shape: List[str]) -> None:
+# TODO: add somehow type check, or enforce to do it before
+def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str]) -> None:
"""Check whether a tensor has a specified shape.
The shape can be specified with a implicit or explicit list of strings.
@@ -71,7 +71,7 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: List[str]) -> None:
raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}")
-def KORNIA_CHECK(condition: bool, msg: Optional[str] = None) -> None:
+def KORNIA_CHECK(condition: bool, msg: str | None = None) -> None:
"""Check any arbitrary boolean condition.
Args:
@@ -89,17 +89,21 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None) -> None:
raise Exception(f"{condition} not true.\n{msg}")
-def KORNIA_UNWRAP(maybe_obj, typ):
+def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:
"""Unwraps an optional contained value that may or not be present.
Args:
maybe_obj: the object to unwrap.
typ: expected type after unwrap.
"""
- return cast(typ, maybe_obj) # type: ignore # TODO: this function will change after kornia/pr#1987
+ # TODO: this function will change after kornia/pr#1987
+ return cast(typ, maybe_obj)
-def KORNIA_CHECK_TYPE(x, typ, msg: Optional[str] = None):
+T = TypeVar('T', bound=type)
+
+
+def KORNIA_CHECK_TYPE(x: object, typ: T, msg: str | None = None) -> TypeGuard[T]:
"""Check the type of an aribratry variable.
Args:
@@ -112,12 +116,15 @@ def KORNIA_CHECK_TYPE(x, typ, msg: Optional[str] = None):
Example:
>>> KORNIA_CHECK_TYPE("foo", str, "Invalid string")
+ True
"""
if not isinstance(x, typ):
raise TypeError(f"Invalid type: {type(x)}.\n{msg}")
+ return True
+
-def KORNIA_CHECK_IS_TENSOR(x, msg: Optional[str] = None):
+def KORNIA_CHECK_IS_TENSOR(x: object, msg: str | None = None) -> TypeGuard[Tensor]:
"""Check the input variable is a Tensor.
Args:
@@ -130,12 +137,15 @@ def KORNIA_CHECK_IS_TENSOR(x, msg: Optional[str] = None):
Example:
>>> x = torch.rand(2, 3, 3)
>>> KORNIA_CHECK_IS_TENSOR(x, "Invalid tensor")
+ True
"""
if not isinstance(x, Tensor):
raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}")
+ return True
+
-def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]]) -> TypeGuard[List[Tensor]]:
+def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Sequence[object] | None) -> TypeGuard[list[Tensor]]:
"""Check the input variable is a List of Tensors.
Args:
@@ -154,7 +164,7 @@ def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]]) -> TypeGuard[L
return isinstance(x, list) and all(isinstance(d, Tensor) for d in x)
-def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor):
+def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor) -> None:
"""Check whether two tensor in the same device.
Args:
@@ -174,7 +184,7 @@ def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor):
raise TypeError(f"Not same device for tensors. Got: {x.device} and {y.device}")
-def KORNIA_CHECK_SAME_DEVICES(tensors: List[Tensor], msg: Optional[str] = None):
+def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: str | None = None) -> None:
"""Check whether a list provided tensors live in the same device.
Args:
@@ -194,7 +204,7 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: List[Tensor], msg: Optional[str] = None):
raise Exception(f"Not same device for tensors. Got: {[x.device for x in tensors]}.\n{msg}")
-def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor) -> None:
+def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor) -> bool:
"""Check whether two tensor have the same shape.
Args:
@@ -209,12 +219,15 @@ def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor) -> None:
>>> x1 = torch.rand(2, 3, 3)
>>> x2 = torch.rand(2, 3, 3)
>>> KORNIA_CHECK_SAME_SHAPE(x1, x2)
+ True
"""
if x.shape != y.shape:
raise TypeError(f"Not same shape for tensors. Got: {x.shape} and {y.shape}")
+ return True
+
-def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None):
+def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: str | None = None) -> bool:
"""Check whether an image tensor is a color images.
Args:
@@ -227,12 +240,14 @@ def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None):
Example:
>>> img = torch.rand(2, 3, 4, 4)
>>> KORNIA_CHECK_IS_COLOR(img, "Image is not color")
+ True
"""
if len(x.shape) < 3 or x.shape[-3] != 3:
raise TypeError(f"Not a color tensor. Got: {type(x)}.\n{msg}")
+ return True
-def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None):
+def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: str | None = None) -> bool:
"""Check whether an image tensor is grayscale.
Args:
@@ -245,12 +260,14 @@ def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None):
Example:
>>> img = torch.rand(2, 1, 4, 4)
>>> KORNIA_CHECK_IS_GRAY(img, "Image is not grayscale")
+ True
"""
if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1):
raise TypeError(f"Not a gray tensor. Got: {type(x)}.\n{msg}")
+ return True
-def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None):
+def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: str | None = None) -> bool:
"""Check whether an image tensor is grayscale or color.
Args:
@@ -262,13 +279,15 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None):
Example:
>>> img = torch.rand(2, 3, 4, 4)
- >>> KORNIA_CHECK_IS_COLOR_OR_GRAY(img, "Image is not color or grayscale")
+ >>> KORNIA_CHECK_IS_COLOR_OR_GRAY(img, "Image is not color orgrayscale")
+ True
"""
if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:
raise TypeError(f"Not a color or gray tensor. Got: {type(x)}.\n{msg}")
+ return True
-def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor):
+def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor) -> bool:
"""Check whether the provided descriptors match with a distance matrix.
Args:
@@ -284,12 +303,14 @@ def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor):
>>> desc2 = torch.rand(8)
>>> dm = torch.rand(4, 8)
>>> KORNIA_CHECK_DM_DESC(desc1, desc2, dm)
+ True
"""
if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
- message = f"""distance matrix shape {dm.shape} is not
- consistent with descriptors shape: desc1 {desc1.shape}
- desc2 {desc2.shape}"""
- raise TypeError(message)
+ raise TypeError(
+ f"distance matrix shape {dm.shape} is not onsistent with descriptors shape: desc1 {desc1.shape} "
+ f"desc2 {desc2.shape}"
+ )
+ return True
def KORNIA_CHECK_LAF(laf: Tensor) -> None:
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index a029fc51e..c1a587ef4 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
import warnings
-from typing import Optional, Tuple
import torch
@@ -19,7 +20,6 @@ __all__ = [
]
def validate_bbox(boxes: torch.Tensor) -> bool:
"""Validate if a 2D bounding box usable or not. This function checks if the boxes are rectangular or not.
@@ -49,7 +49,6 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
return True
def validate_bbox3d(boxes: torch.Tensor) -> bool:
"""Validate if a 3D bounding box usable or not. This function checks if the boxes are cube or not.
@@ -84,7 +83,7 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:
return True
-def infer_bbox_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Auto-infer the output sizes for the given 2D bounding boxes.
Args:
@@ -117,7 +116,7 @@ def infer_bbox_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
return height, width
-def infer_bbox_shape3d(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Auto-infer the output sizes for the given 3D bounding boxes.
Args:
@@ -207,7 +206,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
return mask[:, 1:-1, 1:-1]
-def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Tensor:
+def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Tensor:
"""Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.
Args:
@@ -440,7 +439,7 @@ def bbox_generator3d(
def transform_bbox(
- trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy", restore_coordinates: Optional[bool] = None
+ trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy", restore_coordinates: bool | None = None
) -> torch.Tensor:
r"""Apply a transformation matrix to a box or batch of boxes.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 60facfdef..6190faf9f 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1,4 +1,6 @@
-from typing import List, Optional, Tuple, Union, cast
+from __future__ import annotations
+
+from typing import cast
import torch
@@ -14,7 +16,7 @@ def _is_floating_point_dtype(dtype: torch.dtype) -> bool:
return dtype in (torch.float16, torch.float32, torch.float64, torch.bfloat16, torch.half)
-def _merge_box_list(boxes: List[torch.Tensor], method: str = "pad") -> Tuple[torch.Tensor, List[int]]:
+def _merge_box_list(boxes: list[torch.Tensor], method: str = "pad") -> tuple[torch.Tensor, list[int]]:
r"""Merge a list of boxes into one tensor."""
if not all(box.shape[-2:] == torch.Size([4, 2]) and box.dim() == 3 for box in boxes):
raise TypeError(f"Input boxes must be a list of (N, 4, 2) shaped. Got: {[box.shape for box in boxes]}.")
@@ -164,7 +166,6 @@ def _boxes3d_to_polygons3d(
return polygons3d
-# @torch.jit.script
class Boxes:
r"""2D boxes containing N or BxN boxes.
@@ -186,11 +187,11 @@ class Boxes:
def __init__(
self,
- boxes: Union[torch.Tensor, List[torch.Tensor]],
+ boxes: torch.Tensor | list[torch.Tensor],
raise_if_not_floating_point: bool = True,
mode: str = "vertices_plus",
) -> None:
- self._N: Optional[List[int]] = None
+ self._N: list[int] | None = None
if isinstance(boxes, list):
boxes, self._N = _merge_box_list(boxes)
@@ -205,8 +206,6 @@ class Boxes:
boxes = boxes.float()
if len(boxes.shape) == 0:
- # Use reshape, so we don't end up creating a new tensor that does not depend on
- # the inputs (and consequently confuses jit)
boxes = boxes.reshape((-1, 4))
if not (3 <= boxes.ndim <= 4 and boxes.shape[-2:] == (4, 2)):
@@ -217,12 +216,12 @@ class Boxes:
self._data = boxes
self._mode = mode
- def __getitem__(self, key) -> "Boxes":
+ def __getitem__(self, key) -> Boxes:
new_box = type(self)(self._data[key], False)
new_box._mode = self._mode
return new_box
- def __setitem__(self, key, value: "Boxes") -> "Boxes":
+ def __setitem__(self, key, value: Boxes) -> Boxes:
self._data[key] = value._data
return self
@@ -230,7 +229,7 @@ class Boxes:
def shape(self):
return self.data.shape
- def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor]:
+ def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor]:
r"""Compute boxes heights and widths.
Returns:
@@ -247,7 +246,7 @@ class Boxes:
widths, heights = boxes_xywh[..., 2], boxes_xywh[..., 3]
return heights, widths
- def merge(self, boxes: "Boxes", inplace: bool = False) -> "Boxes":
+ def merge(self, boxes: Boxes, inplace: bool = False) -> Boxes:
"""Merges boxes.
Say, current instance holds :math:`(B, N, 4, 2)` and the incoming boxes holds :math:`(B, M, 4, 2)`,
@@ -267,8 +266,8 @@ class Boxes:
return obj
def index_put(
- self, indices: Union[Tuple[Tensor, ...], List[Tensor]], values: Union[Tensor, "Boxes"], inplace: bool = False
- ) -> "Boxes":
+ self, indices: tuple[Tensor, ...] | list[Tensor], values: Tensor | Boxes, inplace: bool = False
+ ) -> Boxes:
if inplace:
_data = self._data
else:
@@ -286,7 +285,7 @@ class Boxes:
obj._data = _data
return obj
- def pad(self, padding_size: Tensor) -> "Boxes":
+ def pad(self, padding_size: Tensor) -> Boxes:
"""Pad a bounding box.
Args:
@@ -298,7 +297,7 @@ class Boxes:
self._data[..., 1] += padding_size[..., None, 2:3].to(device=self._data.device) # top padding
return self
- def unpad(self, padding_size: Tensor) -> "Boxes":
+ def unpad(self, padding_size: Tensor) -> Boxes:
"""Pad a bounding box.
Args:
@@ -312,10 +311,10 @@ class Boxes:
def clamp(
self,
- topleft: Optional[Union[Tensor, Tuple[int, int]]] = None,
- botright: Optional[Union[Tensor, Tuple[int, int]]] = None,
+ topleft: Tensor | tuple[int, int] | None = None,
+ botright: Tensor | tuple[int, int] | None = None,
inplace: bool = False,
- ) -> "Boxes":
+ ) -> Boxes:
""""""
if not (isinstance(topleft, Tensor) and isinstance(botright, Tensor)):
raise NotImplementedError
@@ -341,7 +340,7 @@ class Boxes:
obj._data = _data
return obj
- def trim(self, correspondence_preserve: bool = False, inplace: bool = False) -> "Boxes":
+ def trim(self, correspondence_preserve: bool = False, inplace: bool = False) -> Boxes:
"""Trim out zero padded boxes.
Given box arrangements of shape :math:`(4, 4, Box)`:
@@ -372,8 +371,8 @@ class Boxes:
raise NotImplementedError
def filter_boxes_by_area(
- self, min_area: Optional[float] = None, max_area: Optional[float] = None, inplace: bool = False
- ) -> "Boxes":
+ self, min_area: float | None = None, max_area: float | None = None, inplace: bool = False
+ ) -> Boxes:
area = self.compute_area()
if inplace:
_data = self._data
@@ -398,8 +397,8 @@ class Boxes:
@classmethod
def from_tensor(
- cls, boxes: Union[torch.Tensor, List[torch.Tensor]], mode: str = "xyxy", validate_boxes: bool = True
- ) -> "Boxes":
+ cls, boxes: torch.Tensor | list[torch.Tensor], mode: str = "xyxy", validate_boxes: bool = True
+ ) -> Boxes:
r"""Helper method to easily create :class:`Boxes` from boxes stored in another format.
Args:
@@ -441,19 +440,15 @@ class Boxes:
[7., 3.],
[5., 3.]]])
"""
- quadrilaterals: Union[torch.Tensor, List[torch.Tensor]]
+ quadrilaterals: torch.Tensor | list[torch.Tensor]
if isinstance(boxes, (torch.Tensor)):
quadrilaterals = _boxes_to_quadrilaterals(boxes, mode=mode, validate_boxes=validate_boxes)
else:
quadrilaterals = [_boxes_to_quadrilaterals(box, mode, validate_boxes) for box in boxes]
- # Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
- # constructing the class from inside of a method.
return cls(quadrilaterals, False, mode)
- def to_tensor(
- self, mode: Optional[str] = None, as_padded_sequence: bool = False
- ) -> Union[torch.Tensor, List[torch.Tensor]]:
+ def to_tensor(self, mode: str | None = None, as_padded_sequence: bool = False) -> torch.Tensor | list[torch.Tensor]:
r"""Cast :class:`Boxes` to a tensor. ``mode`` controls which 2D boxes format should be use to represent
boxes in the tensor.
@@ -487,7 +482,7 @@ class Boxes:
"""
batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)
- boxes: Union[torch.Tensor, List[torch.Tensor]]
+ boxes: torch.Tensor | list[torch.Tensor]
# Create boxes in xyxy_plus format.
boxes = torch.stack([batched_boxes.amin(dim=-2), batched_boxes.amax(dim=-2)], dim=-2).view(
@@ -576,7 +571,7 @@ class Boxes:
return mask
- def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> "Boxes":
+ def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> Boxes:
r"""Apply a transformation matrix to the 2D boxes.
Args:
@@ -589,8 +584,6 @@ class Boxes:
if not 2 <= M.ndim <= 3 or M.shape[-2:] != (3, 3):
raise ValueError(f"The transformation matrix shape must be (3, 3) or (B, 3, 3). Got {M.shape}.")
- # Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
- # constructing the class from inside of a method.
transformed_boxes = _transform_boxes(self._data, M)
if inplace:
self._data = transformed_boxes
@@ -600,11 +593,11 @@ class Boxes:
obj._data = transformed_boxes
return obj
- def transform_boxes_(self, M: torch.Tensor) -> "Boxes":
+ def transform_boxes_(self, M: torch.Tensor) -> Boxes:
"""Inplace version of :func:`Boxes.transform_boxes`"""
return self.transform_boxes(M, inplace=True)
- def translate(self, size: Tensor, method: str = "warp", inplace: bool = False) -> "Boxes":
+ def translate(self, size: Tensor, method: str = "warp", inplace: bool = False) -> Boxes:
"""Translates boxes by the provided size.
Args:
@@ -644,7 +637,7 @@ class Boxes:
"""Returns boxes dtype."""
return self._data.dtype
- def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> "Boxes":
+ def to(self, device: torch.device | None = None, dtype: torch.dtype | None = None) -> Boxes:
"""Like :func:`torch.nn.Module.to()` method."""
# In torchscript, dtype is a int and not a class. https://github.com/pytorch/pytorch/issues/51941
if dtype is not None and not _is_floating_point_dtype(dtype):
@@ -652,14 +645,14 @@ class Boxes:
self._data = self._data.to(device=device, dtype=dtype)
return self
- def clone(self) -> "Boxes":
+ def clone(self) -> Boxes:
obj = type(self)(self._data.clone(), False)
obj._mode = self._mode
obj._N = self._N
obj._is_batched = self._is_batched
return obj
- def type(self, dtype: torch.dtype) -> "Boxes":
+ def type(self, dtype: torch.dtype) -> Boxes:
self._data = self._data.type(dtype)
return self
@@ -669,8 +662,8 @@ class VideoBoxes(Boxes):
@classmethod
def from_tensor( # type: ignore[override]
- cls, boxes: Union[torch.Tensor, List[torch.Tensor]], validate_boxes: bool = True
- ) -> "VideoBoxes":
+ cls, boxes: torch.Tensor | list[torch.Tensor], validate_boxes: bool = True
+ ) -> VideoBoxes:
if isinstance(boxes, (list,)) or (boxes.dim() != 5 or boxes.shape[-2:] != torch.Size([4, 2])):
raise ValueError("Input box type is not yet supported. Please input an `BxTxNx4x2` tensor directly.")
@@ -681,22 +674,18 @@ class VideoBoxes(Boxes):
mode="vertices_plus",
validate_boxes=validate_boxes,
)
- # Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
- # constructing the class from inside of a method.
out = cls(quadrilaterals, False, "vertices_plus")
out.temporal_channel_size = temporal_channel_size
return out
- def to_tensor( # type: ignore[override]
- self, mode: Optional[str] = None
- ) -> Union[torch.Tensor, List[torch.Tensor]]:
+ def to_tensor(self, mode: str | None = None) -> torch.Tensor | list[torch.Tensor]: # type: ignore[override]
out = super().to_tensor(mode, as_padded_sequence=False)
if isinstance(out, Tensor):
return out.view(-1, self.temporal_channel_size, *out.shape[1:])
# If returns a list of boxes.
return [_out.view(-1, self.temporal_channel_size, *_out.shape[1:]) for _out in out]
- def clone(self) -> "VideoBoxes":
+ def clone(self) -> VideoBoxes:
obj = type(self)(self._data.clone(), False)
obj._mode = self._mode
obj._N = self._N
@@ -705,7 +694,6 @@ class VideoBoxes(Boxes):
return obj
class Boxes3D:
r"""3D boxes containing N or BxN boxes.
@@ -735,8 +723,6 @@ class Boxes3D:
boxes = boxes.float()
if len(boxes.shape) == 0:
- # Use reshape, so we don't end up creating a new tensor that does not depend on
- # the inputs (and consequently confuses jit)
boxes = boxes.reshape((-1, 6))
if not (3 <= boxes.ndim <= 4 and boxes.shape[-2:] == (8, 3)):
@@ -747,12 +733,12 @@ class Boxes3D:
self._data = boxes
self._mode = mode
- def __getitem__(self, key) -> "Boxes3D":
+ def __getitem__(self, key) -> Boxes3D:
new_box = Boxes3D(self._data[key], False, mode="xyzxyz_plus")
new_box._mode = self._mode
return new_box
- def __setitem__(self, key, value: "Boxes3D") -> "Boxes3D":
+ def __setitem__(self, key, value: Boxes3D) -> Boxes3D:
self._data[key] = value._data
return self
@@ -760,7 +746,7 @@ class Boxes3D:
def shape(self):
return self.data.shape
- def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Compute boxes heights and widths.
Returns:
@@ -779,7 +765,7 @@ class Boxes3D:
return depths, heights, widths
@classmethod
- def from_tensor(cls, boxes: torch.Tensor, mode: str = "xyzxyz", validate_boxes: bool = True) -> "Boxes3D":
+ def from_tensor(cls, boxes: torch.Tensor, mode: str = "xyzxyz", validate_boxes: bool = True) -> Boxes3D:
r"""Helper method to easily create :class:`Boxes3D` from 3D boxes stored in another format.
Args:
@@ -853,8 +839,6 @@ class Boxes3D:
hexahedrons = _boxes3d_to_polygons3d(xmin, ymin, zmin, width, height, depth)
hexahedrons = hexahedrons if batched else hexahedrons.squeeze(0)
- # Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
- # constructing the class from inside of a method.
return cls(hexahedrons, raise_if_not_floating_point=False, mode=mode)
def to_tensor(self, mode: str = "xyzxyz") -> torch.Tensor:
@@ -1019,7 +1003,7 @@ class Boxes3D:
return mask
- def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> "Boxes3D":
+ def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> Boxes3D:
r"""Apply a transformation matrix to the 3D boxes.
Args:
@@ -1032,8 +1016,6 @@ class Boxes3D:
if not 2 <= M.ndim <= 3 or M.shape[-2:] != (4, 4):
raise ValueError(f"The transformation matrix shape must be (4, 4) or (B, 4, 4). Got {M.shape}.")
- # Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
- # constructing the class from inside of a method.
transformed_boxes = _transform_boxes(self._data, M)
if inplace:
self._data = transformed_boxes
@@ -1041,7 +1023,7 @@ class Boxes3D:
return Boxes3D(transformed_boxes, False, "xyzxyz_plus")
- def transform_boxes_(self, M: torch.Tensor) -> "Boxes3D":
+ def transform_boxes_(self, M: torch.Tensor) -> Boxes3D:
"""Inplace version of :func:`Boxes3D.transform_boxes`"""
return self.transform_boxes(M, inplace=True)
@@ -1063,7 +1045,7 @@ class Boxes3D:
"""Returns boxes dtype."""
return self._data.dtype
- def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> "Boxes3D":
+ def to(self, device: torch.device | None = None, dtype: torch.dtype | None = None) -> Boxes3D:
"""Like :func:`torch.nn.Module.to()` method."""
# In torchscript, dtype is a int and not a class. https://github.com/pytorch/pytorch/issues/51941
if dtype is not None and not _is_floating_point_dtype(dtype):
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 65f5d4ec2..69e723d54 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from __future__ import annotations
import torch
@@ -11,7 +11,7 @@ from .distort import distort_points, tilt_projection
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384
def undistort_points(
- points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor, new_K: Optional[torch.Tensor] = None, num_iters: int = 5
+ points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor, new_K: torch.Tensor | None = None, num_iters: int = 5
) -> torch.Tensor:
r"""Compensate for lens distortion a set of 2D image points.
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index a11e82714..a77ace384 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
from torch import Tensor
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 02864102f..8c126d15e 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from __future__ import annotations
import torch
import torch.nn as nn
@@ -27,7 +27,7 @@ class HomographyWarper(nn.Module):
normalized_coordinates: whether to use a grid with normalized coordinates.
align_corners: interpolation flag.
"""
- _warped_grid: Optional[torch.Tensor]
+ _warped_grid: torch.Tensor | None
def __init__(
self,
@@ -65,7 +65,7 @@ class HomographyWarper(nn.Module):
"""
self._warped_grid = warp_grid(self.grid, src_homo_dst)
- def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
+ def forward(self, patch_src: torch.Tensor, src_homo_dst: torch.Tensor | None = None) -> torch.Tensor:
r"""Warp a tensor from source into reference frame.
Args:
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index b16f307e5..6fce98316 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Tuple
+from __future__ import annotations
import torch
import torch.nn.functional as F
@@ -47,7 +47,7 @@ __all__ = [
def warp_perspective(
src: Tensor,
M: Tensor,
- dsize: Tuple[int, int],
+ dsize: tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
@@ -133,7 +133,7 @@ def warp_perspective(
def warp_affine(
src: Tensor,
M: Tensor,
- dsize: Tuple[int, int],
+ dsize: tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
@@ -468,7 +468,7 @@ def remap(
map_y: Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None,
+ align_corners: bool | None = None,
normalized_coordinates: bool = False,
) -> Tensor:
r"""Apply a generic geometrical transformation to an image tensor.
@@ -572,8 +572,8 @@ def get_affine_matrix2d(
center: Tensor,
scale: Tensor,
angle: Tensor,
- sx: Optional[Tensor] = None,
- sy: Optional[Tensor] = None,
+ sx: Tensor | None = None,
+ sy: Tensor | None = None,
) -> Tensor:
r"""Compose affine matrix from the components.
@@ -625,7 +625,7 @@ def get_translation_matrix2d(translations: Tensor) -> Tensor:
return transform_h
-def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional[Tensor] = None):
+def get_shear_matrix2d(center: Tensor, sx: Tensor | None = None, sy: Tensor | None = None):
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis.
@@ -680,12 +680,12 @@ def get_affine_matrix3d(
center: Tensor,
scale: Tensor,
angles: Tensor,
- sxy: Optional[Tensor] = None,
- sxz: Optional[Tensor] = None,
- syx: Optional[Tensor] = None,
- syz: Optional[Tensor] = None,
- szx: Optional[Tensor] = None,
- szy: Optional[Tensor] = None,
+ sxy: Tensor | None = None,
+ sxz: Tensor | None = None,
+ syx: Tensor | None = None,
+ syz: Tensor | None = None,
+ szx: Tensor | None = None,
+ szy: Tensor | None = None,
) -> Tensor:
r"""Compose 3d affine matrix from the components.
@@ -723,12 +723,12 @@ def get_affine_matrix3d(
def get_shear_matrix3d(
center: Tensor,
- sxy: Optional[Tensor] = None,
- sxz: Optional[Tensor] = None,
- syx: Optional[Tensor] = None,
- syz: Optional[Tensor] = None,
- szx: Optional[Tensor] = None,
- szy: Optional[Tensor] = None,
+ sxy: Tensor | None = None,
+ sxz: Tensor | None = None,
+ syx: Tensor | None = None,
+ syz: Tensor | None = None,
+ szx: Tensor | None = None,
+ szy: Tensor | None = None,
):
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis then z-axis.
@@ -829,7 +829,7 @@ def _compute_shear_matrix_3d(sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_ta
def warp_affine3d(
src: Tensor,
M: Tensor,
- dsize: Tuple[int, int, int],
+ dsize: tuple[int, int, int],
flags: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
@@ -863,8 +863,8 @@ def warp_affine3d(
raise AssertionError(dsize)
B, C, D, H, W = src.size()
- size_src: Tuple[int, int, int] = (D, H, W)
- size_out: Tuple[int, int, int] = dsize
+ size_src: tuple[int, int, int] = (D, H, W)
+ size_out: tuple[int, int, int] = dsize
M_4x4 = convert_affinematrix_to_homography3d(M) # Bx4x4
@@ -875,7 +875,7 @@ def warp_affine3d(
P_norm: Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
# compute meshgrid and apply to input
- dsize_out: List[int] = [B, C] + list(size_out)
+ dsize_out: list[int] = [B, C] + list(size_out)
grid = F.affine_grid(P_norm, dsize_out, align_corners=align_corners)
return grid_sample(src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode)
@@ -1174,7 +1174,7 @@ def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
def warp_perspective3d(
src: Tensor,
M: Tensor,
- dsize: Tuple[int, int, int],
+ dsize: tuple[int, int, int],
flags: str = 'bilinear',
border_mode: str = 'zeros',
align_corners: bool = False,
@@ -1226,7 +1226,7 @@ def warp_perspective3d(
def homography_warp(
patch_src: Tensor,
src_homo_dst: Tensor,
- dsize: Tuple[int, int],
+ dsize: tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
@@ -1287,8 +1287,8 @@ def homography_warp(
def _transform_warp_impl3d(
src: Tensor,
dst_pix_trans_src_pix: Tensor,
- dsize_src: Tuple[int, int, int],
- dsize_dst: Tuple[int, int, int],
+ dsize_src: tuple[int, int, int],
+ dsize_dst: tuple[int, int, int],
grid_mode: str,
padding_mode: str,
align_corners: bool,
@@ -1303,7 +1303,7 @@ def _transform_warp_impl3d(
def homography_warp3d(
patch_src: Tensor,
src_homo_dst: Tensor,
- dsize: Tuple[int, int, int],
+ dsize: tuple[int, int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 3a1c69614..02d09fa08 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
import math
-from typing import List, Tuple
import torch
import torch.nn.functional as F
@@ -161,7 +162,7 @@ class ScalePyramid(Module):
ksize += 1
return ksize
- def get_first_level(self, input: Tensor) -> Tuple[Tensor, float, float]:
+ def get_first_level(self, input: Tensor) -> tuple[Tensor, float, float]:
pixel_distance = 1.0
cur_sigma = 0.5
# Same as in OpenCV up to interpolation difference
@@ -181,7 +182,7 @@ class ScalePyramid(Module):
cur_level = x
return cur_level, cur_sigma, pixel_distance
- def forward(self, x: Tensor) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]:
+ def forward(self, x: Tensor) -> tuple[list[Tensor], list[Tensor], list[Tensor]]:
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
@@ -301,7 +302,7 @@ def pyrup(input: Tensor, border_type: str = 'reflect', align_corners: bool = Fal
def build_pyramid(
input: Tensor, max_level: int, border_type: str = 'reflect', align_corners: bool = False
-) -> List[Tensor]:
+) -> list[Tensor]:
r"""Construct the Gaussian pyramid for a tensor image.
.. image:: _static/img/build_pyramid.png
@@ -329,7 +330,7 @@ def build_pyramid(
)
# create empty list and append the original image
- pyramid: List[Tensor] = []
+ pyramid: list[Tensor] = []
pyramid.append(input)
# iterate and downsample
@@ -354,7 +355,7 @@ def find_next_powerof_two(x):
def build_laplacian_pyramid(
input: Tensor, max_level: int, border_type: str = 'reflect', align_corners: bool = False
-) -> List[Tensor]:
+) -> list[Tensor]:
r"""Construct the Laplacian pyramid for a tensor image.
The function constructs a vector of images and builds the Laplacian pyramid
@@ -393,9 +394,9 @@ def build_laplacian_pyramid(
input = pad(input, padding, "reflect")
# create gaussian pyramid
- gaussian_pyramid: List[Tensor] = build_pyramid(input, max_level, border_type, align_corners)
+ gaussian_pyramid: list[Tensor] = build_pyramid(input, max_level, border_type, align_corners)
# create empty list
- laplacian_pyramid: List[Tensor] = []
+ laplacian_pyramid: list[Tensor] = []
# iterate and compute difference of adjacent layers in a gaussian pyramid
for i in range(max_level - 1):
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index ac9b309fe..e80c71e84 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from .cauchy import CauchyLoss, cauchy_loss
from .charbonnier import CharbonnierLoss, charbonnier_loss
from .depth_smooth import InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss
diff --git a/kornia/losses/cauchy.py b/kornia/losses/cauchy.py
index 76d5d4e74..f75dec42f 100644
--- a/kornia/losses/cauchy.py
+++ b/kornia/losses/cauchy.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from torch import Tensor
from kornia.core import Module
diff --git a/kornia/losses/charbonnier.py b/kornia/losses/charbonnier.py
index 8cc966c22..651adffa9 100644
--- a/kornia/losses/charbonnier.py
+++ b/kornia/losses/charbonnier.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from torch import Tensor
from kornia.core import Module
diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.py
index ba97da229..b520e97a4 100644
--- a/kornia/losses/depth_smooth.py
+++ b/kornia/losses/depth_smooth.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
import torch.nn as nn
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 138c381e6..11a5a8335 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
import torch.nn as nn
import torch.nn.functional as F
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 5f99e9a2c..9331e7e0c 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -1,5 +1,7 @@
r"""Losses based on the divergence between probability distributions."""
+from __future__ import annotations
+
import torch
import torch.nn.functional as F
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 2ea43f397..cdee97727 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -1,5 +1,6 @@
+from __future__ import annotations
+
import warnings
-from typing import Optional
import torch
import torch.nn as nn
@@ -13,12 +14,7 @@ from kornia.utils.one_hot import one_hot
def focal_loss(
- input: Tensor,
- target: Tensor,
- alpha: float,
- gamma: float = 2.0,
- reduction: str = 'none',
- eps: Optional[float] = None,
+ input: Tensor, target: Tensor, alpha: float, gamma: float = 2.0, reduction: str = 'none', eps: float | None = None
) -> Tensor:
r"""Criterion that computes Focal loss.
@@ -134,12 +130,12 @@ class FocalLoss(nn.Module):
>>> output.backward()
"""
- def __init__(self, alpha: float, gamma: float = 2.0, reduction: str = 'none', eps: Optional[float] = None) -> None:
+ def __init__(self, alpha: float, gamma: float = 2.0, reduction: str = 'none', eps: float | None = None) -> None:
super().__init__()
self.alpha: float = alpha
self.gamma: float = gamma
self.reduction: str = reduction
- self.eps: Optional[float] = eps
+ self.eps: float | None = eps
def forward(self, input: Tensor, target: Tensor) -> Tensor:
return focal_loss(input, target, self.alpha, self.gamma, self.reduction, self.eps)
@@ -151,8 +147,8 @@ def binary_focal_loss_with_logits(
alpha: float = 0.25,
gamma: float = 2.0,
reduction: str = 'none',
- eps: Optional[float] = None,
- pos_weight: Optional[Tensor] = None,
+ eps: float | None = None,
+ pos_weight: Tensor | None = None,
) -> Tensor:
r"""Function that computes Binary Focal loss.
@@ -269,13 +265,13 @@ class BinaryFocalLossWithLogits(nn.Module):
"""
def __init__(
- self, alpha: float, gamma: float = 2.0, reduction: str = 'none', pos_weight: Optional[Tensor] = None
+ self, alpha: float, gamma: float = 2.0, reduction: str = 'none', pos_weight: Tensor | None = None
) -> None:
super().__init__()
self.alpha: float = alpha
self.gamma: float = gamma
self.reduction: str = reduction
- self.pos_weight: Optional[Tensor] = pos_weight
+ self.pos_weight: Tensor | None = pos_weight
def forward(self, input: Tensor, target: Tensor) -> Tensor:
return binary_focal_loss_with_logits(
diff --git a/kornia/losses/geman_mcclure.py b/kornia/losses/geman_mcclure.py
index 6eaba99b3..a0b1090dc 100644
--- a/kornia/losses/geman_mcclure.py
+++ b/kornia/losses/geman_mcclure.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from torch import Tensor
from kornia.core import Module
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index b62a1a835..9c96a74fa 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -1,12 +1,14 @@
+from __future__ import annotations
+
from typing import Callable
import torch
import torch.nn as nn
-from kornia.core import Tensor, as_tensor, stack, tensor, where, zeros_like
+from kornia.core import Module, Tensor, as_tensor, stack, tensor, where, zeros_like
-class _HausdorffERLossBase(torch.jit.ScriptModule):
+class _HausdorffERLossBase(Module):
"""Base class for binary Hausdorff loss based on morphological erosion.
This is an Hausdorff Distance (HD) Loss that based on morphological erosion,which provided
@@ -47,8 +49,7 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):
mask = torch.ones_like(bound, device=pred.device, dtype=torch.bool)
# Same padding, assuming kernel is odd and square (cube) shaped.
- # NOTE: int() has to be added for enabling JIT.
- padding = int((kernel.size(-1) - 1) // 2)
+ padding = (kernel.size(-1) - 1) // 2
for k in range(self.k):
# compute convolution with kernel
dilation = self.conv(bound, weight=kernel, padding=padding, groups=1)
@@ -75,8 +76,7 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):
return eroded
- # NOTE: we add type ignore because the forward pass does not work well with subclassing
- def forward(self, pred: Tensor, target: Tensor) -> Tensor: # type: ignore[override]
+ def forward(self, pred: Tensor, target: Tensor) -> Tensor:
"""Compute Hausdorff loss.
Args:
@@ -167,8 +167,7 @@ class HausdorffERLoss(_HausdorffERLossBase):
kernel = cross * 0.2
return kernel[None]
- # NOTE: we add type ignore because the forward pass does not work well with subclassing
- def forward(self, pred: Tensor, target: Tensor) -> Tensor: # type: ignore[override]
+ def forward(self, pred: Tensor, target: Tensor) -> Tensor:
"""Compute Hausdorff loss.
Args:
@@ -238,8 +237,7 @@ class HausdorffERLoss3D(_HausdorffERLossBase):
kernel = stack([bound, cross, bound], 1) * (1 / 7)
return kernel[None]
- # NOTE: we add type ignore because the forward pass does not work well with subclassing
- def forward(self, pred: Tensor, target: Tensor) -> Tensor: # type: ignore[override]
+ def forward(self, pred: Tensor, target: Tensor) -> Tensor:
"""Compute 3D Hausdorff loss.
Args:
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index 4ddac4440..464fc3166 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
import torch.nn as nn
from torch import Tensor
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index c58490fa9..47bfe8fa0 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -1,4 +1,4 @@
-from typing import List
+from __future__ import annotations
import torch
import torch.nn as nn
@@ -77,7 +77,7 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor) -> Tensor:
pred_soft: Tensor = pred_flatten.softmax(1)
# compute actual loss
- losses: List[Tensor] = []
+ losses: list[Tensor] = []
batch_index: Tensor = torch.arange(B, device=pred.device).reshape(-1, 1).repeat(1, N).reshape(-1)
for c in range(C):
foreground: Tensor = 1.0 * (target_flatten == c)
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index b43e9e47a..0b8514835 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Tuple
+from __future__ import annotations
import torch
import torch.nn as nn
@@ -54,9 +54,9 @@ class MS_SSIMLoss(nn.Module):
def __init__(
self,
- sigmas: List[float] = [0.5, 1.0, 2.0, 4.0, 8.0],
+ sigmas: list[float] = [0.5, 1.0, 2.0, 4.0, 8.0],
data_range: float = 1.0,
- K: Tuple[float, float] = (0.01, 0.03),
+ K: tuple[float, float] = (0.01, 0.03),
alpha: float = 0.025,
compensation: float = 200.0,
reduction: str = 'mean',
@@ -83,7 +83,7 @@ class MS_SSIMLoss(nn.Module):
self.register_buffer('_g_masks', g_masks)
def _fspecial_gauss_1d(
- self, size: int, sigma: float, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ self, size: int, sigma: float, device: torch.device | None = None, dtype: torch.dtype | None = None
) -> torch.Tensor:
"""Create 1-D gauss kernel.
@@ -101,7 +101,7 @@ class MS_SSIMLoss(nn.Module):
return g.reshape(-1)
def _fspecial_gauss_2d(
- self, size: int, sigma: float, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ self, size: int, sigma: float, device: torch.device | None = None, dtype: torch.dtype | None = None
) -> torch.Tensor:
"""Create 2-D gauss kernel.
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index e091ac729..5d9a75055 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
import torch.nn as nn
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index 721a4b2e2..0e9846089 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
import torch.nn as nn
diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.py
index 875182d5c..f581c458c 100644
--- a/kornia/losses/ssim3d.py
+++ b/kornia/losses/ssim3d.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import kornia.metrics as metrics
from kornia.core import Module, Tensor
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index a19dab90a..bec32ecff 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from kornia.core import Module, Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index ae73fb39f..026f778e8 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import torch
import torch.nn as nn
import torch.nn.functional as F
diff --git a/kornia/losses/welsch.py b/kornia/losses/welsch.py
index 1238f6d0c..dc4f2e766 100644
--- a/kornia/losses/welsch.py
+++ b/kornia/losses/welsch.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from torch import Tensor
from kornia.core import Module
diff --git a/test/color/test_colormap.py b/test/color/test_colormap.py
index c1af47cec..a7d62eb05 100644
--- a/test/color/test_colormap.py
+++ b/test/color/test_colormap.py
@@ -73,9 +73,9 @@ class TestApplyColorMap(BaseTester):
assert gradcheck(apply_colormap, (input_tensor, cm), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
op = apply_colormap
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
cm = AUTUMN(device=device, dtype=dtype)
img = torch.ones(1, 3, 3, device=device, dtype=dtype)
diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.py
index 7b9e1eae2..99e225490 100644
--- a/test/enhance/test_adjust.py
+++ b/test/enhance/test_adjust.py
@@ -774,13 +774,12 @@ class TestAdjustSigmoid(BaseTester):
f = kornia.enhance.AdjustSigmoid()
self.assert_close(f(data), expected)
- @pytest.mark.jit
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.enhance.adjust_sigmoid
- op_jit = torch.jit.script(op)
- self.assert_close(op(img), op_jit(img))
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img), op_optimized(img))
@pytest.mark.grad
def test_gradcheck(self, device, dtype):
@@ -844,13 +843,12 @@ class TestAdjustLog(BaseTester):
f = kornia.enhance.AdjustLog()
self.assert_close(f(data), expected)
- @pytest.mark.jit
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.enhance.adjust_log
- op_jit = torch.jit.script(op)
- self.assert_close(op(img), op_jit(img))
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img), op_optimized(img))
@pytest.mark.grad
def test_gradcheck(self, device, dtype):
diff --git a/test/enhance/test_core.py b/test/enhance/test_core.py
index 32e447d50..436021bdc 100644
--- a/test/enhance/test_core.py
+++ b/test/enhance/test_core.py
@@ -8,7 +8,6 @@ import kornia
import kornia.testing as utils # test utils
from kornia.core import Tensor
from kornia.testing import assert_close
-from kornia.utils._compat import torch_version_le
def random_shape(dim, min_elem=1, max_elem=10):
@@ -54,17 +53,14 @@ class TestAddWeighted:
gamma = gamma.to(src1)
assert_close(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
- @pytest.mark.skipif(
- torch_version_le(1, 13, 0), reason="`Union` type hint not supported in JIT with PyTorch <= 1.11.0"
- )
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
inputs = (src1, alpha, src2, beta, gamma)
op = TestAddWeighted.fcn
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(*inputs), op_script(*inputs), atol=1e-4, rtol=1e-4)
+ assert_close(op(*inputs), op_optimized(*inputs), atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("size", [2, 3])
def test_gradcheck(self, size, device, dtype):
diff --git a/test/geometry/calibration/test_undistort.py b/test/geometry/calibration/test_undistort.py
index 11f0777e4..e44f06cc7 100644
--- a/test/geometry/calibration/test_undistort.py
+++ b/test/geometry/calibration/test_undistort.py
@@ -233,7 +233,7 @@ class TestUndistortPoints:
gradcheck(undistort_points, (points, K, distCoeff, new_K))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
points = torch.rand(1, 1, 2, device=device, dtype=dtype)
K = torch.rand(1, 3, 3, device=device, dtype=dtype)
new_K = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -241,8 +241,8 @@ class TestUndistortPoints:
inputs = (points, K, distCoeff, new_K)
op = undistort_points
- op_jit = torch.jit.script(op)
- assert_close(op(*inputs), op_jit(*inputs))
+ op_optimized = torch_optimizer(op)
+ assert_close(op(*inputs), op_optimized(*inputs))
class TestUndistortImage:
@@ -342,12 +342,14 @@ class TestUndistortImage:
gradcheck(undistort_image, (im, K, distCoeff))
- def test_jit(self, device, dtype):
+ @pytest.mark.xfail(reason='Some times this seems to random fail')
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ # TODO: check if `undistort_image` fully support dynamo
im = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
K = torch.rand(3, 3, device=device, dtype=dtype)
distCoeff = torch.rand(4, device=device, dtype=dtype)
inputs = (im, K, distCoeff)
op = undistort_image
- op_jit = torch.jit.script(op)
- assert_close(op(*inputs), op_jit(*inputs))
+ op_optimized = torch_optimizer(op)
+ assert_close(op(*inputs), op_optimized(*inputs))
diff --git a/test/geometry/test_bbox.py b/test/geometry/test_bbox.py
index a55f0d3bd..29a9e6c28 100644
--- a/test/geometry/test_bbox.py
+++ b/test/geometry/test_bbox.py
@@ -48,15 +48,15 @@ class TestBbox2D:
boxes = tensor_to_gradcheck_var(boxes)
gradcheck(infer_bbox_shape, (boxes,))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
op = infer_bbox_shape
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
# Define input
boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
# Run
expected = op(boxes)
- actual = op_script(boxes)
+ actual = op_optimized(boxes)
# Compare
assert_close(actual, expected)
@@ -163,13 +163,13 @@ class TestTransformBoxes2D:
gradcheck(transform_bbox, (trans_mat, boxes, "xyxy", True))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075]], device=device, dtype=dtype)
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
args = (boxes, trans_mat)
op = kornia.geometry.transform_points
- op_jit = torch.jit.script(op)
- assert_close(op(*args), op_jit(*args))
+ op_optimized = torch_optimizer(op)
+ assert_close(op(*args), op_optimized(*args))
class TestBbox3D:
@@ -237,10 +237,10 @@ class TestBbox3D:
boxes = tensor_to_gradcheck_var(boxes)
gradcheck(infer_bbox_shape3d, (boxes,))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
op = infer_bbox_shape3d
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
boxes = torch.tensor(
[[[0, 0, 1], [3, 0, 1], [3, 2, 1], [0, 2, 1], [0, 0, 3], [3, 0, 3], [3, 2, 3], [0, 2, 3]]],
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index f7a9c5d87..a01cdebac 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -1749,12 +1749,12 @@ class TestEulerFromQuaternion(BaseTester):
def test_module(self, device, dtype):
pass
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
q = Quaternion.random(batch_size=1)
q = q.to(device, dtype)
op = euler_from_quaternion
- op_jit = torch.jit.script(op)
- assert_close(op(q.w, q.x, q.y, q.z), op_jit(q.w, q.x, q.y, q.z))
+ op_optimized = torch_optimizer(op)
+ assert_close(op(q.w, q.x, q.y, q.z), op_optimized(q.w, q.x, q.y, q.z))
def test_forth_and_back(self, device, dtype):
q = Quaternion.random(batch_size=2)
diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.py
index 7ae43e0ea..7c684bb3d 100644
--- a/test/geometry/test_linalg.py
+++ b/test/geometry/test_linalg.py
@@ -116,11 +116,11 @@ class TestTransformPoints:
kornia.geometry.transform_points, (dst_homo_src, points_src), raise_exception=True, fast_mode=True
)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
points = torch.ones(1, 2, 2, device=device, dtype=dtype)
transform = kornia.eye_like(3, points)
op = kornia.geometry.transform_points
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
actual = op_script(transform, points)
expected = op(transform, points)
assert_close(actual, expected, atol=1e-4, rtol=1e-4)
@@ -419,12 +419,12 @@ class TestEuclideanDistance(BaseTester):
pt2 = torch.rand(2, 3, device=device, dtype=torch.float64, requires_grad=True)
assert gradcheck(kgl.euclidean_distance, (pt1, pt2), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
pt1 = torch.rand(2, 3, device=device, dtype=dtype)
pt2 = torch.rand(2, 3, device=device, dtype=dtype)
op = kgl.euclidean_distance
- op_jit = torch.jit.script(op)
- self.assert_close(op(pt1, pt2), op_jit(pt1, pt2))
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(pt1, pt2), op_optimized(pt1, pt2))
def test_module(self, device, dtype):
pass
diff --git a/test/geometry/transform/test_crop2d.py b/test/geometry/transform/test_crop2d.py
index e62aa99b6..caf97b51d 100644
--- a/test/geometry/transform/test_crop2d.py
+++ b/test/geometry/transform/test_crop2d.py
@@ -92,10 +92,10 @@ class TestCropAndResize:
kornia.geometry.transform.crop_and_resize, (img, boxes, (4, 2)), raise_exception=True, fast_mode=True
)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
op = kornia.geometry.transform.crop_and_resize
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
# Define input
img = torch.tensor(
[[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
@@ -105,7 +105,7 @@ class TestCropAndResize:
boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
crop_height, crop_width = 4, 2
- actual = op_script(img, boxes, (crop_height, crop_width))
+ actual = op_optimized(img, boxes, (crop_height, crop_width))
expected = op(img, boxes, (crop_height, crop_width))
assert_close(actual, expected, rtol=1e-4, atol=1e-4)
@@ -164,10 +164,10 @@ class TestCenterCrop:
assert gradcheck(kornia.geometry.transform.center_crop, (img, (4, 2)), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
op = kornia.geometry.transform.center_crop
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
# Define input
img = torch.ones(1, 2, 5, 4, device=device, dtype=dtype)
@@ -175,19 +175,6 @@ class TestCenterCrop:
expected = op(img, (4, 2))
assert_close(actual, expected, rtol=1e-4, atol=1e-4)
- def test_jit_trace(self, device, dtype):
- # Define script
- op = kornia.geometry.transform.center_crop
- op_script = torch.jit.script(op)
- # Define input
- img = torch.ones(2, 1, 6, 3, device=device, dtype=dtype)
- op_trace = torch.jit.trace(op_script, (img, (torch.tensor(2), torch.tensor(3))))
- img = torch.ones(2, 1, 6, 3, device=device, dtype=dtype)
- # Run
- actual = op_trace(img, (torch.tensor(2), torch.tensor(3)))
- expected = op(img, (2, 3))
- assert_close(actual, expected, rtol=1e-4, atol=1e-4)
-
class TestCropByBoxes:
def test_crop_by_boxes_no_resizing(self, device, dtype):
diff --git a/test/geometry/transform/test_crop3d.py b/test/geometry/transform/test_crop3d.py
index 7b1735f81..eb764c202 100644
--- a/test/geometry/transform/test_crop3d.py
+++ b/test/geometry/transform/test_crop3d.py
@@ -73,10 +73,10 @@ class TestCropAndResize3D:
kornia.geometry.transform.crop_and_resize3d, (img, boxes, (4, 3, 2)), raise_exception=True, fast_mode=True
)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
op = kornia.geometry.transform.crop_and_resize3d
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
img = torch.arange(0.0, 64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
@@ -131,10 +131,10 @@ class TestCenterCrop3D:
kornia.geometry.transform.center_crop3d, (img, (3, 5, 7)), raise_exception=True, fast_mode=True
)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
op = kornia.geometry.transform.center_crop3d
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
img = torch.ones(4, 3, 5, 6, 7, device=device, dtype=dtype)
actual = op_script(img, (4, 3, 2))
@@ -227,10 +227,10 @@ class TestCropByBoxes3D:
patches = kornia.geometry.transform.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)
assert_close(patches, expected, rtol=1e-4, atol=1e-4)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
# Define script
op = kornia.geometry.transform.crop_by_boxes3d
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
# Define input
inp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)
src_box = torch.tensor(
diff --git a/test/geometry/transform/test_homography_warper.py b/test/geometry/transform/test_homography_warper.py
index 2092529a7..c1b1990e0 100644
--- a/test/geometry/transform/test_homography_warper.py
+++ b/test/geometry/transform/test_homography_warper.py
@@ -256,7 +256,7 @@ class TestHomographyWarper:
@pytest.mark.parametrize("batch_size", [1, 2, 3])
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("normalized_coordinates", [True, False])
- def test_jit_warp_homography(self, batch_size, align_corners, normalized_coordinates, device, dtype):
+ def test_dynamo(self, batch_size, align_corners, normalized_coordinates, device, dtype, torch_optimizer):
# generate input data
height, width = 128, 64
eye_size = 3 # identity 3x3
@@ -280,7 +280,7 @@ class TestHomographyWarper:
align_corners=align_corners,
normalized_coordinates=normalized_coordinates,
)
- patch_dst_jit = torch.jit.script(kornia.geometry.transform.homography_warp)(
+ patch_dst_optimized = torch_optimizer(kornia.geometry.transform.homography_warp)(
patch_src,
dst_homo_src_i,
(height, width),
@@ -288,7 +288,7 @@ class TestHomographyWarper:
normalized_coordinates=normalized_coordinates,
)
- assert_close(patch_dst, patch_dst_jit, atol=1e-4, rtol=1e-4)
+ assert_close(patch_dst, patch_dst_optimized, atol=1e-4, rtol=1e-4)
class TestHomographyNormalTransform:
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 6fd98be7d..5ca1e95d2 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -72,14 +72,14 @@ class TestGetPerspectiveTransform:
assert_close(kornia.geometry.transform_points(dst_trans_src, point_left), point_right)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
points_src = torch.rand(1, 4, 2, device=device, dtype=dtype)
points_dst = torch.rand(1, 4, 2, device=device, dtype=dtype)
op = kornia.geometry.get_perspective_transform
- op_jit = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(points_src, points_dst), op_jit(points_src, points_dst))
+ assert_close(op(points_src, points_dst), op_optimized(points_src, points_dst))
@pytest.mark.skipif(torch_version_lt(1, 11, 0), reason="backward for LSTSQ not supported in pytorch < 1.11.0")
def test_gradcheck(self, device):
@@ -216,13 +216,13 @@ class TestWarpAffine:
img_b_hat = kornia.geometry.warp_affine(img_a, aff_ba_2x3, (h, w))
assert_close(img_b_hat, img_b, atol=1e-3, rtol=1e-3)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
args = (img, aff_ab, (4, 5))
op = kornia.geometry.warp_affine
- op_jit = torch.jit.script(op)
- assert_close(op(*args), op_jit(*args))
+ op_optimized = torch_optimizer(op)
+ assert_close(op(*args), op_optimized(*args))
def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
@@ -415,13 +415,13 @@ class TestWarpPerspective:
patch_warped = kornia.geometry.warp_perspective(patch, dst_trans_src, (dst_h, dst_w))
assert_close(patch_warped, expected)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
H_ab = kornia.eye_like(3, img)
args = (img, H_ab, (4, 5))
op = kornia.geometry.warp_perspective
- op_jit = torch.jit.script(op)
- assert_close(op(*args), op_jit(*args))
+ op_optimized = torch_optimizer(op)
+ assert_close(op(*args), op_optimized(*args))
def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
@@ -559,7 +559,9 @@ class TestRemap:
fast_mode=True,
)
- def test_jit(self, device, dtype):
+ @pytest.mark.skip(reason='Not fully support dynamo')
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ # TODO: add dynamo support to create_meshgrid
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
@@ -567,7 +569,7 @@ class TestRemap:
grid += 1.0 # apply some shift
op = kornia.geometry.remap
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
inputs = (img, grid[..., 0], grid[..., 1], 'bilinear', 'zeros', True)
actual = op_script(*inputs)
@@ -604,9 +606,9 @@ class TestInvertAffineTransform:
matrix = utils.tensor_to_gradcheck_var(matrix) # to var
assert gradcheck(kornia.geometry.invert_affine_transform, (matrix,), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
op = kornia.geometry.invert_affine_transform
- op_script = torch.jit.script(op)
+ op_script = torch_optimizer(op)
matrix = torch.eye(2, 3, device=device, dtype=dtype)[None]
actual = op_script(matrix)
diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.py
index 4eacfa97e..83712b256 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -202,12 +202,11 @@ class TestUpscaleDouble(BaseTester):
assert tuple(actual.shape) == expected
- @pytest.mark.jit
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
img = self.prepare_data((1, 2, 5, 5), device, dtype)
op = kornia.geometry.transform.upscale_double
- op_jit = torch.jit.script(op)
- self.assert_close(op(img), op_jit(img))
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img), op_optimized(img))
@pytest.mark.grad
def test_gradcheck(self, device):
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index b89d36db6..458924ba2 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -64,13 +64,13 @@ class TestBinaryFocalLossWithLogits:
== ()
)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
op = kornia.losses.binary_focal_loss_with_logits
- op_script = torch.jit.script(op)
- actual = op_script(logits, labels, alpha=0.5, gamma=2.0, reduction="none")
+ op_optimized = torch_optimizer(op)
+ actual = op_optimized(logits, labels, alpha=0.5, gamma=2.0, reduction="none")
expected = op(logits, labels, alpha=0.5, gamma=2.0, reduction="none")
assert_close(actual, expected)
@@ -150,7 +150,7 @@ class TestFocalLoss:
logits = tensor_to_gradcheck_var(logits) # to var
assert gradcheck(kornia.losses.focal_loss, (logits, labels, alpha, gamma), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 3
params = (0.5, 2.0)
logits = torch.rand(2, num_classes, device=device, dtype=dtype)
@@ -158,9 +158,9 @@ class TestFocalLoss:
labels = labels.to(device).long()
op = kornia.losses.focal_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- actual = op_script(logits, labels, *params)
+ actual = op_optimized(logits, labels, *params)
expected = op(logits, labels, *params)
assert_close(actual, expected)
@@ -213,7 +213,7 @@ class TestTverskyLoss:
kornia.losses.tversky_loss, (logits, labels, alpha, beta), raise_exception=True, fast_mode=True
)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 3
params = (0.5, 0.05)
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -221,9 +221,9 @@ class TestTverskyLoss:
labels = labels.to(device).long()
op = kornia.losses.tversky_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- actual = op_script(logits, labels, *params)
+ actual = op_optimized(logits, labels, *params)
expected = op(logits, labels, *params)
assert_close(actual, expected)
@@ -273,16 +273,16 @@ class TestDiceLoss:
logits = tensor_to_gradcheck_var(logits) # to var
assert gradcheck(kornia.losses.dice_loss, (logits, labels), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 3
logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)
labels = torch.rand(2, 1, 2) * num_classes
labels = labels.to(device).long()
op = kornia.losses.dice_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(logits, labels), op_script(logits, labels))
+ assert_close(op(logits, labels), op_optimized(logits, labels))
def test_module(self, device, dtype):
num_classes = 3
@@ -305,14 +305,14 @@ class TestDepthSmoothnessLoss:
criterion = kornia.losses.InverseDepthSmoothnessLoss()
assert criterion(depth, image) is not None
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
depth = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
op = kornia.losses.inverse_depth_smoothness_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(image, depth), op_script(image, depth))
+ assert_close(op(image, depth), op_optimized(image, depth))
def test_module(self, device, dtype):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -425,21 +425,21 @@ class TestDivergenceLoss:
target = tensor_to_gradcheck_var(target) # to var
assert gradcheck(kornia.losses.js_div_loss_2d, (input, target), raise_exception=True, fast_mode=True)
- def test_jit_kl(self, device, dtype):
+ def test_dynamo_kl(self, device, dtype, torch_optimizer):
input = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
target = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
args = (input, target)
op = kornia.losses.kl_div_loss_2d
- op_jit = torch.jit.script(op)
- assert_close(op(*args), op_jit(*args), rtol=0, atol=1e-5)
+ op_optimized = torch_optimizer(op)
+ assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
- def test_jit_js(self, device, dtype):
+ def test_dynamo_js(self, device, dtype, torch_optimizer):
input = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
target = torch.full((1, 1, 2, 4), 0.125, dtype=dtype, device=device)
args = (input, target)
op = kornia.losses.js_div_loss_2d
- op_jit = torch.jit.script(op)
- assert_close(op(*args), op_jit(*args), rtol=0, atol=1e-5)
+ op_optimized = torch_optimizer(op)
+ assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
class TestTotalVariation:
@@ -555,13 +555,13 @@ class TestTotalVariation:
with pytest.raises(TypeError):
kornia.losses.total_variation(input)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
op = kornia.losses.total_variation
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(image), op_script(image))
+ assert_close(op(image), op_optimized(image))
def test_module(self, device, dtype):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -607,16 +607,16 @@ class TestPSNRLoss:
actual = kornia.losses.psnr_loss(input, 1.2 * input, 2.0)
assert_close(actual, expected)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
args = (input, target, 1.0)
op = kornia.losses.psnr_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(*args), op_script(*args))
+ assert_close(op(*args), op_optimized(*args))
def test_module(self, device, dtype):
input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
@@ -675,16 +675,16 @@ class TestLovaszHingeLoss:
logits = tensor_to_gradcheck_var(logits) # to var
assert gradcheck(kornia.losses.lovasz_hinge_loss, (logits, labels), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 1
logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)
labels = torch.rand(2, 1, 2) * num_classes
labels = labels.to(device).long()
op = kornia.losses.lovasz_hinge_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(logits, labels), op_script(logits, labels))
+ assert_close(op(logits, labels), op_optimized(logits, labels))
def test_module(self, device, dtype):
num_classes = 1
@@ -740,16 +740,16 @@ class TestLovaszSoftmaxLoss:
logits = tensor_to_gradcheck_var(logits) # to var
assert gradcheck(kornia.losses.lovasz_softmax_loss, (logits, labels), raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 6
logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)
labels = torch.rand(2, 1, 2) * num_classes
labels = labels.to(device).long()
op = kornia.losses.lovasz_softmax_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- assert_close(op(logits, labels), op_script(logits, labels))
+ assert_close(op(logits, labels), op_optimized(logits, labels))
def test_module(self, device, dtype):
num_classes = 5
@@ -789,14 +789,14 @@ class TestWelschLoss(BaseTester):
img1 = tensor_to_gradcheck_var(img1) # to var
assert self.gradcheck(kornia.losses.welsch_loss, (img1, img2))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
img2 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
op = kornia.losses.welsch_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- self.assert_close(op(img1, img2), op_script(img1, img2))
+ self.assert_close(op(img1, img2), op_optimized(img1, img2))
def test_module(self, device, dtype):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
@@ -906,14 +906,14 @@ class TestCauchyLoss(BaseTester):
img2 = tensor_to_gradcheck_var(img2) # to var
self.gradcheck(kornia.losses.cauchy_loss, (img1, img2))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
img2 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
op = kornia.losses.cauchy_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- self.assert_close(op(img1, img2), op_script(img1, img2))
+ self.assert_close(op(img1, img2), op_optimized(img1, img2))
def test_module(self, device, dtype):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
@@ -1000,14 +1000,14 @@ class TestGemanMcclureLossLoss(BaseTester):
img2 = tensor_to_gradcheck_var(img2) # to var
self.gradcheck(kornia.losses.geman_mcclure_loss, (img1, img2))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
img2 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
op = kornia.losses.geman_mcclure_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- self.assert_close(op(img1, img2), op_script(img1, img2))
+ self.assert_close(op(img1, img2), op_optimized(img1, img2))
def test_module(self, device, dtype):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
@@ -1094,14 +1094,14 @@ class TestCharbonnierLoss(BaseTester):
img2 = tensor_to_gradcheck_var(img2) # to var
self.gradcheck(kornia.losses.charbonnier_loss, (img1, img2))
- def test_jit(self, device, dtype):
+ def test_dynamo(self, device, dtype, torch_optimizer):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
img2 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)
op = kornia.losses.charbonnier_loss
- op_script = torch.jit.script(op)
+ op_optimized = torch_optimizer(op)
- self.assert_close(op(img1, img2), op_script(img1, img2))
+ self.assert_close(op(img1, img2), op_optimized(img1, img2))
def test_module(self, device, dtype):
img1 = torch.rand(2, 3, 3, 3, device=device, dtype=dtype)