π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
deprecate utils module across library (#3449)
Edgar Riba94882c52ae4e
diff --git a/conftest.py b/conftest.pyindex 04a464bfe..37bc855db 100644--- a/conftest.py+++ b/conftest.py@@ -49,7 +49,7 @@ def get_test_devices() -> dict[str, torch.device]:if torch.cuda.is_available():devices["cuda"] = torch.device("cuda:0")- if kornia.xla_is_available():+ if kornia.core.utils.xla_is_available():import torch_xla.core.xla_model as xmdevices["tpu"] = xm.xla_device()diff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex 89e9f3e71..1ef549076 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -57,7 +57,7 @@ def read_img_from_url(url: str, resize_to: Optional[tuple[int, int]] = None, **r# convert to image array and resizeimg: np.ndarray = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)[..., :3]# convert the image to a tensor- img_t: torch.Tensor = K.utils.image_to_tensor(img, keepdim=False) # 1xCxHXW+ img_t: torch.Tensor = K.image.image_to_tensor(img, keepdim=False) # 1xCxHXWimg_t = img_t.float() / 255.0if resize_to is None:img_t = K.geometry.resize(img_t, 184, **resize_kwargs)@@ -80,7 +80,7 @@ def draw_bbox_kpts(imgs: torch.Tensor, bboxes: torch.Tensor, keypoints: torch.Terectangle[..., 2] = bboxes[..., 0] + bboxes[..., -2] # x2rectangle[..., 3] = bboxes[..., 1] + bboxes[..., -1] # y2color = torch.tensor([1, 0, 0]).repeat(imgs.shape[0], imgs.shape[1], 1)- imgs_draw = K.utils.draw_rectangle(imgs, rectangle, color=color)+ imgs_draw = K.image.draw_rectangle(imgs, rectangle, color=color)rectangle2 = torch.zeros(imgs.shape[0], imgs.shape[1], 4)for n in range(keypoints.shape[-2]):@@ -219,7 +219,7 @@ def main():out = torch.cat([ori, *(out[i] for i in range(out.size(0)))], dim=-1)# save the output image- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"print(f"Generated image example for {aug_name}. {sig}")@@ -373,7 +373,7 @@ def main():)else:out = torch.cat([img2[0], *(out[i] for i in range(out.size(0)))], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -389,7 +389,7 @@ def main():out = torch.cat([bar_img, out], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{colormap_name}.png"), out_np)sig = f"{colormap_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {colormap_name}. {sig}")@@ -454,7 +454,7 @@ def main():out = fn(*args_in)# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -481,7 +481,7 @@ def main():out = fn(*args_in)# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -532,7 +532,7 @@ def main():out = torch.cat([args_in[1], out], dim=-1)# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -555,7 +555,7 @@ def main():mask = mask.repeat(1, img1.shape[1], 1, 1)# save the output imageout = torch.cat([img1[0], mask[0], filtered[0]], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -585,7 +585,7 @@ def main():),"remap": ((- *(K.utils.create_meshgrid(h, w, normalized_coordinates=True) - 0.25).unbind(-1),+ *(K.geometry.create_meshgrid(h, w, normalized_coordinates=True) - 0.25).unbind(-1),"bilinear","zeros",True,@@ -642,7 +642,7 @@ def main():out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)else:out = torch.cat([*(out[i] for i in range(out.size(0)))], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")@@ -713,7 +713,7 @@ def main():# save the output imageout = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.image.tensor_to_image((out * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for response function {fn_name}")diff --git a/docs/source/geometry.grid.rst b/docs/source/geometry.grid.rstnew file mode 100644index 000000000..086427b7d--- /dev/null+++ b/docs/source/geometry.grid.rst@@ -0,0 +1,11 @@+kornia.geometry.grid+====================++.. meta::+ :name: description+ :content: "The kornia.geometry.grid module provides functions for generating coordinate grids for images. It includes functions for creating 2D and 3D mesh grids with optional coordinate normalization, making it easy to work with grid-based transformations and sampling operations in computer vision tasks."++.. currentmodule:: kornia.geometry.grid++.. autofunction:: create_meshgrid+.. autofunction:: create_meshgrid3ddiff --git a/docs/source/geometry.pointcloud.rst b/docs/source/geometry.pointcloud.rstnew file mode 100644index 000000000..7d31a1ba4--- /dev/null+++ b/docs/source/geometry.pointcloud.rst@@ -0,0 +1,11 @@+kornia.geometry.pointcloud+==========================++.. meta::+ :name: description+ :content: "The kornia.geometry.pointcloud module provides functionality for loading and saving point clouds in PLY format. It includes functions for reading and writing 3D point cloud data, making it easy to work with point cloud files in computer vision and geometric processing tasks."++.. currentmodule:: kornia.geometry.pointcloud++.. autofunction:: save_pointcloud_ply+.. autofunction:: load_pointcloud_plydiff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex fc4c9832e..404cea7f5 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -56,10 +56,12 @@ transforms, camera, conversions, linalg and depth. We next describe each of themgeometry.conversionsgeometry.depthgeometry.epipolar+ geometry.gridgeometry.homographygeometry.liegroupgeometry.linalggeometry.line+ geometry.pointcloudgeometry.quaterniongeometry.solversgeometry.subpixdiff --git a/docs/source/get-started/highlights.rst b/docs/source/get-started/highlights.rstindex 76abc4a71..0dec0981d 100644--- a/docs/source/get-started/highlights.rst+++ b/docs/source/get-started/highlights.rst@@ -41,5 +41,4 @@ At a granular level, Kornia is a library that consists of the following componen+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------+| `kornia.morphology <https://kornia.readthedocs.io/en/latest/morphology.html>`_ | a module to perform morphological operations |+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------+-| `kornia.utils <https://kornia.readthedocs.io/en/latest/utils.html>`_ | image to tensor utilities and metrics for vision problems |+-----------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------+diff --git a/docs/source/image.rst b/docs/source/image.rstindex e824957c3..186de2bf5 100644--- a/docs/source/image.rst+++ b/docs/source/image.rst@@ -28,3 +28,32 @@ Module to provide a high level API to process images... autoclass:: Image:members::undoc-members:++Drawing+-------++.. autofunction:: draw_line+.. autofunction:: draw_rectangle+.. autofunction:: draw_convex_polygon+.. autofunction:: draw_point2d++Image Conversion+----------------++.. autofunction:: tensor_to_image+.. autofunction:: image_to_tensor+.. autofunction:: image_list_to_tensor+.. autoclass:: ImageToTensor++Image Printing+--------------++.. autofunction:: image_to_string+.. autofunction:: print_image++Utilities+---------++.. autofunction:: make_grid+.. autofunction:: perform_keep_shape_image+.. autofunction:: perform_keep_shape_videodiff --git a/docs/source/index.rst b/docs/source/index.rstindex e705e382f..81c031e33 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -121,7 +121,6 @@ Join the communitymorphologyonnxtracking- utils.. toctree:::caption: KORNIA APPLICATIONSdiff --git a/docs/source/losses.rst b/docs/source/losses.rstindex f874ebd55..dce565326 100644--- a/docs/source/losses.rst+++ b/docs/source/losses.rst@@ -34,6 +34,7 @@ ReconstructionSemantic Segmentation---------------------+.. autofunction:: one_hot.. autofunction:: binary_focal_loss_with_logits.. autofunction:: focal_loss.. autofunction:: dice_lossdiff --git a/docs/source/models/segment_anything.rst b/docs/source/models/segment_anything.rstindex c6bd35365..9624a5696 100644--- a/docs/source/models/segment_anything.rst+++ b/docs/source/models/segment_anything.rst@@ -96,7 +96,7 @@ to query the image masks from the SAM model.from kornia.io import load_image, ImageLoadTypefrom kornia.geometry.keypoints import Keypointsfrom kornia.geometry.boxes import Boxes- from kornia.utils import get_cuda_or_mps_device_if_available+ from kornia.core.utils import get_cuda_or_mps_device_if_availablemodel_type = 'vit_h'checkpoint = './https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth'@@ -180,7 +180,7 @@ parameters. If a checkpoint URL or path for a file is seted, the method will aut.. code-block:: pythonfrom kornia.models.sam import Sam, SamConfig- from kornia.utils import get_cuda_or_mps_device_if_available+ from kornia.core.utils import get_cuda_or_mps_device_if_available# model_type can be:# 0, 'vit_h' or `kornia.models.sam.SamModelType.vit_h`@@ -216,7 +216,7 @@ If a URL is passed the model will automatically download and cache the weights u.. code-block:: pythonfrom kornia.models.sam import Sam, SamConfig- from kornia.utils import get_cuda_or_mps_device_if_available+ from kornia.core.utils import get_cuda_or_mps_device_if_availablemodel_type = 'vit_b'@@ -245,7 +245,7 @@ This is a simple example, of how to directly use the SAM model loaded. We recommfrom kornia.models.sam import Samfrom kornia.models.structures import SegmentationResultsfrom kornia.io import load_image, ImageLoadType- from kornia.utils import get_cuda_or_mps_device_if_available+ from kornia.core.utils import get_cuda_or_mps_device_if_availablefrom kornia.geometry import resizefrom kornia.enhance import normalizediff --git a/docs/source/utils.rst b/docs/source/utils.rstdeleted file mode 100644index 939fb6683..000000000--- a/docs/source/utils.rst+++ /dev/null@@ -1,55 +0,0 @@-kornia.utils-===================--.. meta::- :name: description- :content: "The `kornia.utils` module provides a variety of utility functions for computer vision tasks, including image manipulation, pointcloud handling, device management, memory operations, and automatic mixed precision support. These utilities streamline workflows for tasks like image transformation, grid generation, and point cloud file handling."--.. currentmodule:: kornia.utils--Draw-------.. autofunction:: draw_line-.. autofunction:: draw_rectangle-.. autofunction:: draw_convex_polygon--Image--------.. autofunction:: tensor_to_image-.. autofunction:: image_to_tensor-.. autofunction:: image_list_to_tensor-.. autofunction:: image_to_string-.. autofunction:: print_image--Grid-------.. autofunction:: create_meshgrid-.. autofunction:: create_meshgrid3d--Pointcloud-------------.. autofunction:: save_pointcloud_ply-.. autofunction:: load_pointcloud_ply--Memory----------.. autofunction:: one_hot-.. autofunction:: batched_forward--Device----------.. autofunction:: get_cuda_device_if_available-.. autofunction:: get_mps_device_if_available-.. autofunction:: get_cuda_or_mps_device_if_available-.. autofunction:: map_location_to_cpu---Automatic Mixed Precision---------------------------.. autofunction:: is_autocast_enableddiff --git a/kornia/__init__.py b/kornia/__init__.pyindex da5c6974c..258d41606 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -21,6 +21,8 @@ This package exposes core modules (filters, geometry, etc.) and providesconvenience imports at the top level."""+from typing import Any+# NOTE: kornia filters and geometry must go first since are the core of the library# and by changing the import order you might get into a circular dependencies issue.from . import filters@@ -42,7 +44,6 @@ from . import (morphology,onnx,tracking,- utils,)@@ -51,14 +52,197 @@ from .transpiler import to_jax, to_numpy, to_tensorflow# NOTE: we are going to expose to top level very few thingsfrom kornia.constants import pi-from kornia.utils import (- eye_like,- vec_like,- create_meshgrid,- image_to_tensor,- tensor_to_image,- xla_is_available,++# Deprecated top-level imports - use kornia.core.ops or kornia.core.utils instead+from kornia.core._compat import deprecated++# Import the actual functions to wrap+from kornia.core.ops import eye_like as _eye_like, vec_like as _vec_like+from kornia.core.utils import (+ get_cuda_device_if_available as _get_cuda_device_if_available,+ get_cuda_or_mps_device_if_available as _get_cuda_or_mps_device_if_available,+ get_mps_device_if_available as _get_mps_device_if_available,+ is_autocast_enabled as _is_autocast_enabled,+ xla_is_available as _xla_is_available,+)+from kornia.geometry import (+ create_meshgrid as _create_meshgrid,+ create_meshgrid3d as _create_meshgrid3d,+ load_pointcloud_ply as _load_pointcloud_ply,+ save_pointcloud_ply as _save_pointcloud_ply,+)+from kornia.image import (+ draw_convex_polygon as _draw_convex_polygon,+ draw_line as _draw_line,+ draw_point2d as _draw_point2d,+ draw_rectangle as _draw_rectangle,+ image_to_string as _image_to_string,+ image_to_tensor as _image_to_tensor,+ print_image as _print_image,+ tensor_to_image as _tensor_to_image,+)+from kornia.losses import one_hot as _one_hot+++@deprecated(replace_with="kornia.core.ops.eye_like", version="0.8.3")+def eye_like(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.ops.eye_like` instead."""+ return _eye_like(*args, **kwargs)+++@deprecated(replace_with="kornia.core.ops.vec_like", version="0.8.3")+def vec_like(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.ops.vec_like` instead."""+ return _vec_like(*args, **kwargs)+++@deprecated(replace_with="kornia.core.utils.xla_is_available", version="0.8.3")+def xla_is_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.xla_is_available` instead."""+ return _xla_is_available(*args, **kwargs)+++@deprecated(replace_with="kornia.geometry.create_meshgrid", version="0.8.3")+def create_meshgrid(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""+ return _create_meshgrid(*args, **kwargs)+++@deprecated(replace_with="kornia.image.image_to_tensor", version="0.8.3")+def image_to_tensor(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.image_to_tensor` instead."""+ return _image_to_tensor(*args, **kwargs)+++@deprecated(replace_with="kornia.image.tensor_to_image", version="0.8.3")+def tensor_to_image(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.tensor_to_image` instead."""+ return _tensor_to_image(*args, **kwargs)+++@deprecated(replace_with="kornia.core.utils.get_cuda_device_if_available", version="0.8.3")+def get_cuda_device_if_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.get_cuda_device_if_available` instead."""+ return _get_cuda_device_if_available(*args, **kwargs)+++@deprecated(replace_with="kornia.core.utils.get_mps_device_if_available", version="0.8.3")+def get_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.get_mps_device_if_available` instead."""+ return _get_mps_device_if_available(*args, **kwargs)+++@deprecated(replace_with="kornia.core.utils.get_cuda_or_mps_device_if_available", version="0.8.3")+def get_cuda_or_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.get_cuda_or_mps_device_if_available` instead."""+ return _get_cuda_or_mps_device_if_available(*args, **kwargs)+++@deprecated(replace_with="kornia.core.utils.is_autocast_enabled", version="0.8.3")+def is_autocast_enabled(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.is_autocast_enabled` instead."""+ return _is_autocast_enabled(*args, **kwargs)+++@deprecated(+ replace_with="kornia.geometry.create_meshgrid3d",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.create_meshgrid3d`.",)+def create_meshgrid3d(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.create_meshgrid3d` instead (previously `kornia.utils.create_meshgrid3d`)."""+ return _create_meshgrid3d(*args, **kwargs)+++@deprecated(+ replace_with="kornia.geometry.load_pointcloud_ply",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.load_pointcloud_ply`.",+)+def load_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.load_pointcloud_ply` instead (previously `kornia.utils.load_pointcloud_ply`)."""+ return _load_pointcloud_ply(*args, **kwargs)+++@deprecated(+ replace_with="kornia.geometry.save_pointcloud_ply",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.save_pointcloud_ply`.",+)+def save_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.save_pointcloud_ply` instead (previously `kornia.utils.save_pointcloud_ply`)."""+ return _save_pointcloud_ply(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_line",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.draw_line`.",+)+def draw_line(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_line` instead (previously `kornia.utils.draw_line`)."""+ return _draw_line(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_rectangle",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.draw_rectangle`.",+)+def draw_rectangle(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_rectangle` instead (previously `kornia.utils.draw_rectangle`)."""+ return _draw_rectangle(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_point2d",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.draw_point2d`.",+)+def draw_point2d(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_point2d` instead (previously `kornia.utils.draw_point2d`)."""+ return _draw_point2d(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_convex_polygon",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.draw_convex_polygon`.",+)+def draw_convex_polygon(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_convex_polygon` instead (previously `kornia.utils.draw_convex_polygon`)."""+ return _draw_convex_polygon(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.image_to_string",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.image_to_string`.",+)+def image_to_string(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.image_to_string` instead (previously `kornia.utils.image_to_string`)."""+ return _image_to_string(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.print_image",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.print_image`.",+)+def print_image(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.print_image` instead (previously `kornia.utils.print_image`)."""+ return _print_image(*args, **kwargs)+++@deprecated(+ replace_with="kornia.losses.one_hot",+ version="0.8.3",+ extra_reason=" Previously available as `kornia.utils.one_hot`.",+)+def one_hot(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.losses.one_hot` instead (previously `kornia.utils.one_hot`)."""+ return _one_hot(*args, **kwargs)+# Version variable__version__ = "0.8.2"diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex b9e1a5ca9..05f171eae 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -22,9 +22,10 @@ from torch import float16, float32, float64from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype+from kornia.core.ops import eye_like+from kornia.core.utils import is_autocast_enabledfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints-from kornia.utils import eye_like, is_autocast_enabledclass AugmentationBase2D(_AugmentationBase):diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.pyindex d8abcb2a6..dddc3a663 100644--- a/kornia/augmentation/_2d/geometric/base.py+++ b/kornia/augmentation/_2d/geometric/base.py@@ -21,9 +21,9 @@ import torchfrom kornia.augmentation._2d.base import RigidAffineAugmentationBase2Dfrom kornia.constants import Resample+from kornia.core.utils import _torch_inverse_castfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints-from kornia.utils.helpers import _torch_inverse_castclass GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.pyindex 31ab715a5..e57a14da6 100644--- a/kornia/augmentation/_2d/geometric/fisheye.py+++ b/kornia/augmentation/_2d/geometric/fisheye.py@@ -21,8 +21,8 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.base import AugmentationBase2D+from kornia.geometry.grid import create_meshgridfrom kornia.geometry.transform import remap-from kornia.utils import create_meshgridclass RandomFisheye(AugmentationBase2D):diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.pyindex e2035be01..6634a868e 100644--- a/kornia/augmentation/_2d/geometric/resize.py+++ b/kornia/augmentation/_2d/geometric/resize.py@@ -22,8 +22,8 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.constants import Resample+from kornia.core.ops import eye_likefrom kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize-from kornia.utils import eye_likeclass Resize(GeometricAugmentationBase2D):diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.pyindex a5d778783..05cf68d50 100644--- a/kornia/augmentation/_2d/geometric/rotation.py+++ b/kornia/augmentation/_2d/geometric/rotation.py@@ -22,9 +22,9 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.constants import Resample+from kornia.core.ops import eye_likefrom kornia.geometry.transform import affinefrom kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center-from kornia.utils.misc import eye_likeclass RandomRotation(GeometricAugmentationBase2D):diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.pyindex 270941679..a02ffa881 100644--- a/kornia/augmentation/_2d/mix/mosaic.py+++ b/kornia/augmentation/_2d/mix/mosaic.py@@ -24,9 +24,9 @@ from kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.mix.base import MixAugmentationBaseV2from kornia.constants import DataKey, Resamplefrom kornia.core.check import KORNIA_UNWRAP+from kornia.core.ops import eye_likefrom kornia.geometry.boxes import Boxesfrom kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform-from kornia.utils import eye_like__all__ = ["RandomMosaic"]diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.pyindex f3b311be2..6e820c22f 100644--- a/kornia/augmentation/_3d/base.py+++ b/kornia/augmentation/_3d/base.py@@ -57,7 +57,7 @@ class AugmentationBase3D(_AugmentationBase):def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:"""Return 4x4 identity matrix."""- return kornia.eye_like(4, input)+ return kornia.core.ops.eye_like(4, input)class RigidAffineAugmentationBase3D(AugmentationBase3D):diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.pyindex 0e8617453..aebd473a7 100644--- a/kornia/augmentation/_3d/geometric/rotation.py+++ b/kornia/augmentation/_3d/geometric/rotation.py@@ -118,7 +118,7 @@ class RandomRotation3D(GeometricAugmentationBase3D):rotation_mat: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))# rotation_mat is B x 3 x 4 and we need a B x 4 x 4 matrix- trans_mat: torch.Tensor = kornia.eye_like(4, input)+ trans_mat: torch.Tensor = kornia.core.ops.eye_like(4, input)trans_mat[:, 0] = rotation_mat[:, 0]trans_mat[:, 1] = rotation_mat[:, 1]trans_mat[:, 2] = rotation_mat[:, 2]diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.pyindex 520bf9847..2ad330786 100644--- a/kornia/augmentation/auto/base.py+++ b/kornia/augmentation/auto/base.py@@ -25,7 +25,7 @@ from kornia.augmentation.auto.operations.policy import PolicySequentialfrom kornia.augmentation.container.base import ImageSequentialBase, TransformMatrixMinInfrom kornia.augmentation.container.ops import InputSequentialOpsfrom kornia.augmentation.container.params import ParamItem-from kornia.utils import eye_like+from kornia.core.ops import eye_likeNUMBER = Union[float, int]OP_CONFIG = Tuple[str, NUMBER, Optional[NUMBER]]diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.pyindex efacc5b9b..23884d8ee 100644--- a/kornia/augmentation/auto/operations/policy.py+++ b/kornia/augmentation/auto/operations/policy.py@@ -26,7 +26,7 @@ from kornia.augmentation.container.base import ImageSequentialBase, TransformMatfrom kornia.augmentation.container.ops import InputSequentialOpsfrom kornia.augmentation.container.params import ParamItemfrom kornia.augmentation.utils import _transform_input, override_parameters-from kornia.utils import eye_like+from kornia.core.ops import eye_likeclass PolicySequential(TransformMatrixMinIn, ImageSequentialBase):diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex bdf15e6db..00b0e2af7 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -29,9 +29,9 @@ from kornia.augmentation.utils import (_transform_output_shape,override_parameters,)+from kornia.core.utils import is_autocast_enabledfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints-from kornia.utils import is_autocast_enabledTensorWithTransformMat = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 8366f326a..61a894715 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -16,7 +16,7 @@#import warnings-from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast+from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union, castimport torchfrom torch import nn@@ -25,9 +25,10 @@ from kornia.augmentation._2d.base import RigidAffineAugmentationBase2Dfrom kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3Dfrom kornia.augmentation.base import _AugmentationBasefrom kornia.constants import DataKey, Resample+from kornia.core.ops import eye_like+from kornia.core.utils import is_autocast_enabledfrom kornia.geometry.boxes import Boxes, VideoBoxesfrom kornia.geometry.keypoints import Keypoints, VideoKeypoints-from kornia.utils import eye_like, is_autocast_enabledfrom .base import TransformMatrixMinInfrom .image import ImageSequential@@ -336,7 +337,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):outputs = self.transform_op.inverse( # type: ignore*outputs, module=module, param=param, extra_args=self.extra_args)- if not isinstance(outputs, (list, tuple)):+ if not isinstance(outputs, list | tuple):# Make sure we are unpacking a list whilst post-procoutputs = [outputs]@@ -400,7 +401,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:_out_k = self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate)- if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Keypoints)):+ if is_autocast_enabled() and isinstance(in_arg, torch.Tensor | Keypoints):if isinstance(_out_k, list):_out_k = [i.type(in_arg.dtype) for i in _out_k]else:@@ -409,7 +410,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):elif DataKey.get(dcate) in _BOXES_OPTIONS:_out_b = self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate)- if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Boxes)):+ if is_autocast_enabled() and isinstance(in_arg, torch.Tensor | Boxes):if isinstance(_out_b, list):_out_b = [i.type(in_arg.dtype) for i in _out_b]else:@@ -448,7 +449,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# image data must exist if params is not provided.if DataKey.INPUT in self.transform_op.data_keys:inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]- if not isinstance(inp, (torch.Tensor,)):+ if not isinstance(inp, torch.Tensor):raise ValueError(f"`INPUT` should be a torch.tensor but `{type(inp)}` received.")# A video input shall be BCDHW while an image input shall be BCHWif self.contains_video_sequential or self.contains_3d_augmentation:@@ -465,7 +466,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):outputs = self.transform_op.transform( # type: ignore*outputs, module=module, param=param, extra_args=self.extra_args)- if not isinstance(outputs, (list, tuple)):+ if not isinstance(outputs, list | tuple):# Make sure we are unpacking a list whilst post-procoutputs = [outputs]self._update_transform_matrix_by_module(module)@@ -491,7 +492,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):self,*inputs: Any,input_names_to_handle: Optional[List[Any]] = None,- output_type: str = "torch.tensor",+ output_type: Literal["pt", "numpy", "pil"] = "pt",**kwargs: Any,) -> Any:"""Overwrite the __call__ function to handle various inputs.@@ -499,7 +500,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):Args:inputs: Inputs to operate on.input_names_to_handle: List of input names to convert, if None, handle all inputs.- output_type: Desired output type ('torch.tensor', 'numpy', or 'pil').+ output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.Returns:@@ -525,7 +526,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):if len(data_keys) > 1 and DataKey.INPUT in data_keys:# NOTE: we may update it later for more supports of drawing boxes, etc.idx = data_keys.index(DataKey.INPUT)- if output_type == "torch.tensor":+ if output_type == "pt":self._output_image = _output_imageif isinstance(_output_image, dict):self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]@@ -616,7 +617,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):mode = "xywh"else:raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")- if isinstance(arg, (Boxes,)):+ if isinstance(arg, Boxes):return argelif self.contains_video_sequential:arg = cast(torch.Tensor, arg)@@ -640,7 +641,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")# TODO: handle 3d scenarios- if isinstance(in_arg, (Boxes,)):+ if isinstance(in_arg, Boxes):return out_argelse:return out_arg.to_tensor(mode=mode)@@ -661,7 +662,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):return video_result.type(dtype) if dtype else video_resultelif self.contains_3d_augmentation:raise NotImplementedError("3D keypoint handlers are not yet supported.")- elif isinstance(arg, (Keypoints,)):+ elif isinstance(arg, Keypoints):return argelse:arg = cast(torch.Tensor, arg)@@ -675,7 +676,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):def _postproc_keypoint(self, in_arg: DataType, out_arg: Keypoints, dcate: DataKey) -> Union[torch.Tensor, List[torch.Tensor], Keypoints]:- if isinstance(in_arg, (Keypoints,)):+ if isinstance(in_arg, Keypoints):return out_argelse:return out_arg.to_tensor()diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 6054548b0..338319407 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -15,7 +15,7 @@# limitations under the License.#-from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast+from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union, castimport torchfrom torch import nn@@ -24,8 +24,8 @@ import kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import override_parametersfrom kornia.core import ImageModule-from kornia.core.module import ImageModuleMixIn-from kornia.utils import eye_like+from kornia.core.mixin.image_module import ImageModuleMixIn+from kornia.core.ops import eye_likefrom .base import ImageSequentialBasefrom .params import ParamItem@@ -338,7 +338,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):self,*inputs: Any,input_names_to_handle: Optional[List[Any]] = None,- output_type: str = "tensor",+ output_type: Literal["pt", "numpy", "pil"] = "pt",**kwargs: Any,) -> Any:"""Overwrite the __call__ function to handle various inputs.@@ -346,7 +346,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):Args:inputs: Inputs to operate on.input_names_to_handle: List of input names to convert, if None, handle all inputs.- output_type: Desired output type ('tensor', 'numpy', or 'pil').+ output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.Returns:@@ -359,7 +359,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):input_names_to_handle=input_names_to_handle, output_type=output_type)(super().__call__)_output_image = decorated_forward(*inputs, **kwargs)- if output_type == "tensor":+ if output_type == "pt":self._output_image = self._detach_tensor_to_cpu(_output_image)else:self._output_image = _output_imagediff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.pyindex baf5f60a3..be7220d52 100644--- a/kornia/augmentation/random_generator/_2d/affine.py+++ b/kornia/augmentation/random_generator/_2d/affine.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["AffineGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.pyindex 1b975f5e2..7733cbcae 100644--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py@@ -22,7 +22,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["ColorJiggleGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.pyindex b7e59e03f..34a28371e 100644--- a/kornia/augmentation/random_generator/_2d/crop.py+++ b/kornia/augmentation/random_generator/_2d/crop.py@@ -22,8 +22,8 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check+from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.bbox import bbox_generator-from kornia.utils.helpers import _extract_device_dtype__all__ = ["CropGenerator", "ResizedCropGenerator", "center_crop_generator"]diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.pyindex 94cd79578..336ba6352 100644--- a/kornia/augmentation/random_generator/_2d/cutmix.py+++ b/kornia/augmentation/random_generator/_2d/cutmix.py@@ -22,8 +22,8 @@ from torch.distributions import Bernoulli, Beta, Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check+from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.bbox import bbox_generator-from kornia.utils.helpers import _extract_device_dtype__all__ = ["CutmixGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/jpeg.py b/kornia/augmentation/random_generator/_2d/jpeg.pyindex 30ad9b0fb..99f7d96c3 100644--- a/kornia/augmentation/random_generator/_2d/jpeg.py+++ b/kornia/augmentation/random_generator/_2d/jpeg.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["JPEGGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/linear_illumination.py b/kornia/augmentation/random_generator/_2d/linear_illumination.pyindex d657cccca..7d6b0240d 100644--- a/kornia/augmentation/random_generator/_2d/linear_illumination.py+++ b/kornia/augmentation/random_generator/_2d/linear_illumination.py@@ -21,8 +21,8 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound+from kornia.core.utils import _extract_device_dtypefrom kornia.enhance.normalize import normalize_min_max-from kornia.utils import _extract_device_dtypeclass LinearIlluminationGenerator(RandomGeneratorBase):diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.pyindex 3fbb910f7..949c81491 100644--- a/kornia/augmentation/random_generator/_2d/mixup.py+++ b/kornia/augmentation/random_generator/_2d/mixup.py@@ -22,7 +22,7 @@ from torch.distributions import Bernoullifrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["MixupGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.pyindex b66918351..f9c75792a 100644--- a/kornia/augmentation/random_generator/_2d/mosaic.py+++ b/kornia/augmentation/random_generator/_2d/mosaic.py@@ -22,8 +22,8 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check+from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.bbox import bbox_generator-from kornia.utils.helpers import _extract_device_dtype__all__ = ["MosaicGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.pyindex 6e1fd0712..5752f5d58 100644--- a/kornia/augmentation/random_generator/_2d/motion_blur.py+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["MotionBlurGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.pyindex 0f402229d..a99dd7771 100644--- a/kornia/augmentation/random_generator/_2d/perspective.py+++ b/kornia/augmentation/random_generator/_2d/perspective.py@@ -22,7 +22,7 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["PerspectiveGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.pyindex 2240daada..780c31e8b 100644--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py@@ -22,7 +22,7 @@ from torch.distributions import Distributionfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["ParameterBound", "PlainUniformGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.pyindex 7669984f9..20768133f 100644--- a/kornia/augmentation/random_generator/_2d/posterize.py+++ b/kornia/augmentation/random_generator/_2d/posterize.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["PosterizeGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/random_rain.py b/kornia/augmentation/random_generator/_2d/random_rain.pyindex a4dedae3e..9d607766b 100644--- a/kornia/augmentation/random_generator/_2d/random_rain.py+++ b/kornia/augmentation/random_generator/_2d/random_rain.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound-from kornia.utils import _extract_device_dtype+from kornia.core.utils import _extract_device_dtypeclass RainGenerator(RandomGeneratorBase):diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.pyindex 32855fc3f..f2f89bc49 100644--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["RectangleEraseGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.pyindex 1d61b68a6..f80320984 100644--- a/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py+++ b/kornia/augmentation/random_generator/_2d/salt_pepper_noise.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _range_bound-from kornia.utils import _extract_device_dtype+from kornia.core.utils import _extract_device_dtypeclass SaltAndPepperGenerator(RandomGeneratorBase):diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.pyindex 9f5d151ae..f17c393ca 100644--- a/kornia/augmentation/random_generator/_2d/shear.py+++ b/kornia/augmentation/random_generator/_2d/shear.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["ShearGenerator"]diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.pyindex 837d575ee..fa02e319b 100644--- a/kornia/augmentation/random_generator/_2d/translate.py+++ b/kornia/augmentation/random_generator/_2d/translate.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtype__all__ = ["TranslateGenerator"]diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.pyindex 2dbff2c86..6dd02b97a 100644--- a/kornia/augmentation/random_generator/_3d/affine.py+++ b/kornia/augmentation/random_generator/_3d/affine.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _singular_range_check, _tuple_range_reader-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtypeclass AffineGenerator3D(RandomGeneratorBase):diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.pyindex 56b43413e..148b7796c 100644--- a/kornia/augmentation/random_generator/_3d/crop.py+++ b/kornia/augmentation/random_generator/_3d/crop.py@@ -22,8 +22,8 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check+from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.bbox import bbox_generator3d-from kornia.utils.helpers import _extract_device_dtypeclass CropGenerator3D(RandomGeneratorBase):diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.pyindex fc3f10063..50e8d3be9 100644--- a/kornia/augmentation/random_generator/_3d/motion_blur.py+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound, _tuple_range_reader-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtypeclass MotionBlurGenerator3D(RandomGeneratorBase):diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.pyindex 03645c396..b5e2a75a4 100644--- a/kornia/augmentation/random_generator/_3d/perspective.py+++ b/kornia/augmentation/random_generator/_3d/perspective.py@@ -22,7 +22,7 @@ from torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtypeclass PerspectiveGenerator3D(RandomGeneratorBase):diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.pyindex e9152b8c6..fba2d0037 100644--- a/kornia/augmentation/random_generator/_3d/rotation.py+++ b/kornia/augmentation/random_generator/_3d/rotation.py@@ -21,7 +21,7 @@ import torchfrom kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistributionfrom kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _tuple_range_reader-from kornia.utils.helpers import _extract_device_dtype+from kornia.core.utils import _extract_device_dtypeclass RotationGenerator3D(RandomGeneratorBase):diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 11c541d35..22a037da6 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -21,9 +21,9 @@ from typing import Any, Callable, Dict, List, Optional, Tuple, Unionimport torchfrom torch.distributions import Beta, Uniform+from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints-from kornia.utils import _extract_device_dtypedef _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:diff --git a/kornia/contrib/boxmot_tracker.py b/kornia/contrib/boxmot_tracker.pyindex f0353ca6c..eed984e00 100644--- a/kornia/contrib/boxmot_tracker.py+++ b/kornia/contrib/boxmot_tracker.py@@ -29,8 +29,8 @@ from kornia.config import kornia_configfrom kornia.contrib.object_detection import ObjectDetector, RTDETRDetectorBuilderfrom kornia.core.external import boxmotfrom kornia.core.external import numpy as np+from kornia.image.utils import tensor_to_imagefrom kornia.io import write_image-from kornia.utils.image import tensor_to_image__all__ = ["BoxMotTracker"]@@ -71,15 +71,9 @@ class BoxMotTracker:fuse_first_associate: Whether to fuse appearance and motion information during the first association step.with_reid: Whether to use ReID (Re-Identification) features for association.- .. code-block:: python-- import kornia- import torch- image = kornia.utils.sample.get_sample_images()[0][None]- model = BoxMotTracker()- for i in range(4): # At least 4 frames are needed to initialize the tracking position- model.update(image)- model.save(image)+ Note:+ To use this tracker, load image tensors (shape: ``(1, C, H, W)``) and call ``model.update(image)``+ for at least 4 frames before calling ``model.save(image)``... note::At least 4 frames are needed to initialize the tracking position.diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.pyindex 3b37de999..888f8d1cd 100644--- a/kornia/contrib/distance_transform.py+++ b/kornia/contrib/distance_transform.py@@ -21,7 +21,7 @@ import torchfrom torch import nnfrom kornia.filters import filter2d-from kornia.utils import create_meshgrid+from kornia.geometry.grid import create_meshgriddef distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.pyindex 5ecbf0b51..85fc89860 100644--- a/kornia/contrib/edge_detection.py+++ b/kornia/contrib/edge_detection.py@@ -212,11 +212,8 @@ class EdgeDetectorBuilder:This is a high-level API that builds edge detection models like :py:class:`kornia.models.DexiNed`and wraps them with :py:class:`EdgeDetector`.- .. code-block:: python-- images = kornia.utils.sample.get_sample_images()- model = EdgeDetectorBuilder.build()- model.save(images)+ Note:+ To use this model, load image tensors and call ``model.save(images)``."""@staticmethoddiff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex 67b9ae950..608b5b52f 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -28,9 +28,9 @@ from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnxfrom kornia.core.mixin.onnx import ONNXExportMixin+from kornia.image.draw import draw_rectanglefrom kornia.models.base import ModelBasefrom kornia.models.processors import ResizePreProcessor-from kornia.utils.draw import draw_rectangle__all__ = ["BoundingBox",@@ -402,11 +402,8 @@ class RTDETRDetectorBuilder:- Build an object detection model from a model name or configuration.- Export the model to ONNX format for inference.- .. code-block:: python-- images = kornia.utils.sample.get_sample_images()- model = RTDETRDetectorBuilder.build()- model.save(images)+ Note:+ To use this model, load image tensors and call ``model.save(images)``."""@staticmethoddiff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.pyindex 0f0e8a18c..6149b5c38 100644--- a/kornia/contrib/super_resolution.py+++ b/kornia/contrib/super_resolution.py@@ -27,7 +27,7 @@ from kornia.core.mixin.onnx import ONNXExportMixinfrom kornia.models.base import ModelBasefrom kornia.models.processors import OutputRangePostProcessor, ResizePreProcessorfrom kornia.models.small_sr import SmallSRNetWrapper-from kornia.utils.download import CachedDownloader+from kornia.onnx.download import CachedDownloader__all__ = ["RRDBNetBuilder", "SmallSRBuilder", "SuperResolution"]diff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex b1c24870d..bd40fefb1 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -28,7 +28,7 @@ from .mixin import (ONNXRuntimeMixin,)from .module import ImageModule, ImageSequential-from .tensor_wrapper import TensorWrapper # type: ignore+from .tensor_wrapper import TensorWrapper__all__ = ["ImageModule",@@ -39,4 +39,6 @@ __all__ = ["ONNXRuntimeMixin","TensorWrapper","external",+ "eye_like",+ "vec_like",]diff --git a/kornia/core/_compat.py b/kornia/core/_compat.pynew file mode 100644index 000000000..d12d3191f--- /dev/null+++ b/kornia/core/_compat.py@@ -0,0 +1,221 @@+# 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 warnings+from functools import wraps+from inspect import isclass+from typing import Any, Callable, Optional++import torch+from packaging import version+++def torch_version() -> str:+ """Parse the PyTorch version string and remove build metadata.++ Extracts the clean version number from `torch.__version__` by removing any+ build suffixes like "+cu118" (CUDA builds) or "+cpu" (CPU builds).++ Returns:+ The clean version string (e.g., "2.0.1" from "2.0.1+cu118").++ Example:+ >>> torch_version()+ '2.0.1'+ """+ return torch.__version__.partition("+")[0]+++def torch_version_lt(major: int, minor: int, patch: int) -> bool:+ """Check if the current PyTorch version is less than the specified version.++ Args:+ major: Major version number (e.g., 2 for version 2.x.x).+ minor: Minor version number (e.g., 0 for version x.0.x).+ patch: Patch version number (e.g., 1 for version x.x.1).++ Returns:+ True if the current PyTorch version is strictly less than the specified version,+ False otherwise.++ Example:+ >>> torch_version_lt(2, 0, 0) # True if PyTorch < 2.0.0+ False+ >>> torch_version_lt(3, 0, 0) # True if PyTorch < 3.0.0+ True+ """+ _version = version.parse(torch_version())+ return _version < version.parse(f"{major}.{minor}.{patch}")+++def torch_version_le(major: int, minor: int, patch: int) -> bool:+ """Check if the current PyTorch version is less than or equal to the specified version.++ Args:+ major: Major version number (e.g., 2 for version 2.x.x).+ minor: Minor version number (e.g., 0 for version x.0.x).+ patch: Patch version number (e.g., 1 for version x.x.1).++ Returns:+ True if the current PyTorch version is less than or equal to the specified version,+ False otherwise.++ Example:+ >>> torch_version_le(2, 0, 0) # True if PyTorch <= 2.0.0+ True+ >>> torch_version_le(1, 13, 0) # True if PyTorch <= 1.13.0+ True+ """+ _version = version.parse(torch_version())+ return _version <= version.parse(f"{major}.{minor}.{patch}")+++def torch_version_ge(major: int, minor: int, patch: Optional[int] = None) -> bool:+ """Check if the current PyTorch version is greater than or equal to the specified version.++ This function is useful for implementing version-specific behavior or compatibility checks.+ When `patch` is None, only major and minor versions are compared.++ Args:+ major: Major version number (e.g., 2 for version 2.x.x).+ minor: Minor version number (e.g., 0 for version x.0.x).+ patch: Optional patch version number (e.g., 1 for version x.x.1).+ If None, only major.minor version is compared.++ Returns:+ True if the current PyTorch version is greater than or equal to the specified version,+ False otherwise.++ Example:+ >>> torch_version_ge(2, 0, 0) # True if PyTorch >= 2.0.0+ True+ >>> torch_version_ge(2, 4) # True if PyTorch >= 2.4.0 (any patch)+ True+ >>> torch_version_ge(3, 0, 0) # True if PyTorch >= 3.0.0+ False+ """+ _version = version.parse(torch_version())+ if patch is None:+ return _version >= version.parse(f"{major}.{minor}")+ else:+ return _version >= version.parse(f"{major}.{minor}.{patch}")+++def _emit_deprecation_warning(+ name: str, replace_with: Optional[str], version: Optional[str], extra_reason: Optional[str]+) -> None:+ """Emit a deprecation warning with the given parameters."""+ beginning = f"Since kornia {version} the " if version is not None else ""+ extra = f" {extra_reason}" if extra_reason else ""++ warnings.simplefilter("always", DeprecationWarning)+ try:+ if replace_with is not None:+ msg = f"{beginning}`{name}` is deprecated in favor of `{replace_with}`.{extra}"+ else:+ msg = f"{beginning}`{name}` is deprecated and will be removed in the future versions.{extra}"+ warnings.warn(+ msg,+ category=DeprecationWarning,+ stacklevel=3,+ )+ finally:+ warnings.simplefilter("default", DeprecationWarning)+++def deprecated(+ replace_with: Optional[str] = None, version: Optional[str] = None, extra_reason: Optional[str] = None+) -> Any:+ """Mark functions or classes as deprecated with a warning.++ This decorator emits a :class:`DeprecationWarning` when the decorated function or class is called.+ It provides information about when the deprecation was introduced and what should be used instead.++ Args:+ replace_with: The name of the replacement function/class that should be used instead.+ If provided, the warning message will suggest using this replacement.+ version: The kornia version when the deprecation was introduced (e.g., "0.8.3").+ If provided, the warning message will include "Since kornia {version}".+ extra_reason: Additional context or reason for the deprecation. This will be appended+ to the warning message.++ Returns:+ A decorator that wraps the function or class with deprecation warnings.++ Example:+ Basic usage without replacement:+ ```python+ @deprecated(version="0.8.3")+ def old_function():+ pass+ ```++ With replacement suggestion:+ ```python+ @deprecated(replace_with="new_function", version="0.8.3")+ def old_function():+ pass+ ```++ With additional context:+ ```python+ @deprecated(+ replace_with="new_function",+ version="0.8.3",+ extra_reason=" The old implementation has performance issues."+ )+ def old_function():+ pass+ ```++ Works with classes too:+ ```python+ @deprecated(replace_with="NewClass", version="0.8.3")+ class OldClass:+ pass+ ```+ """++ def _deprecated(func: Callable[..., Any]) -> Any:+ # Get the name - use __name__ for both functions and classes+ name = getattr(func, "__name__", "unknown")++ if isclass(func):+ # For classes, wrap in a function that emits warning and instantiates the class+ # We manually preserve important class attributes since @wraps doesn't work on classes+ def class_wrapper(*args: Any, **kwargs: Any) -> Any:+ _emit_deprecation_warning(name, replace_with, version, extra_reason)+ return func(*args, **kwargs)++ # Preserve important class attributes+ class_wrapper.__name__ = name+ class_wrapper.__qualname__ = getattr(func, "__qualname__", name)+ class_wrapper.__module__ = getattr(func, "__module__", None)+ class_wrapper.__doc__ = func.__doc__+ class_wrapper.__annotations__ = getattr(func, "__annotations__", {})+ return class_wrapper+ else:+ # For functions, use @wraps normally+ @wraps(func)+ def wrapper(*args: Any, **kwargs: Any) -> Any:+ _emit_deprecation_warning(name, replace_with, version, extra_reason)+ return func(*args, **kwargs)++ return wrapper++ return _deprecateddiff --git a/kornia/core/check.py b/kornia/core/check.pyindex d075135cc..e1d5d21f6 100644--- a/kornia/core/check.py+++ b/kornia/core/check.py@@ -24,7 +24,6 @@ from typing import Any, Optional, Sequence, TypeVar, castimport torchfrom torch import float16, float32, float64-from typing_extensions import TypeGuardfrom kornia.core.exceptions import (BaseError,@@ -255,7 +254,7 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = Truereturn True-def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:+def KORNIA_UNWRAP(maybe_obj: Any, typ: Any) -> Any:"""Unwrap an optional contained value that may or not be present.Args:@@ -270,9 +269,7 @@ def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:T = TypeVar("T", bound=type)-def KORNIA_CHECK_TYPE(- x: object, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True-) -> TypeGuard[T]:+def KORNIA_CHECK_TYPE(x: Any, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True) -> bool:"""Check the type of an aribratry variable.Args:@@ -301,20 +298,29 @@ def KORNIA_CHECK_TYPE(if not isinstance(x, typ):if raises:- expected_type_str = typ.__name__ if not isinstance(typ, tuple) else " | ".join(t.__name__ for t in typ)- error_msg = f"Type mismatch: expected {expected_type_str}, got {type(x).__name__}."- if msg is not None:- error_msg += f"\n {msg}"- raise TypeCheckError(- error_msg,- actual_type=type(x),- expected_type=typ,- )+ # JIT doesn't support try-except or type introspection, so use simple message+ if torch.jit.is_scripting():+ error_msg = "Type mismatch."+ if msg is not None:+ error_msg += f"\n {msg}"+ raise TypeCheckError(error_msg)+ else:+ # In Python mode, we can safely use type introspection+ expected_type_str = typ.__name__ if not isinstance(typ, tuple) else " | ".join(t.__name__ for t in typ)+ type_name = str(type(x))+ error_msg = f"Type mismatch: expected {expected_type_str}, got {type_name}."+ if msg is not None:+ error_msg += f"\n {msg}"+ raise TypeCheckError(+ error_msg,+ actual_type=type(x),+ expected_type=typ,+ )return Falsereturn True-def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool = True) -> TypeGuard[torch.Tensor]:+def KORNIA_CHECK_IS_TENSOR(x: Any, msg: Optional[str] = None, raises: bool = True) -> bool:"""Check the input variable is a Tensor.Args:@@ -343,19 +349,28 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool =if not isinstance(x, torch.Tensor):if raises:- error_msg = f"Type mismatch: expected Tensor, got {type(x).__name__}."- if msg is not None:- error_msg += f"\n {msg}"- raise TypeCheckError(- error_msg,- actual_type=type(x),- expected_type=torch.Tensor,- )+ # JIT doesn't support try-except or type introspection, so use simple message+ if torch.jit.is_scripting():+ error_msg = "Type mismatch: expected Tensor."+ if msg is not None:+ error_msg += f"\n {msg}"+ raise TypeCheckError(error_msg)+ else:+ # In Python mode, we can safely use type introspection+ type_name = str(type(x))+ error_msg = f"Type mismatch: expected Tensor, got {type_name}."+ if msg is not None:+ error_msg += f"\n {msg}"+ raise TypeCheckError(+ error_msg,+ actual_type=type(x),+ expected_type=torch.Tensor,+ )return Falsereturn True-def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool = True) -> TypeGuard[list[torch.Tensor]]:+def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[Any]], raises: bool = True) -> bool:"""Check the input variable is a List of Tensors.Args:diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex ca1e9e574..c4d24d28b 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -19,7 +19,7 @@ import datetimeimport mathimport osfrom functools import wraps-from typing import Any, Callable, List, Optional, Tuple, Union+from typing import Any, Callable, List, Literal, Optional, Tuple, Unionimport torch@@ -39,18 +39,21 @@ class ImageModuleMixIn:def convert_input_output(self,input_names_to_handle: Optional[List[Any]] = None,- output_type: str = "tensor",+ output_type: Literal["pt", "numpy", "pil"] = "pt",) -> Callable[[Any], Any]:"""Convert input and output types for a function.Args:input_names_to_handle: List of input names to convert, if None, handle all inputs.- output_type: Desired output type ('tensor', 'numpy', or 'pil').+ output_type: Desired output type ('pt', 'numpy', or 'pil').Returns:Callable: Decorated function with converted input and output types."""+ # Validate output_type at the start+ if output_type not in ("pt", "numpy", "pil"):+ raise ValueError(f"Invalid output_type '{output_type}'. Must be one of 'pt', 'numpy', or 'pil'.")def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:@wraps(func)@@ -75,20 +78,20 @@ class ImageModuleMixIn:# Call the actual forward methodtensor_outputs = func(*args, **kwargs)- if not isinstance(tensor_outputs, (tuple,)):+ if not isinstance(tensor_outputs, tuple):tensor_outputs = (tensor_outputs,)# Convert outputs to the desired typeoutputs = []for output in tensor_outputs:- if output_type == "tensor":+ if output_type == "pt":outputs.append(output)elif output_type == "numpy":outputs.append(self.to_numpy(output))elif output_type == "pil":outputs.append(self.to_pil(output))else:- raise ValueError("Output type not supported. Choose from 'tensor', 'numpy', or 'pil'.")+ raise ValueError("Output type not supported. Choose from 'pt', 'numpy', or 'pil'.")return outputs if len(outputs) > 1 else outputs[0]@@ -106,12 +109,12 @@ class ImageModuleMixIn:bool: True if valid, False otherwise."""- if isinstance(arg, (str,)) and os.path.exists(arg):+ if isinstance(arg, str) and os.path.exists(arg):return True- if isinstance(arg, (torch.Tensor,)):+ if isinstance(arg, torch.Tensor):return True# Make sure that the numpy and PIL are not necessarily needed to be imported.- if isinstance(arg, (np.ndarray,)): # type: ignore+ if isinstance(arg, np.ndarray): # type: ignorereturn Trueif isinstance(arg, (Image.Image)): # type: ignorereturn True@@ -129,17 +132,17 @@ class ImageModuleMixIn:Tensor: The converted tensor."""- if isinstance(x, (str,)):+ if isinstance(x, str):from kornia.io import ImageLoadType, load_image # pylint: disable=C0415return load_image(x, ImageLoadType.UNCHANGED) / 255- if isinstance(x, (torch.Tensor,)):+ if isinstance(x, torch.Tensor):return x- if isinstance(x, (np.ndarray,)): # type: ignore- from kornia.utils.image import image_to_tensor # pylint: disable=C0415+ if isinstance(x, np.ndarray): # type: ignore+ from kornia.image.utils import image_to_tensor # pylint: disable=C0415return image_to_tensor(x) / 255- if isinstance(x, (Image.Image,)): # type: ignore+ if isinstance(x, Image.Image): # type: ignorereturn torch.from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignoreraise TypeError("Input type not supported")@@ -153,11 +156,11 @@ class ImageModuleMixIn:np.array: The converted numpy array."""- if isinstance(x, (torch.Tensor,)):+ if isinstance(x, torch.Tensor):return x.cpu().detach().numpy()- if isinstance(x, (np.ndarray,)): # type: ignore+ if isinstance(x, np.ndarray): # type: ignorereturn x- if isinstance(x, (Image.Image,)): # type: ignore+ if isinstance(x, Image.Image): # type: ignorereturn np.array(x) # type: ignoreraise TypeError("Input type not supported")@@ -171,7 +174,7 @@ class ImageModuleMixIn:Image.Image: The converted PIL image."""- if isinstance(x, (torch.Tensor,)):+ if isinstance(x, torch.Tensor):x = x.cpu().detach() * 255if x.dim() == 3:x = x.permute(1, 2, 0)@@ -181,24 +184,18 @@ class ImageModuleMixIn:return [Image.fromarray(_x.byte().numpy()) for _x in x] # type: ignoreelse:raise NotImplementedError- if isinstance(x, (np.ndarray,)): # type: ignore+ if isinstance(x, np.ndarray): # type: ignoreraise NotImplementedError- if isinstance(x, (Image.Image,)): # type: ignore+ if isinstance(x, Image.Image): # type: ignorereturn xraise TypeError("Input type not supported")def _detach_tensor_to_cpu(self, output_image: Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]) -> Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]:- if isinstance(output_image, (torch.Tensor,)):+ if isinstance(output_image, torch.Tensor):return output_image.detach().cpu()- if isinstance(- output_image,- (- list,- tuple,- ),- ):+ if isinstance(output_image, list | tuple):return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignoreraise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")@@ -217,7 +214,7 @@ class ImageModuleMixIn:if len(self._output_image.shape) == 3:out_image = self._output_imageelif len(self._output_image.shape) == 4:- from kornia.utils.image import make_grid # pylint: disable=C0415+ from kornia.image.utils import make_grid # pylint: disable=C0415if n_row is None:n_row = math.ceil(self._output_image.shape[0] ** 0.5)@@ -240,8 +237,8 @@ class ImageModuleMixIn:n_row: Number of images displayed in each row of the grid."""+ from kornia.image.utils import make_grid # pylint: disable=C0415from kornia.io import write_image # pylint: disable=C0415- from kornia.utils.image import make_grid # pylint: disable=C0415if name is None:name = f"Kornia-{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}.jpg"diff --git a/kornia/core/module.py b/kornia/core/module.pyindex 546d42e34..7b938f551 100644--- a/kornia/core/module.py+++ b/kornia/core/module.py@@ -17,263 +17,14 @@from __future__ import annotations-import datetime-import math-import os-from functools import wraps-from typing import Any, Callable, Optional, Union+from typing import Any, Literal, Optional-import torchfrom torch import nn-# TODO: not use top level import-import kornia--from .external import PILImage as Image-from .external import numpy as np+from .mixin.image_module import ImageModuleMixInfrom .mixin.onnx import ONNXExportMixin-class ImageModuleMixIn:- """A MixIn that handles image-based operations.-- This modules accepts multiple input and output data types, provides end-to-end visualization, file saving features.- Note that this MixIn fits the classes that return one image tensor only.- """-- _output_image: Any-- def convert_input_output(- self,- input_names_to_handle: Optional[list[Any]] = None,- output_type: str = "tensor",- ) -> Callable[[Any], Any]:- """Convert input and output types for a function.-- Args:- input_names_to_handle: List of input names to convert, if None, handle all inputs.- output_type: Desired output type ('tensor', 'numpy', or 'pil').-- Returns:- Callable: Decorated function with converted input and output types.-- """- # Ensure output_type has a valid default- if not output_type or output_type not in ("tensor", "numpy", "pil"):- output_type = "tensor"-- def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:- @wraps(func)- def wrapper(*args: Any, **kwargs: Any) -> Union[Any, list[Any]]:- # Remove output_type and input_names_to_handle from kwargs if present- # (they are handled by the decorator, not the wrapped function)- kwargs.pop("output_type", None)- kwargs.pop("input_names_to_handle", None)-- # If input_names_to_handle is None, handle all inputs- if input_names_to_handle is None:- # Convert all args to tensors- args = tuple(self.to_tensor(arg) if self._is_valid_arg(arg) else arg for arg in args)- # Convert all kwargs to tensors- kwargs = {k: self.to_tensor(v) if self._is_valid_arg(v) else v for k, v in kwargs.items()}- else:- # Convert specified args to tensors- args = list(args) # type:ignore- for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)):- if name in input_names_to_handle:- args[i] = self.to_tensor(arg) # type:ignore- # Convert specified kwargs to tensors- for name, value in kwargs.items():- if name in input_names_to_handle:- kwargs[name] = self.to_tensor(value)-- # Call the actual forward method- tensor_outputs = func(*args, **kwargs)-- if not isinstance(tensor_outputs, (tuple,)):- tensor_outputs = (tensor_outputs,)-- # Convert outputs to the desired type- outputs = []- for output in tensor_outputs:- if output_type == "tensor":- outputs.append(output)- elif output_type == "numpy":- outputs.append(self.to_numpy(output))- elif output_type == "pil":- outputs.append(self.to_pil(output))- else:- raise ValueError("Output type not supported. Choose from 'tensor', 'numpy', or 'pil'.")-- return outputs if len(outputs) > 1 else outputs[0]-- return wrapper-- return decorator-- def _is_valid_arg(self, arg: Any) -> bool:- """Check if the argument is a valid type for conversion.-- Args:- arg: The argument to check.-- Returns:- bool: True if valid, False otherwise.-- """- if isinstance(arg, (str,)) and os.path.exists(arg):- return True- if isinstance(arg, (torch.Tensor,)):- return True- # Make sure that the numpy and PIL are not necessarily needed to be imported.- if isinstance(arg, (np.ndarray,)): # type: ignore- return True- if isinstance(arg, (Image.Image)): # type: ignore- return True- return False-- def to_tensor(self, x: Any) -> torch.Tensor:- """Convert input to tensor.-- Supports image path, numpy array, PIL image, and raw tensor.-- Args:- x: The input to convert.-- Returns:- Tensor: The converted tensor.-- """- if isinstance(x, (str,)):- return kornia.io.load_image(x, kornia.io.ImageLoadType.UNCHANGED) / 255- if isinstance(x, (torch.Tensor,)):- return x- if isinstance(x, (np.ndarray,)): # type: ignore- return kornia.utils.image.image_to_tensor(x) / 255- if isinstance(x, (Image.Image,)): # type: ignore- return torch.from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore- raise TypeError("Input type not supported")-- def to_numpy(self, x: Any) -> np.array: # type: ignore- """Convert input to numpy array.-- Args:- x: The input to convert.-- Returns:- np.array: The converted numpy array.-- """- if isinstance(x, (torch.Tensor,)):- return x.cpu().detach().numpy()- if isinstance(x, (np.ndarray,)): # type: ignore- return x- if isinstance(x, (Image.Image,)): # type: ignore- return np.array(x) # type: ignore- raise TypeError("Input type not supported")-- def to_pil(self, x: Any) -> Image.Image: # type: ignore- """Convert input to PIL image.-- Args:- x: The input to convert.-- Returns:- Image.Image: The converted PIL image.-- """- if isinstance(x, (torch.Tensor,)):- tensor = x.detach().cpu()- if tensor.ndim == 3:- tensor.mul_(255)- arr = tensor.permute(1, 2, 0).contiguous().byte().numpy()- if arr.shape[2] == 1:- arr = arr[:, :, 0]- return Image.fromarray(arr) # type: ignore- if tensor.ndim == 4:- tensor.mul_(255)- tensor_chw = tensor.permute(0, 2, 3, 1).contiguous()- numpy_batch = tensor_chw.byte().numpy()- return [Image.fromarray(img) for img in numpy_batch] # type: ignore- else:- raise NotImplementedError- if isinstance(x, (np.ndarray,)): # type: ignore- raise NotImplementedError- if isinstance(x, (Image.Image,)): # type: ignore- return x- raise TypeError("Input type not supported")-- def _detach_tensor_to_cpu(- self, output_image: Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor]]- ) -> Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor]]:- """Detach the input tensor (or list/tuple of tensors) from the GPU and move it to the CPU.-- Args:- output_image (Union[Tensor, list[Tensor], tuple[Tensor]]): The input tensor(s) to be moved.-- Returns:- Union[Tensor, list[Tensor], tuple[Tensor]]: The tensor(s) moved to the CPU and detached from- the computational graph.- """- if isinstance(output_image, (torch.Tensor,)):- return output_image.detach().cpu()- if isinstance(- output_image,- (- list,- tuple,- ),- ):- return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignore- raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")-- def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]:- """Return PIL images.-- Args:- n_row: Number of images displayed in each row of the grid.- backend: visualization backend. Only PIL is supported now.- display: whether to display the image.-- """- if self._output_image is None:- raise ValueError("No pre-computed images found. Needs to execute first.")-- if len(self._output_image.shape) == 3:- out_image = self._output_image- elif len(self._output_image.shape) == 4:- if n_row is None:- n_row = math.ceil(self._output_image.shape[0] ** 0.5)- out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2)- else:- raise ValueError-- if backend == "pil" and display:- Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)).show() # type: ignore- return None- if backend == "pil":- return Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)) # type: ignore- raise ValueError(f"Unsupported backend `{backend}`.")-- def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None:- """Save the output image(s) to a directory.-- Args:- name: Directory to save the images.- n_row: Number of images displayed in each row of the grid.-- """- if name is None:- name = f"Kornia-{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}.jpg"- if len(self._output_image.shape) == 3:- out_image = self._output_image- if len(self._output_image.shape) == 4:- if n_row is None:- n_row = math.ceil(self._output_image.shape[0] ** 0.5)- out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2)- kornia.io.write_image(name, out_image.mul(255.0).byte())--class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):"""Handles image-based operations.@@ -303,7 +54,7 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):self,*inputs: Any,input_names_to_handle: Optional[list[Any]] = None,- output_type: str = "tensor",+ output_type: Literal["pt", "numpy", "pil"] = "pt",**kwargs: Any,) -> Any:"""Overwrite the __call__ function to handle various inputs.@@ -311,7 +62,7 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):Args:inputs: Inputs to operate on.input_names_to_handle: List of input names to convert, if None, handle all inputs.- output_type: Desired output type ('tensor', 'numpy', or 'pil').+ output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.Returns:@@ -324,7 +75,7 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):input_names_to_handle=input_names_to_handle, output_type=output_type)(super().__call__)_output_image = decorated_forward(*inputs, **kwargs)- if output_type == "tensor":+ if output_type == "pt":self._output_image = self._detach_tensor_to_cpu(_output_image)else:self._output_image = _output_image@@ -362,7 +113,7 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):self,*inputs: Any,input_names_to_handle: Optional[list[Any]] = None,- output_type: str = "tensor",+ output_type: Literal["pt", "numpy", "pil"] = "pt",**kwargs: Any,) -> Any:"""Overwrite the __call__ function to handle various inputs.@@ -370,7 +121,7 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):Args:inputs: Inputs to operate on.input_names_to_handle: List of input names to convert, if None, handle all inputs.- output_type: Desired output type ('tensor', 'numpy', or 'pil').+ output_type: Desired output type ('pt', 'numpy', or 'pil').kwargs: Additional arguments.Returns:@@ -383,7 +134,7 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):input_names_to_handle=input_names_to_handle, output_type=output_type)(super().__call__)_output_image = decorated_forward(*inputs, **kwargs)- if output_type == "tensor":+ if output_type == "pt":self._output_image = self._detach_tensor_to_cpu(_output_image)else:self._output_image = _output_imagediff --git a/kornia/utils/misc.py b/kornia/core/ops.pysimilarity index 54%rename from kornia/utils/misc.pyrename to kornia/core/ops.pyindex 7af3c35d2..82f3d59aa 100644--- a/kornia/utils/misc.py+++ b/kornia/core/ops.py@@ -15,10 +15,10 @@# limitations under the License.#-from typing import Optional-import torch+from kornia.core.check import KORNIA_CHECK+def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.@@ -38,12 +38,11 @@ def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True."""- if n <= 0:- raise AssertionError(type(n), n)- if len(input.shape) < 1:- raise AssertionError(input.shape)+ KORNIA_CHECK(n > 0, f"n must be positive. Got: {n}")+ KORNIA_CHECK(len(input.shape) >= 1, f"input must have at least 1 dimension. Got shape: {input.shape}")- identity = torch.eye(n, device=input.device).type(input.dtype)+ # Use torch.eye with dtype parameter directly (available since PyTorch 2.0+)+ identity = torch.eye(n, device=input.device, dtype=input.dtype)return identity[None].expand(input.shape[0], n, n) if shared_memory else identity[None].repeat(input.shape[0], 1, 1)@@ -66,70 +65,8 @@ def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torchuse this method with shared_memory=False, otherwise, prefer using it with shared_memory=True."""- if n <= 0:- raise AssertionError(type(n), n)- if len(tensor.shape) < 1:- raise AssertionError(tensor.shape)+ KORNIA_CHECK(n > 0, f"n must be positive. Got: {n}")+ KORNIA_CHECK(len(tensor.shape) >= 1, f"tensor must have at least 1 dimension. Got shape: {tensor.shape}")vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)return vec[None].expand(tensor.shape[0], n, 1) if shared_memory else vec[None].repeat(tensor.shape[0], 1, 1)---def differentiable_polynomial_rounding(input: torch.Tensor) -> torch.Tensor:- """Differentiable rounding.-- Args:- input (torch.Tensor): Input tensor of any shape to be rounded.-- Returns:- output (torch.Tensor): Pseudo rounded tensor of the same shape as input tensor.-- """- # Perform differentiable rounding- input_round = input.round()- output: torch.Tensor = input_round + (input - input_round) ** 3- return output---def differentiable_polynomial_floor(input: torch.Tensor) -> torch.Tensor:- """Perform floor via a differentiable operation.-- Args:- input (torch.Tensor): Input tensor of any shape to be floored.-- Returns:- output (torch.Tensor): Pseudo rounded tensor of the same shape as input tensor.-- """- # Perform differentiable rounding- input_floor = input.floor()- output: torch.Tensor = input_floor + (input - 0.5 - input_floor) ** 3- return output---def differentiable_clipping(- input: torch.Tensor,- min_val: Optional[float] = None,- max_val: Optional[float] = None,- scale: float = 0.02,-) -> torch.Tensor:- """Clip via a differentiable and soft approximation of the clipping operation.-- Args:- input (torch.Tensor): Input tensor of any shape.- min_val (Optional[float]): Minimum value.- max_val (Optional[float]): Maximum value.- scale (float): Scale value. Default 0.02.-- Returns:- output (torch.Tensor): Clipped output tensor of the same shape as the input tensor.-- """- # Make a copy of the input tensor- output: torch.Tensor = input.clone()- # Perform differentiable soft clipping- if max_val is not None:- output[output > max_val] = -scale * (torch.exp(-output[output > max_val] + max_val) - 1.0) + max_val- if min_val is not None:- output[output < min_val] = scale * (torch.exp(output[output < min_val] - min_val) - 1.0) + min_val- return outputdiff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.pyindex 9e4f398fb..b21e0cb62 100644--- a/kornia/core/tensor_wrapper.py+++ b/kornia/core/tensor_wrapper.py@@ -15,169 +15,268 @@# limitations under the License.#-# type: ignore-# pytorch tensor wrapper class-# insipired by:-# https://github.com/pytorch/pytorch/blob/591dfffa38848de54b7f5f4e49260847024c9281/test/test_overrides.py#L748-import collections+from __future__ import annotations++import collections.abc+from typing import Any, Optionalimport torchfrom torch import Tensor+from kornia.core.check import KORNIA_CHECK_IS_TENSOR+++def _wrap(v: Any, cls: type[TensorWrapper]) -> Any:+ """Wrap type.++ Args:+ v: Value to wrap (tensor, list, tuple, or other).+ cls: TensorWrapper class to use for wrapping.-# TODO: promote to KORNIA_WRAP-def wrap(v, cls):- """Wrap type."""+ Returns:+ Wrapped value if tensor, otherwise original value or wrapped collection.+ """# wrap inputs if necessaryif type(v) in {tuple, list}:- return type(v)(wrap(vi, cls) for vi in v)+ return type(v)(_wrap(vi, cls) for vi in v)return cls(v) if isinstance(v, Tensor) else v-# TODO: promote to KORNIA_UNWRAP-def unwrap(v):- """Unwrap nested type."""+def _unwrap(v: Any) -> Any:+ """Unwrap nested type.++ Args:+ v: Value to unwrap (TensorWrapper, list, tuple, or other).++ Returns:+ Unwrapped value (underlying tensor or original value).+ """if type(v) in {tuple, list}:- return type(v)(unwrap(vi) for vi in v)+ return type(v)(_unwrap(vi) for vi in v)return v._data if isinstance(v, TensorWrapper) else vclass TensorWrapper:- """Wrap a PyTorch Tensor to provide additional metadata and specialized methods.-- Args:- data: The underlying :class:`torch.Tensor` to be wrapped.- """+ """Wrapper around PyTorch tensors that tracks attribute and function usage.- def __init__(self, data: Tensor) -> None:- self.__dict__["_data"] = data- self.__dict__["used_attrs"] = set()- self.__dict__["used_calls"] = set()+ This class provides a transparent wrapper around PyTorch tensors while+ tracking which attributes and functions are accessed. Useful for debugging+ and understanding tensor usage patterns.- def unwrap(self):- return unwrap(self)+ Attributes:+ _data: The underlying PyTorch tensor.+ used_attrs: Set of attribute names that have been accessed.+ used_calls: Set of functions that have been called.+ """- def __getstate__(self):- return self.__dict__+ __slots__ = ("_data", "used_attrs", "used_calls")- def __setstate__(self, state):- self.__dict__.update(state)+ def __init__(self, data: Tensor) -> None:+ """Initialize TensorWrapper with a PyTorch tensor.++ Args:+ data: The PyTorch tensor to wrap. If data is already a TensorWrapper,+ its underlying tensor will be extracted.++ Raises:+ TypeCheckError: If data is not a PyTorch tensor or TensorWrapper.+ """+ # Handle case where data is already a TensorWrapper (e.g., Scalar wrapping another Scalar)+ if isinstance(data, TensorWrapper):+ data = data._data+ KORNIA_CHECK_IS_TENSOR(data, "Expected Tensor for TensorWrapper")+ object.__setattr__(self, "_data", data)+ object.__setattr__(self, "used_attrs", set())+ object.__setattr__(self, "used_calls", set())++ def unwrap(self) -> Tensor:+ """Return the underlying PyTorch tensor."""+ return _unwrap(self)++ @property+ def data(self) -> Tensor:+ """Access the underlying tensor."""+ return self._data++ def __getstate__(self) -> dict[str, Any]:+ """Support for pickle serialization."""+ return {+ "_data": self._data,+ "used_attrs": self.used_attrs,+ "used_calls": self.used_calls,+ }++ def __setstate__(self, state: dict[str, Any]) -> None:+ """Support for pickle deserialization."""+ object.__setattr__(self, "_data", state["_data"])+ object.__setattr__(self, "used_attrs", state.get("used_attrs", set()))+ object.__setattr__(self, "used_calls", state.get("used_calls", set()))def __repr__(self) -> str:- return f"{self._data}"+ """Return string representation."""+ return f"{self.__class__.__name__}({self._data})"- def __getattr__(self, name):+ def __getattr__(self, name: str) -> Any:+ """Get attribute from underlying tensor."""+ # Handle special 'data' propertyif name == "data":return self._data- elif name in self.__dict__:- return self.__dict__[name]++ # Track attribute usageself.used_attrs.add(name)+ # Get value from underlying tensorval = getattr(self._data, name)- # NOTE: not clear is really needed- # If it's a method- # if callable(val):- # c = getattr(type(self._data), name)- # # Don't append self to args if classmethod/staticmethod- # if c is val:- # return lambda *a, **kw: wrap(self.__torch_function__(c, (type(self),), args=a, kwargs=kw), type(self))- # # Otherwise append self to args- # return lambda *a, **kw: wrap(- # #self.__torch_function__(c, (type(self),), args=(self,) + a, kwargs=kw), type(self)- # )-- return wrap(val, type(self))-- def __setattr__(self, name, value) -> None:- if name in self.__dict__:- self.__dict__[name] = value-- self.used_attrs.add(name)- setattr(self._data, name, value)-- def __setitem__(self, key, value) -> None:+ # Wrap the result if it's a tensor+ return _wrap(val, type(self))++ def __setattr__(self, name: str, value: Any) -> None:+ """Set attribute on underlying tensor."""+ # Only track non-internal attributes+ if name not in self.__slots__:+ self.used_attrs.add(name)+ setattr(self._data, name, value)+ else:+ # Use object.__setattr__ for internal attributes to avoid recursion+ object.__setattr__(self, name, value)++ def __setitem__(self, key: Any, value: Any) -> None:+ """Set item on underlying tensor."""self._data[key] = value- def __getitem__(self, key):- return wrap(self._data[key], type(self))+ def __getitem__(self, key: Any) -> TensorWrapper:+ """Get item from underlying tensor."""+ return _wrap(self._data[key], type(self))@classmethod- def __torch_function__(cls, func, types, args=(), kwargs=None):+ def __torch_function__(+ cls,+ func: Any,+ types: tuple[type, ...],+ args: tuple[Any, ...] = (),+ kwargs: Optional[dict[str, Any]] = None,+ ) -> Any:+ """Intercept PyTorch function calls."""if kwargs is None:kwargs = {}- # Find an instance of this class in the arguments- args_of_this_cls = []++ # Find instances of this class in the arguments+ args_of_this_cls: list[TensorWrapper] = []for a in args:if isinstance(a, cls):args_of_this_cls.append(a)- elif isinstance(a, collections.abc.Sequence):+ 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))- # assert len(args_of_this_cls) > 0++ # Track function usagefor a in args_of_this_cls:a.used_calls.add(func)- args = unwrap(tuple(args))- kwargs = {k: unwrap(v) for k, v in kwargs.items()}- return wrap(func(*args, **kwargs), cls)+ # Unwrap arguments and call the function+ unwrapped_args = _unwrap(args)+ unwrapped_kwargs = {k: _unwrap(v) for k, v in kwargs.items()}- # TODO: `def __add__(self, other) -> Self:` when mypy release >0.991- def __add__(self, other):- return self.__unary_op__(torch.add, other)+ return _wrap(func(*unwrapped_args, **unwrapped_kwargs), cls)- def __radd__(self, other):- return self.__unary_op__(torch.add, other)+ def __add__(self, other: Any) -> TensorWrapper:+ """Add operation."""+ return self.__binary_op__(torch.add, other)- def __mul__(self, other):- return self.__unary_op__(torch.mul, other)+ def __radd__(self, other: Any) -> TensorWrapper:+ """Right-side add operation."""+ return self.__binary_op__(torch.add, other, swap=True)- def __rmul__(self, other):- return self.__unary_op__(torch.mul, other)+ def __mul__(self, other: Any) -> TensorWrapper:+ """Multiply operation."""+ return self.__binary_op__(torch.mul, other)- def __sub__(self, other):- return self.__unary_op__(torch.sub, other)+ def __rmul__(self, other: Any) -> TensorWrapper:+ """Right-side multiply operation."""+ return self.__binary_op__(torch.mul, other, swap=True)- def __rsub__(self, other):- return self.__unary_op__(torch.sub, other)+ def __sub__(self, other: Any) -> TensorWrapper:+ """Subtract operation."""+ return self.__binary_op__(torch.sub, other)- def __truediv__(self, other):- return self.__unary_op__(torch.true_divide, other)+ def __rsub__(self, other: Any) -> TensorWrapper:+ """Right-side subtract operation."""+ return self.__binary_op__(torch.sub, other, swap=True)- def __floordiv__(self, other):- return self.__unary_op__(torch.floor_divide, other)+ def __truediv__(self, other: Any) -> TensorWrapper:+ """True division operation."""+ return self.__binary_op__(torch.true_divide, other)- def __ge__(self, other):- return self.__unary_op__(torch.ge, other)+ def __floordiv__(self, other: Any) -> TensorWrapper:+ """Floor division operation."""+ return self.__binary_op__(torch.floor_divide, other)- def __gt__(self, other):- return self.__unary_op__(torch.gt, other)+ def __ge__(self, other: Any) -> TensorWrapper:+ """Greater than or equal comparison."""+ return self.__binary_op__(torch.ge, other)- def __lt__(self, other):- return self.__unary_op__(torch.lt, other)+ def __gt__(self, other: Any) -> TensorWrapper:+ """Greater than comparison."""+ return self.__binary_op__(torch.gt, other)- def __le__(self, other):- return self.__unary_op__(torch.le, other)+ def __lt__(self, other: Any) -> TensorWrapper:+ """Less than comparison."""+ return self.__binary_op__(torch.lt, other)- def __eq__(self, other):- return self.__unary_op__(torch.eq, other)+ def __le__(self, other: Any) -> TensorWrapper:+ """Less than or equal comparison."""+ return self.__binary_op__(torch.le, other)- def __ne__(self, other):- return self.__unary_op__(torch.ne, other)+ def __eq__(self, other: object) -> TensorWrapper:+ """Equality comparison."""+ return self.__binary_op__(torch.eq, other)++ def __ne__(self, other: object) -> TensorWrapper:+ """Inequality comparison."""+ return self.__binary_op__(torch.ne, other)def __bool__(self) -> bool:- return self.__unary_op__(Tensor.__bool__)+ """Convert to boolean (unwrapped)."""+ return bool(self._data)def __int__(self) -> int:- return self.__unary_op__(Tensor.__int__)-- def __neg__(self):- return self.__unary_op__(Tensor.negative)+ """Convert to integer (unwrapped)."""+ return int(self._data)- def __unary_op__(self, func, other=None):- args = (self, other) if other is not None else (self,)- return self.__torch_function__(func, (type(self),), args)+ def __neg__(self) -> TensorWrapper:+ """Negation operation."""+ return self.__unary_op__(torch.neg)def __len__(self) -> int:+ """Return length of tensor."""return len(self._data)++ def __binary_op__(self, func: Any, other: Any, swap: bool = False) -> TensorWrapper:+ """Helper for binary operations.++ Args:+ func: The PyTorch function to call.+ other: The other operand.+ swap: If True, swap the order of operands (for right-side operations).++ Returns:+ Wrapped result of the operation.+ """+ if swap:+ args = (other, self)+ else:+ args = (self, other)+ return self.__torch_function__(func, (type(self),), args)++ def __unary_op__(self, func: Any) -> TensorWrapper:+ """Helper for unary operations.++ Args:+ func: The PyTorch function to call.++ Returns:+ Wrapped result of the operation.+ """+ return self.__torch_function__(func, (type(self),), (self,))diff --git a/kornia/utils/helpers.py b/kornia/core/utils.pysimilarity index 59%rename from kornia/utils/helpers.pyrename to kornia/core/utils.pyindex 1efed98c2..8c780dd24 100644--- a/kornia/utils/helpers.py+++ b/kornia/core/utils.py@@ -15,19 +15,19 @@# limitations under the License.#+import importlib.utilimport platformimport sys-import warningsfrom dataclasses import asdict, fields, is_dataclass-from functools import wraps-from inspect import isclass, isfunction-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union, overload+from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Unionimport torchfrom torch.linalg import inv_ex-from kornia.utils._compat import torch_version_ge+from kornia.core._compat import torch_version_ge+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_TYPE+from kornia.core.exceptions import DeviceErrordef xla_is_available() -> bool:@@ -85,59 +85,11 @@ def get_cuda_or_mps_device_if_available() -> torch.device:return get_cuda_device_if_available()-@overload-def map_location_to_cpu(storage: torch.Tensor, location: str) -> torch.Tensor: ...---@overload-def map_location_to_cpu(storage: str) -> str: ...---def map_location_to_cpu(storage: Union[str, torch.Tensor], *args: Any, **kwargs: Any) -> Union[str, torch.Tensor]:- """Map location of device to CPU, util for loading things from HUB."""- return storage---def deprecated(- replace_with: Optional[str] = None, version: Optional[str] = None, extra_reason: Optional[str] = None-) -> Any:- """Mark methods as deprecated."""-- def _deprecated(func: Callable[..., Any]) -> Any:- @wraps(func)- def wrapper(*args: Any, **kwargs: Any) -> Any:- name = ""- beginning = f"Since kornia {version} the " if version is not None else ""-- if isclass(func):- name = func.__class__.__name__- if isfunction(func):- name = func.__name__- warnings.simplefilter("always", DeprecationWarning)- if replace_with is not None:- warnings.warn(- f"{beginning}`{name}` is deprecated in favor of `{replace_with}`.{extra_reason}",- category=DeprecationWarning,- stacklevel=2,- )- else:- warnings.warn(- f"{beginning}`{name}` is deprecated and will be removed in the future versions.{extra_reason}",- category=DeprecationWarning,- stacklevel=2,- )- warnings.simplefilter("default", DeprecationWarning)- return func(*args, **kwargs)-- return wrapper-- return _deprecated--def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:"""Check if all the input are in the same device (only if when they are torch.Tensor).- If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).+ If so, it would return a tuple of (device, dtype).+ Default: (``torch.get_default_device()``, ``torch.get_default_dtype()``).Returns:[torch.device, torch.dtype]@@ -146,7 +98,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devicdevice, dtype = None, Nonefor tensor in tensor_list:if tensor is not None:- if not isinstance(tensor, (torch.Tensor,)):+ if not isinstance(tensor, torch.Tensor):continue_device = tensor.device_dtype = tensor.dtype@@ -154,29 +106,39 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devicdevice = _devicedtype = _dtypeelif device != _device or dtype != _dtype:- raise ValueError(- "Passed values are not in the same device and dtype."- f"Got ({device}, {dtype}) and ({_device}, {_dtype})."+ raise DeviceError(+ f"Passed values are not in the same device and dtype. "+ f"Got ({device}, {dtype}) and ({_device}, {_dtype}).",+ actual_devices=[device, _device],+ expected_device=device,)if device is None:- # TODO: update this when having torch.get_default_device()- device = torch.device("cpu")+ device = torch.get_default_device()if dtype is None:dtype = torch.get_default_dtype()return (device, dtype)+def _normalize_to_float32_or_float64(dtype: torch.dtype) -> torch.dtype:+ """Normalize dtype to float32 or float64 for operations that require full precision.++ Args:+ dtype: The input dtype to normalize.++ Returns:+ torch.float32 if dtype is not float32 or float64, otherwise returns the original dtype.+ """+ return dtype if dtype in (torch.float32, torch.float64) else torch.float32++def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:"""Make torch.inverse work with other than fp32/64.The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. Whatthis function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype."""- if not isinstance(input, torch.Tensor):- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")- dtype: torch.dtype = input.dtype- if dtype not in (torch.float32, torch.float64):- dtype = torch.float32+ KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")+ dtype = _normalize_to_float32_or_float64(input.dtype)return torch.linalg.inv(input.to(dtype)).to(input.dtype)@@ -186,11 +148,8 @@ def _torch_histc_cast(input: torch.Tensor, bins: int, min: Union[float, bool], mThe function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. Whatthis function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype."""- if not isinstance(input, torch.Tensor):- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")- dtype: torch.dtype = input.dtype- if dtype not in (torch.float32, torch.float64):- dtype = torch.float32+ KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")+ dtype = _normalize_to_float32_or_float64(input.dtype)return torch.histc(input.to(dtype), bins, min, max).to(input.dtype)@@ -203,17 +162,11 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, toNOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd"""- # if not isinstance(input, torch.Tensor):- # raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")- dtype = input.dtype- if dtype not in (torch.float32, torch.float64):- dtype = torch.float32+ dtype = _normalize_to_float32_or_float64(input.dtype)out1, out2, out3H = torch.linalg.svd(input.to(dtype))- if torch_version_ge(1, 11):- out3 = out3H.mH- else:- out3 = out3H.transpose(-1, -2)+ # Since kornia requires torch>=2.0.0, we can always use .mH+ out3 = out3H.mHreturn (out1.to(input.dtype), out2.to(input.dtype), out3.to(input.dtype))@@ -226,29 +179,24 @@ def _torch_linalg_svdvals(input: torch.Tensor) -> torch.Tensor:NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd"""- if not isinstance(input, torch.Tensor):- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")- dtype: torch.dtype = input.dtype- if dtype not in (torch.float32, torch.float64):- dtype = torch.float32+ KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")+ dtype = _normalize_to_float32_or_float64(input.dtype)- if TYPE_CHECKING:- # TODO: remove this branch when kornia relies on torch >= 1.10- out: torch.Tensor- elif torch_version_ge(1, 10):- out = torch.linalg.svdvals(input.to(dtype))- else:- # TODO: remove this branch when kornia relies on torch >= 1.10- _, out, _ = torch.linalg.svd(input.to(dtype))+ # Since kornia requires torch>=2.0.0, we can always use torch.linalg.svdvals+ out = torch.linalg.svdvals(input.to(dtype))return out.to(input.dtype)-# TODO: return only `torch.Tensor` and review all the calls to adjustdef _torch_solve_cast(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:"""Make torch.solve work with other than fp32/64.For stable operation, the input matrices should be cast to fp64, and the output willbe cast back to the input dtype. However, fp64 is not yet supported on MPS.++ This function is actively used in:+ - kornia.geometry.transform.imgwarp+ - kornia.geometry.transform.thin_plate_spline+ - kornia.geometry.epipolar.essential"""if is_mps_tensor_safe(A):dtype = torch.float32@@ -266,27 +214,14 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.TensorAvoids crashing because of singular matrix input and outputs the mask of valid solution."""- if not torch_version_ge(1, 10):- sol = _torch_solve_cast(A, B)- warnings.warn("PyTorch version < 1.10, solve validness mask maybe not correct", RuntimeWarning, stacklevel=1)- return sol, sol, torch.ones(len(A), dtype=torch.bool, device=A.device)# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622- if not isinstance(B, torch.Tensor):- raise AssertionError(f"B must be torch.Tensor. Got: {type(B)}.")+ KORNIA_CHECK_IS_TENSOR(B, "B must be torch.Tensor")dtype: torch.dtype = B.dtypeif dtype not in (torch.float32, torch.float64):dtype = torch.float32- if TYPE_CHECKING:- # TODO: remove this branch when kornia relies on torch >= 1.13- A_LU: torch.Tensor- pivots: torch.Tensor- info: torch.Tensor- elif torch_version_ge(1, 13):- A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))- else:- # TODO: remove this branch when kornia relies on torch >= 1.13- A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)+ # Since kornia requires torch>=2.0.0, we can always use torch.linalg.lu_factor_ex and torch.linalg.lu_solve+ A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))valid_mask: torch.Tensor = info == 0n_dim_B = len(B.shape)@@ -294,14 +229,7 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensorif n_dim_A - n_dim_B == 1:B = B.unsqueeze(-1)- if TYPE_CHECKING:- # TODO: remove this branch when kornia relies on torch >= 1.13- X: torch.Tensor- elif torch_version_ge(1, 13):- X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))- else:- # TODO: remove this branch when kornia relies on torch >= 1.13- X = torch.lu_solve(B.to(dtype), A_LU, pivots)+ X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))return X.to(B.dtype), A_LU.to(A.dtype), valid_mask@@ -311,14 +239,10 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]Avoids crashing because of non-invertable matrix input and outputs the mask of valid solution."""- if not isinstance(A, torch.Tensor):- raise AssertionError(f"A must be torch.Tensor. Got: {type(A)}.")+ KORNIA_CHECK_IS_TENSOR(A, "A must be torch.Tensor")dtype_original = A.dtype- if dtype_original not in (torch.float32, torch.float64):- dtype = torch.float32- else:- dtype = dtype_original+ dtype = _normalize_to_float32_or_float64(dtype_original)inverse, info = inv_ex(A.to(dtype))mask = info == 0@@ -338,13 +262,7 @@ def is_autocast_enabled(both: bool = True) -> bool:`torch.is_autocast_enabled()`."""- if TYPE_CHECKING:- # TODO: remove this branch when kornia relies on torch >= 1.10.2- return False-- if not torch_version_ge(1, 10, 2):- return False-+ # Since kornia requires torch>=2.0.0, autocast is always availableif both:if torch_version_ge(2, 4):return torch.is_autocast_enabled() or torch.is_autocast_enabled("cpu")@@ -358,7 +276,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()}- elif isinstance(obj, (list, tuple)):+ elif isinstance(obj, list | tuple):return type(obj)(dataclass_to_dict(item) for item in obj)elif isinstance(obj, dict):return {key: dataclass_to_dict(value) for key, value in obj.items()}@@ -371,10 +289,8 @@ T = TypeVar("T")def dict_to_dataclass(dict_obj: Dict[str, Any], dataclass_type: Type[T]) -> T:"""Recursively convert dictionaries to dataclass instances."""- if not isinstance(dict_obj, dict):- raise TypeError("Input conf must be dict")- if not is_dataclass(dataclass_type):- raise TypeError("dataclass_type must be a dataclass")+ KORNIA_CHECK_TYPE(dict_obj, dict, "Input conf must be dict")+ KORNIA_CHECK(is_dataclass(dataclass_type), "dataclass_type must be a dataclass")field_types: dict[str, Any] = {f.name: f.type for f in fields(dataclass_type)}constructor_args = {}for key, value in dict_obj.items():diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex af51a2f97..55be0f02c 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -30,8 +30,8 @@ from kornia.core.check import (KORNIA_CHECK_IS_COLOR_OR_GRAY,KORNIA_CHECK_IS_TENSOR,)-from kornia.utils.helpers import _torch_histc_cast-from kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video+from kornia.core.utils import _torch_histc_cast+from kornia.image.utils import perform_keep_shape_image, perform_keep_shape_videodef adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 9c59ff1ef..ed85583c4 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -23,8 +23,8 @@ from typing import Tupleimport torchimport torch.nn.functional as F-from kornia.utils.helpers import _torch_histc_cast-from kornia.utils.image import perform_keep_shape_image+from kornia.core.utils import _torch_histc_cast+from kornia.image.utils import perform_keep_shape_imagefrom .histogram import histogramdiff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.pyindex 3ea1ebf61..4ad529057 100644--- a/kornia/enhance/jpeg.py+++ b/kornia/enhance/jpeg.py@@ -32,12 +32,7 @@ from kornia.core.check import (KORNIA_CHECK_SHAPE,)from kornia.geometry.transform.affwarp import rescale-from kornia.utils.image import perform_keep_shape_image-from kornia.utils.misc import (- differentiable_clipping,- differentiable_polynomial_floor,- differentiable_polynomial_rounding,-)+from kornia.image.utils import perform_keep_shape_image_DCT8_CACHE: dict[tuple[Union[torch.dtype, None], Union[str, torch.device, None]], tuple[torch.Tensor, torch.Tensor]@@ -46,6 +41,60 @@ _DCT8_CACHE: dict[__all__ = ["JPEGCodecDifferentiable", "jpeg_codec_differentiable"]+def _differentiable_polynomial_rounding(input: torch.Tensor) -> torch.Tensor:+ """Differentiable rounding.++ Args:+ input: Input tensor of any shape to be rounded.++ Returns:+ Pseudo rounded tensor of the same shape as input tensor.++ """+ input_round = input.round()+ return input_round + (input - input_round) ** 3+++def _differentiable_polynomial_floor(input: torch.Tensor) -> torch.Tensor:+ """Perform floor via a differentiable operation.++ Args:+ input: Input tensor of any shape to be floored.++ Returns:+ Pseudo rounded tensor of the same shape as input tensor.++ """+ input_floor = input.floor()+ return input_floor + (input - 0.5 - input_floor) ** 3+++def _differentiable_clipping(+ input: torch.Tensor,+ min_val: Union[float, None] = None,+ max_val: Union[float, None] = None,+ scale: float = 0.02,+) -> torch.Tensor:+ """Clip via a differentiable and soft approximation of the clipping operation.++ Args:+ input: Input tensor of any shape.+ min_val: Minimum value.+ max_val: Maximum value.+ scale: Scale value. Default 0.02.++ Returns:+ Clipped output tensor of the same shape as the input tensor.++ """+ output: torch.Tensor = input.clone()+ if max_val is not None:+ output[output > max_val] = -scale * (torch.exp(-output[output > max_val] + max_val) - 1.0) + max_val+ if min_val is not None:+ output[output < min_val] = scale * (torch.exp(output[output < min_val] - min_val) - 1.0) + min_val+ return output++def _get_default_qt_y(device: Union[str, torch.device, None], dtype: Union[torch.dtype, None]) -> torch.Tensor:"""Generate default Quantization table of Y channel."""return torch.tensor(@@ -180,7 +229,7 @@ def _jpeg_quality_to_scale("""# Get scale- scale: torch.Tensor = differentiable_polynomial_floor(+ scale: torch.Tensor = _differentiable_polynomial_floor(torch.where(compression_strength < 50,5000.0 / compression_strength,@@ -211,12 +260,12 @@ def _quantize(quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None])# Perform scaling- quantization_table = differentiable_polynomial_floor(- differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)+ quantization_table = _differentiable_polynomial_floor(+ _differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255))output: torch.Tensor = input / quantization_table# Perform rounding- output = differentiable_polynomial_rounding(output)+ output = _differentiable_polynomial_rounding(output)return output@@ -241,8 +290,8 @@ def _dequantize(quantization_table[:, None] * _jpeg_quality_to_scale(jpeg_quality)[:, None, None, None])# Perform scaling- output: torch.Tensor = input * differentiable_polynomial_floor(- differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255)+ output: torch.Tensor = input * _differentiable_polynomial_floor(+ _differentiable_clipping((quantization_table_scaled + 50.0) / 100.0, 1, 255))return output@@ -579,7 +628,7 @@ def jpeg_codec_differentiable(quantization_table_y=quantization_table_y,)# Clip coded image- image_rgb_jpeg = differentiable_clipping(input=image_rgb_jpeg, min_val=0.0, max_val=255.0)+ image_rgb_jpeg = _differentiable_clipping(input=image_rgb_jpeg, min_val=0.0, max_val=255.0)# Crop the image again to the original shapeimage_rgb_jpeg = image_rgb_jpeg[..., : H - h_pad, : W - w_pad]return image_rgb_jpegdiff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 72457f4b0..cc7a0a069 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -22,7 +22,7 @@ from typing import List, Tuple, Unionimport torchfrom torch import nn-from kornia.utils.image import perform_keep_shape_image+from kornia.image.utils import perform_keep_shape_image__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"]diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.pyindex ba44700ae..bdab8c401 100644--- a/kornia/feature/dedode/dedode.py+++ b/kornia/feature/dedode/dedode.py@@ -23,7 +23,6 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.enhance.normalize import Normalize-from kornia.utils.helpers import map_location_to_cpufrom .dedode_models import DeDoDeDescriptor, DeDoDeDetector, get_descriptor, get_detectorfrom .utils import dedode_denormalize_pixel_coordinates, sample_keypointsdiff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 1fa958e73..0653db058 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -22,7 +22,7 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.utils.helpers import is_mps_tensor_safe+from kornia.core.utils import is_mps_tensor_safeurls: Dict[str, str] = {}urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 41aacafef..a01029cd6 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -301,7 +301,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0) -> Tuple[List[int],Examples:x, y = get_laf_pts_to_draw(LAF, img_idx)plt.figure()- plt.imshow(kornia.utils.tensor_to_image(img[img_idx]))+ plt.imshow(kornia.image.tensor_to_image(img[img_idx]))plt.plot(x, y, 'r')plt.show()diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex bba5adfc2..22d084e80 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -27,7 +27,6 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECKfrom kornia.feature.laf import laf_to_three_points, scale_laf-from kornia.utils._compat import custom_fwdtry:from flash_attn.modules.mha import FlashCrossAttention@@ -45,7 +44,7 @@ def math_clamp(x, min_, max_): # type: ignorereturn min(max(x, min_), max_)-@custom_fwd(cast_inputs=torch.float32)[email protected]_fwd(cast_inputs=torch.float32, device_type="cuda")def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:"""Normalize torch.tensor of keypoints."""if isinstance(size, torch.Size):diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.pyindex 72d92f1a7..309a0ebe7 100644--- a/kornia/feature/loftr/utils/fine_matching.py+++ b/kornia/feature/loftr/utils/fine_matching.py@@ -24,8 +24,8 @@ import torchimport torch.nn.functional as Ffrom torch import nn+from kornia.geometry.grid import create_meshgridfrom kornia.geometry.subpix import dsnt-from kornia.utils.grid import create_meshgridclass FineMatching(nn.Module):diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.pyindex ad914608f..3fed900c4 100644--- a/kornia/feature/loftr/utils/supervision.py+++ b/kornia/feature/loftr/utils/supervision.py@@ -21,7 +21,7 @@ from typing import Anyimport torch-from kornia.utils import create_meshgrid+from kornia.geometry.grid import create_meshgridfrom .geometry import warp_kptsdiff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex fb76e34bc..384641b91 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -22,9 +22,9 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE+from kornia.core.utils import is_mps_tensor_safefrom kornia.feature.laf import get_laf_centerfrom kornia.feature.steerers import DiscreteSteerer-from kornia.utils.helpers import is_mps_tensor_safefrom .adalam import get_adalam_default_config, match_adalamdiff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 84e962536..ff0b2fc18 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -24,7 +24,7 @@ from torch import nnfrom kornia.constants import pifrom kornia.filters import GaussianBlur2d, SpatialGradientfrom kornia.geometry.conversions import cart2pol-from kornia.utils import create_meshgrid+from kornia.geometry.grid import create_meshgrid# Precomputed coefficients for Von Mises kernel, given N and K(appa).sqrt2: float = 1.4142135623730951diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex a70a2750a..72dd98636 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -23,9 +23,9 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.utils import dataclass_to_dict, dict_to_dataclassfrom kornia.feature.sold2.structures import DetectorCfg, LineMatcherCfgfrom kornia.geometry.conversions import normalize_pixel_coordinates-from kornia.utils import dataclass_to_dict, dict_to_dataclassfrom .backbones import SOLD2Netfrom .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctionsdiff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.pyindex 915270ea3..80c9ac53c 100644--- a/kornia/feature/sold2/sold2_detector.py+++ b/kornia/feature/sold2/sold2_detector.py@@ -23,9 +23,9 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.utils import dataclass_to_dict, dict_to_dataclassfrom kornia.feature.sold2.structures import DetectorCfg, HeatMapRefineCfg, JunctionRefineCfg, LineDetectorCfgfrom kornia.geometry.bbox import nms-from kornia.utils import dataclass_to_dict, dict_to_dataclass, torch_meshgridfrom .backbones import SOLD2Net@@ -420,7 +420,7 @@ class LineSegmentDetectionModule:device=device,)- h1_grid, w1_grid, h2_grid, w2_grid = torch_meshgrid(+ h1_grid, w1_grid, h2_grid, w2_grid = torch.meshgrid([perturb_vec, perturb_vec, perturb_vec, perturb_vec], indexing="ij")diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex d1b43479f..8bdb07314 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -22,8 +22,8 @@ from typing import Anyimport torchfrom torch import nn+from kornia.core._compat import deprecatedfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE-from kornia.utils import deprecatedfrom .filter import filter2d, filter2d_separablefrom .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2ddiff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.pyindex 03b7982f4..4597dda44 100644--- a/kornia/filters/in_range.py+++ b/kornia/filters/in_range.py@@ -22,7 +22,7 @@ from typing import Any, Unionimport torchfrom torch import nn-from kornia.utils.image import perform_keep_shape_image+from kornia.image.utils import perform_keep_shape_image@perform_keep_shape_imagediff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 61d68e016..453c0be9e 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -22,8 +22,8 @@ from typing import Any, Optional, Unionimport torch+from kornia.core._compat import deprecatedfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE-from kornia.utils import deprecateddef _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, allow_even: bool = False) -> None:diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.pyindex e72663e18..1b67c6ebe 100644--- a/kornia/filters/kernels_geometry.py+++ b/kornia/filters/kernels_geometry.py@@ -21,8 +21,8 @@ import torchimport torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE+from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.transform import rotate, rotate3d-from kornia.utils import _extract_device_dtypefrom .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ksdiff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.pyindex 6a989107b..e8c3008c6 100644--- a/kornia/filters/otsu_thresholding.py+++ b/kornia/filters/otsu_thresholding.py@@ -22,8 +22,8 @@ from typing import Optional, Tupleimport torchfrom kornia.core.check import KORNIA_CHECK+from kornia.core.utils import _torch_histc_castfrom kornia.enhance.histogram import histogram as diff_histogram-from kornia.utils.helpers import _torch_histc_castclass OtsuThreshold(torch.nn.Module):diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.pyindex 2d87fa256..923ed1ac7 100644--- a/kornia/geometry/__init__.py+++ b/kornia/geometry/__init__.py@@ -26,10 +26,13 @@ from .camera import *from .conversions import *from .depth import *from .epipolar import *+from .grid import *from .homography import *from .liegroup import *from .linalg import *from .line import *+from .plane import *+from .pointcloud import *from .pose import *from .ransac import *from .solvers import *diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 08fc40ce7..4dc7a94db 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -22,9 +22,9 @@ from typing import Optional, Tuple, castimport torchfrom torch import Size+from kornia.core.ops import eye_likefrom kornia.geometry.bbox import validate_bboxfrom kornia.geometry.linalg import transform_points-from kornia.utils import eye_like__all__ = ["Boxes", "Boxes3D"]diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex c4bdc0bd2..51b5445ca 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -21,10 +21,10 @@ import torchfrom torch.linalg import qr as linalg_qrfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE+from kornia.core.ops import eye_like+from kornia.core.utils import _torch_linalg_svdvals, _torch_svd_castfrom kornia.geometry.conversions import convert_points_to_homogeneous, normalize_points_with_intrinsicsfrom kornia.geometry.linalg import transform_points-from kornia.utils import eye_like-from kornia.utils.helpers import _torch_linalg_svdvals, _torch_svd_castdef _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex 65bd3cd32..52bbf4eb4 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -23,9 +23,9 @@ import torchimport torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.geometry.grid import create_meshgridfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.transform import remap-from kornia.utils import create_meshgridfrom .distort import distort_points, tilt_projectiondiff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 2e5298993..e5bbdc5c9 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -20,9 +20,9 @@ from typing import Iterable, List, Unionimport torchfrom kornia.core.check import KORNIA_CHECK_SAME_DEVICE+from kornia.core.utils import _torch_inverse_castfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.linalg import inverse_transformation, transform_points-from kornia.utils.helpers import _torch_inverse_castclass PinholeCamera:diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex 768cb5375..2c079fafc 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -19,8 +19,8 @@ from typing import Anyimport torch+from kornia.geometry.grid import create_meshgridfrom kornia.geometry.linalg import transform_points-from kornia.utils.grid import create_meshgridclass StereoException(Exception):diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 3fe4c611c..861728a83 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -23,9 +23,9 @@ import torchimport torch.nn.functional as Ffrom kornia.constants import pi+from kornia.core._compat import deprecatedfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE-from kornia.utils import deprecated-from kornia.utils.helpers import _torch_inverse_cast+from kornia.core.utils import _torch_inverse_cast__all__ = ["ARKitQTVecs_to_ColmapQTVecs",diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex 1d9bcd92b..3cf28e7bf 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -28,7 +28,7 @@ from torch import nnimport kornia.core as kornia_opsfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.filters.sobel import spatial_gradient-from kornia.utils import create_meshgrid+from kornia.geometry.grid import create_meshgridfrom .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_pointsfrom .conversions import normalize_pixel_coordinates, normalize_points_with_intrinsicsdiff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex c0986cb30..c5579eeb9 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -22,9 +22,9 @@ from typing import Optional, Tupleimport torchfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE+from kornia.core.ops import eye_like, vec_like+from kornia.core.utils import _torch_solve_cast, _torch_svd_castfrom kornia.geometry import solvers-from kornia.utils import eye_like, vec_like-from kornia.utils.helpers import _torch_solve_cast, _torch_svd_castfrom .numeric import cross_product_matrix, matrix_cofactor_tensorfrom .projection import depth_from_point, projection_from_KRtdiff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex e758f0abe..2238d3099 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -22,10 +22,10 @@ from typing import Literal, Optional, Tupleimport torchfrom kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE+from kornia.core.utils import _torch_svd_cast, safe_inverse_with_maskfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.solvers import solve_cubic-from kornia.utils.helpers import _torch_svd_cast, safe_inverse_with_maskdef normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex d08ffbd20..a9202ae4f 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -24,8 +24,8 @@ import torch.nn.functional as Ffrom torch.linalg import qr as linalg_qrfrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.utils import eye_like, vec_like-from kornia.utils.helpers import _torch_svd_cast+from kornia.core.ops import eye_like, vec_like+from kornia.core.utils import _torch_svd_castfrom .numeric import cross_product_matrixdiff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.pyindex 6656b0206..61cf9b624 100644--- a/kornia/geometry/epipolar/triangulation.py+++ b/kornia/geometry/epipolar/triangulation.py@@ -20,8 +20,8 @@import torchfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.utils import _torch_svd_castfrom kornia.geometry.conversions import convert_points_from_homogeneous-from kornia.utils.helpers import _torch_svd_cast# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68diff --git a/kornia/utils/grid.py b/kornia/geometry/grid.pysimilarity index 95%rename from kornia/utils/grid.pyrename to kornia/geometry/grid.pyindex bb1d91217..5a338c709 100644--- a/kornia/utils/grid.py+++ b/kornia/geometry/grid.py@@ -15,12 +15,11 @@# limitations under the License.#+from typing import Optionalimport torch-from kornia.utils._compat import torch_meshgrid-def create_meshgrid(height: int,@@ -79,10 +78,10 @@ def create_meshgrid(# generate grid by stacking coordinates# TODO: torchscript doesn't like `torch_version_ge`# if torch_version_ge(1, 13, 0):- # x, y = torch_meshgrid([xs, ys], indexing="xy")+ # x, y = torch.meshgrid([xs, ys], indexing="xy")# return torch.stack([x, y], -1).unsqueeze(0) # 1xHxWx2# TODO: remove after we drop support of old versions- base_grid: torch.Tensor = torch.stack(torch_meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2+ base_grid: torch.Tensor = torch.stack(torch.meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2return base_grid.permute(1, 0, 2).unsqueeze(0) # 1xHxWx2@@ -123,5 +122,5 @@ def create_meshgrid3d(ys = (ys / (height - 1) - 0.5) * 2zs = (zs / (depth - 1) - 0.5) * 2# generate grid by stacking coordinates- base_grid = torch.stack(torch_meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3+ base_grid = torch.stack(torch.meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3return base_grid.permute(0, 2, 1, 3).unsqueeze(0) # 1xDxHxWx3diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex 713b92859..069f69c0c 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -21,8 +21,7 @@ from typing import Optional, Tupleimport torchfrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.utils import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask-from kornia.utils.helpers import _torch_svd_cast+from kornia.core.utils import _extract_device_dtype, _torch_svd_cast, safe_inverse_with_mask, safe_solve_with_maskfrom .conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom .epipolar import normalize_pointsdiff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex 7510f9d97..7d5530bea 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -24,9 +24,9 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+from kornia.core.utils import _torch_svd_castfrom kornia.geometry.linalg import batched_dot_productfrom kornia.geometry.plane import Hyperplane-from kornia.utils.helpers import _torch_svd_cast__all__ = ["ParametrizedLine", "fit_line"]diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.pyindex 9cac30490..5299c00db 100644--- a/kornia/geometry/plane.py+++ b/kornia/geometry/plane.py@@ -24,10 +24,10 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE-from kornia.core.tensor_wrapper import unwrap, wrap # type: ignore[attr-defined]+from kornia.core.tensor_wrapper import _unwrap, _wrap+from kornia.core.utils import _torch_svd_castfrom kornia.geometry.linalg import batched_dot_productfrom kornia.geometry.vector import Scalar, Vector3-from kornia.utils.helpers import _torch_svd_cast__all__ = ["Hyperplane", "fit_plane"]@@ -75,7 +75,7 @@ class Hyperplane(nn.Module):# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L145# TODO: testsdef signed_distance(self, p: Vector3) -> Scalar:- 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@@ -106,7 +106,7 @@ class Hyperplane(nn.Module):# TODO: implement `.unitOrthonormal`normal2d = normalized(p1 - p0)offset2d = -batched_dot_product(p0, normal2d)- return Hyperplane(wrap(normal2d, Vector3), wrap(offset2d, Scalar))+ return Hyperplane(_wrap(normal2d, Vector3), _wrap(offset2d, Scalar))# 3d caseKORNIA_CHECK_SHAPE(p0, ["*", "3"])KORNIA_CHECK(p0.shape == p1.shape)@@ -118,15 +118,15 @@ class Hyperplane(nn.Module):# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108def compute_normal_svd(v0: torch.Tensor, v1: torch.Tensor) -> "Vector3":# NOTE: for reason torch.TensorWrapper does not stack well- m = torch.stack((unwrap(v0), unwrap(v1)), -2) # Bx2x3+ m = torch.stack((_unwrap(v0), _unwrap(v1)), -2) # Bx2x3_, _, V = _torch_svd_cast(m) # kornia solution lies in the last row- return wrap(V[..., :, -1], Vector3) # Bx3+ return _wrap(V[..., :, -1], Vector3) # Bx3normal_mask = norm <= v0.norm(-1) * v1.norm(-1) * 1e-6normal = torch.where(normal_mask, compute_normal_svd(v0, v1).data, normal / (norm + 1e-6))offset = -batched_dot_product(p0, normal)- return Hyperplane(wrap(normal, Vector3), wrap(offset, Scalar))+ return Hyperplane(_wrap(normal, Vector3), _wrap(offset, Scalar))# TODO: factor to avoid duplicated from line.pydiff --git a/kornia/utils/pointcloud_io.py b/kornia/geometry/pointcloud.pysimilarity index 99%rename from kornia/utils/pointcloud_io.pyrename to kornia/geometry/pointcloud.pyindex c2baf61bd..7da0bd86d 100644--- a/kornia/utils/pointcloud_io.py+++ b/kornia/geometry/pointcloud.py@@ -15,6 +15,7 @@# limitations under the License.#+import osimport torchdiff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.pyindex 017727682..699933763 100644--- a/kornia/geometry/subpix/dsnt.py+++ b/kornia/geometry/subpix/dsnt.py@@ -28,7 +28,7 @@ import torchimport torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE-from kornia.utils.grid import create_meshgrid+from kornia.geometry.grid import create_meshgriddef _validate_batched_image_tensor_input(tensor: torch.Tensor) -> None:diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex dd960e2c6..d7d4e20c6 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -23,11 +23,11 @@ import torchimport torch.nn.functional as Ffrom torch import nn+from kornia.core._compat import torch_version_ge+from kornia.core.utils import safe_solve_with_maskfrom kornia.filters.sobel import spatial_gradient3dfrom kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3d-from kornia.utils import create_meshgrid, create_meshgrid3d-from kornia.utils._compat import torch_version_ge-from kornia.utils.helpers import safe_solve_with_mask+from kornia.geometry.grid import create_meshgrid, create_meshgrid3dfrom .dsnt import spatial_expectation2d, spatial_softmax2dfrom .nms import nms3ddiff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex a737325ea..6c9619a66 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -21,10 +21,10 @@ from typing import Optional, Tuple, Unionimport torchfrom torch import nn+from kornia.core.ops import eye_like+from kornia.core.utils import _extract_device_dtypefrom kornia.filters import gaussian_blur2d-from kornia.utils import _extract_device_dtype-from kornia.utils.image import perform_keep_shape_image-from kornia.utils.misc import eye_like+from kornia.image.utils import perform_keep_shape_imagefrom .imgwarp import get_affine_matrix2d, get_projective_transform, get_rotation_matrix2d, warp_affine, warp_affine3ddiff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.pyindex 17f08b8c3..8702c9f25 100644--- a/kornia/geometry/transform/elastic_transform.py+++ b/kornia/geometry/transform/elastic_transform.py@@ -23,7 +23,7 @@ import torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.filters import filter2dfrom kornia.filters.kernels import get_gaussian_kernel2d-from kornia.utils import create_meshgrid+from kornia.geometry.grid import create_meshgrid__all__ = ["elastic_transform2d"]diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.pyindex b6329c2f0..63b78cb7a 100644--- a/kornia/geometry/transform/homography_warper.py+++ b/kornia/geometry/transform/homography_warper.py@@ -24,7 +24,7 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.utils import create_meshgrid+from kornia.geometry.grid import create_meshgridfrom .imgwarp import homography_warp, warp_griddiff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex d76c2812d..4fc6bcf62 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -23,6 +23,8 @@ import torchimport torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE+from kornia.core.ops import eye_like+from kornia.core.utils import _torch_inverse_cast, _torch_solve_castfrom kornia.geometry.conversions import (angle_to_rotation_matrix,axis_angle_to_rotation_matrix,@@ -32,9 +34,8 @@ from kornia.geometry.conversions import (normalize_homography3d,normalize_pixel_coordinates,)+from kornia.geometry.grid import create_meshgrid, create_meshgrid3dfrom kornia.geometry.linalg import transform_points-from kornia.utils import create_meshgrid, create_meshgrid3d, eye_like-from kornia.utils.helpers import _torch_inverse_cast, _torch_solve_cast__all__ = ["get_affine_matrix2d",@@ -526,7 +527,7 @@ def remap(Example:>>> import torch- >>> from kornia.utils import create_meshgrid+ >>> from kornia.geometry import create_meshgrid>>> grid = create_meshgrid(2, 2, False) # 1x2x2x2>>> grid += 1 # apply offset in both directions>>> input = torch.ones(1, 1, 2, 2)@@ -535,7 +536,7 @@ def remap([0., 0.]]]]).. note::- This function is often used in conjunction with :func:`kornia.utils.create_meshgrid`.+ This function is often used in conjunction with :func:`kornia.geometry.create_meshgrid`."""KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.pyindex 5d1f0f428..041efff0a 100644--- a/kornia/geometry/transform/thin_plate_spline.py+++ b/kornia/geometry/transform/thin_plate_spline.py@@ -20,8 +20,8 @@ from __future__ import annotationsimport torchfrom torch import nn-from kornia.utils import create_meshgrid-from kornia.utils.helpers import _torch_solve_cast+from kornia.core.utils import _torch_solve_cast+from kornia.geometry.grid import create_meshgrid__all__ = ["get_tps_transform", "warp_image_tps", "warp_points_tps"]diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.pyindex fdb308e5d..45c744270 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -21,7 +21,7 @@ import torchimport torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK-from kornia.core.tensor_wrapper import TensorWrapper, wrap # type: ignore[attr-defined]+from kornia.core.tensor_wrapper import TensorWrapper, _wrap # type: ignore[attr-defined]from kornia.geometry.linalg import batched_dot_product, batched_squared_norm__all__ = ["Scalar", "Vector2", "Vector3"]@@ -110,12 +110,12 @@ class Vector3(TensorWrapper):dtype: Optional[torch.dtype] = None,) -> "Vector3":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)+ return _wrap(torch.as_tensor((x, y, z), device=device, dtype=dtype), Vector3)# TODO: this is totally insane ...tensors: Tuple[torch.Tensor, ...] = (x, cast(torch.Tensor, y), cast(torch.Tensor, z))- return wrap(torch.stack(tensors, -1), Vector3)+ return _wrap(torch.stack(tensors, -1), Vector3)class Vector2(TensorWrapper):@@ -168,12 +168,12 @@ class Vector2(TensorWrapper):dtype: Optional[torch.dtype] = None,) -> "Vector2":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)+ return _wrap(torch.as_tensor((x, y), device=device, dtype=dtype), Vector2)# TODO: this is totally insane ...tensors: Tuple[torch.Tensor, ...] = (x, cast(torch.Tensor, y))- return wrap(torch.stack(tensors, -1), Vector2)+ return _wrap(torch.stack(tensors, -1), Vector2)Vec3 = Vector3diff --git a/kornia/image/__init__.py b/kornia/image/__init__.pyindex 2dd22c4f9..002ba3b54 100644--- a/kornia/image/__init__.py+++ b/kornia/image/__init__.py@@ -22,6 +22,36 @@ and channel order definitions."""from .base import ChannelsOrder, ImageLayout, ImageSize, PixelFormat+from .draw import draw_convex_polygon, draw_line, draw_point2d, draw_rectanglefrom .image import Image+from .image_print import image_to_string, print_image+from .utils import (+ ImageToTensor,+ image_list_to_tensor,+ image_to_tensor,+ make_grid,+ perform_keep_shape_image,+ perform_keep_shape_video,+ tensor_to_image,+)-__all__ = ["ChannelsOrder", "Image", "ImageLayout", "ImageSize", "PixelFormat"]+__all__ = [+ "ChannelsOrder",+ "Image",+ "ImageLayout",+ "ImageSize",+ "ImageToTensor",+ "PixelFormat",+ "draw_convex_polygon",+ "draw_line",+ "draw_point2d",+ "draw_rectangle",+ "image_list_to_tensor",+ "image_to_string",+ "image_to_tensor",+ "make_grid",+ "perform_keep_shape_image",+ "perform_keep_shape_video",+ "print_image",+ "tensor_to_image",+]diff --git a/kornia/utils/draw.py b/kornia/image/draw.pysimilarity index 100%rename from kornia/utils/draw.pyrename to kornia/image/draw.pydiff --git a/kornia/image/image.py b/kornia/image/image.pyindex 469a5e709..d358a72b5 100644--- a/kornia/image/image.py+++ b/kornia/image/image.py@@ -26,8 +26,8 @@ from torch.utils.dlpack import from_dlpack, to_dlpackimport kornia.colorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat+from kornia.image.image_print import image_to_stringfrom kornia.io.io import ImageLoadType, load_image, write_image-from kornia.utils.image_print import image_to_string# placeholder for numpynp_ndarray = Anydiff --git a/kornia/utils/image_print.py b/kornia/image/image_print.pysimilarity index 99%rename from kornia/utils/image_print.pyrename to kornia/image/image_print.pyindex 299e60ea4..54d21d28a 100644--- a/kornia/utils/image_print.py+++ b/kornia/image/image_print.py@@ -15,6 +15,7 @@# limitations under the License.#+"""Convert an image torch.tensor to an ANSI text string (xterm-256color).Nice long listing of all 256 colors and their codes.@@ -30,7 +31,6 @@ from torch import float16, float32, float64import korniafrom kornia.core.check import KORNIA_CHECK_IS_IMAGE, KORNIA_CHECK_SHAPE-from kornia.io import ImageLoadType# color look-up table# 8-bit, RGB hex@@ -410,6 +410,8 @@ def print_image(image: Union[str, torch.Tensor], max_width: int = 96) -> None:"""if isinstance(image, str):+ from kornia.io import ImageLoadType # pylint: disable=C0415+img = kornia.io.load_image(image, ImageLoadType.RGB8)elif isinstance(image, torch.Tensor):img = imagediff --git a/kornia/utils/image.py b/kornia/image/utils.pysimilarity index 99%rename from kornia/utils/image.pyrename to kornia/image/utils.pyindex f58863c38..9bc180a93 100644--- a/kornia/utils/image.py+++ b/kornia/image/utils.py@@ -15,6 +15,7 @@# limitations under the License.#+from functools import wrapsfrom typing import Any, Callable, List, Optional@@ -257,7 +258,7 @@ def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int =B, C, H, W = tensor.shapeif n_row is None:- n_row = int(torch.sqrt(tensor(B, dtype=torch.float32)).ceil().item())+ n_row = int(torch.sqrt(torch.tensor(B, dtype=torch.float32)).ceil().item())n_col = (B + n_row - 1) // n_rowpadded_H = H + paddingdiff --git a/kornia/io/io.py b/kornia/io/io.pyindex cf04068ba..16681f13b 100644--- a/kornia/io/io.py+++ b/kornia/io/io.py@@ -26,7 +26,7 @@ import torchimport korniafrom kornia.core.check import KORNIA_CHECK-from kornia.utils import image_to_tensor, tensor_to_image+from kornia.image.utils import image_to_tensor, tensor_to_imageclass ImageLoadType(Enum):diff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex 0aa350bd7..76d2122a5 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -25,7 +25,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSORfrom kornia.losses._utils import mask_ignore_pixels-from kornia.utils.one_hot import one_hot+from kornia.losses.one_hot import one_hot# based on:# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.pydiff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 53dd978bd..d7df190b1 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -24,7 +24,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.losses._utils import mask_ignore_pixels-from kornia.utils.one_hot import one_hot+from kornia.losses.one_hot import one_hot# based on:# https://github.com/zhezh/focalloss/blob/master/focalloss.pydiff --git a/kornia/utils/one_hot.py b/kornia/losses/one_hot.pysimilarity index 62%rename from kornia/utils/one_hot.pyrename to kornia/losses/one_hot.pyindex 4497085fc..e465431c6 100644--- a/kornia/utils/one_hot.py+++ b/kornia/losses/one_hot.py@@ -16,6 +16,9 @@#import torch+import torch.nn.functional as F++from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSORdef one_hot(@@ -47,15 +50,23 @@ def one_hot([1.0000e+00, 1.0000e-06]]]])"""- if not isinstance(labels, torch.Tensor):- raise TypeError(f"Input labels type is not a torch.Tensor. Got {type(labels)}")+ KORNIA_CHECK_IS_TENSOR(labels, "Input labels must be a torch.Tensor")+ KORNIA_CHECK(labels.dtype == torch.int64, f"labels must be of dtype torch.int64. Got: {labels.dtype}")+ KORNIA_CHECK(num_classes >= 1, f"The number of classes must be >= 1. Got: {num_classes}")++ # Use PyTorch's built-in one_hot function+ one_hot_tensor = F.one_hot(labels, num_classes=num_classes)- if not labels.dtype == torch.int64:- raise ValueError(f"labels must be of the same dtype torch.int64. Got: {labels.dtype}")+ # PyTorch's one_hot adds the class dimension at the end: (*, num_classes)+ # We need it at position 1: (N, C, *)+ # Permute: move the last dimension (num_classes) to position 1+ ndim = labels.ndim+ permute_dims = [0] + [ndim] + list(range(1, ndim))+ one_hot_tensor = one_hot_tensor.permute(*permute_dims)- if num_classes < 1:- raise ValueError(f"The number of classes must be bigger than one. Got: {num_classes}")+ # Convert to desired dtype and device, then apply eps for numerical stability+ one_hot_tensor = one_hot_tensor.to(dtype=dtype, device=device)+ # Apply eps: multiply by (1-eps) and add eps to all elements+ one_hot_tensor = one_hot_tensor * (1.0 - eps) + eps- shape = labels.shape- one_hot = torch.full((shape[0], num_classes) + shape[1:], eps, device=device, dtype=dtype)- return one_hot.scatter_(1, labels.unsqueeze(1), 1.0)+ return one_hot_tensordiff --git a/kornia/models/base.py b/kornia/models/base.pyindex 61f02d1c1..dbdb552fa 100644--- a/kornia/models/base.py+++ b/kornia/models/base.py@@ -27,8 +27,8 @@ import torchfrom torch import nnfrom kornia.core.external import PILImage as Image+from kornia.image.utils import tensor_to_imagefrom kornia.io import write_image-from kornia.utils.image import tensor_to_imagelogger = logging.getLogger(__name__)diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.pyindex 0ee9b25d3..125530ae7 100644--- a/kornia/models/depth_estimation/depth_anything.py+++ b/kornia/models/depth_estimation/depth_anything.py@@ -51,13 +51,10 @@ class DepthAnythingONNXBuilder:The directory where the model should be cached.Returns:- str: The name of the output ONNX file.+ DepthEstimation: The depth estimation model.- .. code-block:: python-- images = kornia.utils.sample.get_sample_images()- model = DepthAnythingONNXBuilder.build()- model.save(images)+ Note:+ To use this model, load an image tensor (shape: ``(1, C, H, W)``) and call ``model.save(image)``."""if model_name not in [diff --git a/kornia/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.pyindex 7c86b2845..cb9f5bbc6 100644--- a/kornia/models/efficient_vit/nn/ops.py+++ b/kornia/models/efficient_vit/nn/ops.py@@ -29,7 +29,6 @@ from torch import nnfrom kornia.models.efficient_vit.nn.act import build_actfrom kornia.models.efficient_vit.nn.norm import build_normfrom kornia.models.efficient_vit.utils import get_same_padding, val2tuple-from kornia.utils._compat import autocast__all__ = ["ConvLayer",@@ -430,7 +429,7 @@ class LiteMLA(nn.Module):total_dim * (1 + len(scales)), out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1])- @autocast(enabled=False)+ @torch.amp.autocast(device_type="cuda", enabled=False)def relu_linear_att(self, qkv: torch.Tensor) -> torch.Tensor:B, _, H, W = list(qkv.size())diff --git a/kornia/models/rt_detr/architecture/hybrid_encoder.py b/kornia/models/rt_detr/architecture/hybrid_encoder.pyindex c3908f434..13fd7d075 100644--- a/kornia/models/rt_detr/architecture/hybrid_encoder.py+++ b/kornia/models/rt_detr/architecture/hybrid_encoder.py@@ -31,7 +31,6 @@ from torch import nnfrom torch.nn.utils.fusion import fuse_conv_bn_weightsfrom kornia.models.common import ConvNormAct-from kornia.utils._compat import torch_meshgridclass RepVggBlock(nn.Module):@@ -181,7 +180,7 @@ class AIFI(nn.Module):"""xs = torch.arange(w, device=device, dtype=dtype)ys = torch.arange(h, device=device, dtype=dtype)- grid_x, grid_y = torch_meshgrid([xs, ys], indexing="ij")+ grid_x, grid_y = torch.meshgrid([xs, ys], indexing="ij")pos_dim = embed_dim // 4omega = torch.arange(pos_dim, device=device, dtype=dtype) / pos_dimdiff --git a/kornia/models/rt_detr/architecture/rtdetr_head.py b/kornia/models/rt_detr/architecture/rtdetr_head.pyindex 8ab3726c7..e45e29a6f 100644--- a/kornia/models/rt_detr/architecture/rtdetr_head.py+++ b/kornia/models/rt_detr/architecture/rtdetr_head.py@@ -27,7 +27,6 @@ import torchfrom torch import nnfrom kornia.models.common import MLP, ConvNormAct-from kornia.utils._compat import torch_meshgriddef _inverse_sigmoid(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor:@@ -476,8 +475,8 @@ class RTDETRHead(nn.Module):anchors_list: list[torch.Tensor] = []for i, (h, w) in enumerate(spatial_shapes):- # TODO: fix later kornia.utils.create_meshgrid()- grid_y, grid_x = torch_meshgrid(+ # TODO: fix later kornia.geometry.create_meshgrid()+ grid_y, grid_x = torch.meshgrid([torch.arange(h, device=device, dtype=dtype), torch.arange(w, device=device, dtype=dtype)],indexing="ij",)diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.pyindex ddef29384..1f79a6484 100644--- a/kornia/models/small_sr.py+++ b/kornia/models/small_sr.py@@ -20,7 +20,7 @@ from torch import nnfrom kornia.color.ycbcr import RgbToYcbcr, YcbcrToRgbfrom kornia.config import kornia_config-from kornia.utils.download import CachedDownloader+from kornia.onnx.download import CachedDownloaderurl = "https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch100-44c6958e.pth"diff --git a/kornia/utils/download.py b/kornia/onnx/download.pysimilarity index 100%rename from kornia/utils/download.pyrename to kornia/onnx/download.pydiff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.pyindex 12b9a360d..7a318db84 100644--- a/kornia/onnx/utils.py+++ b/kornia/onnx/utils.py@@ -27,7 +27,7 @@ import korniafrom kornia.config import kornia_configfrom kornia.core.external import numpy as npfrom kornia.core.external import onnx, requests-from kornia.utils.download import CachedDownloader+from kornia.onnx.download import CachedDownloader__all__ = ["ONNXLoader", "add_metadata", "io_name_conversion"]diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex 377644fb4..f477e4614 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -17,75 +17,195 @@"""Utils submodule for Kornia.-This package provides utility functions and helpers for image processing, device management, data conversion, and more.+This module has been deprecated. Functions have been moved to their respective modules.+Import from the new locations instead (e.g., `kornia.image.draw_line` instead of `kornia.utils.draw_line`)."""-from ._compat import torch_meshgrid-from .download import CachedDownloader-from .draw import draw_convex_polygon, draw_line, draw_point2d, draw_rectangle-from .grid import create_meshgrid, create_meshgrid3d-from .helpers import (- _extract_device_dtype,- dataclass_to_dict,- deprecated,- dict_to_dataclass,- get_cuda_device_if_available,- get_cuda_or_mps_device_if_available,- get_mps_device_if_available,- is_autocast_enabled,- is_mps_tensor_safe,- map_location_to_cpu,- safe_inverse_with_mask,- safe_solve_with_mask,- xla_is_available,-)-from .image import ImageToTensor, image_list_to_tensor, image_to_tensor, tensor_to_image-from .image_print import image_to_string, print_image-from .memory import batched_forward-from .misc import (- differentiable_clipping,- differentiable_polynomial_floor,- differentiable_polynomial_rounding,- eye_like,- vec_like,-)-from .one_hot import one_hot-from .pointcloud_io import load_pointcloud_ply, save_pointcloud_ply-from .sample import get_sample_images+from typing import Any++from kornia.core._compat import deprecated+from kornia.geometry import (+ create_meshgrid as _create_meshgrid,+)+from kornia.geometry import (+ create_meshgrid3d as _create_meshgrid3d,+)+from kornia.geometry import (+ load_pointcloud_ply as _load_pointcloud_ply,+)+from kornia.geometry import (+ save_pointcloud_ply as _save_pointcloud_ply,+)+from kornia.image import (+ draw_convex_polygon as _draw_convex_polygon,+)+from kornia.image import (+ draw_line as _draw_line,+)+from kornia.image import (+ draw_point2d as _draw_point2d,+)+from kornia.image import (+ draw_rectangle as _draw_rectangle,+)+from kornia.image import (+ image_to_string as _image_to_string,+)+from kornia.image import (+ image_to_tensor as _image_to_tensor,+)+from kornia.image import (+ print_image as _print_image,+)+from kornia.image import (+ tensor_to_image as _tensor_to_image,+)+from kornia.losses import one_hot as _one_hot+++# Re-export with deprecation warnings+@deprecated(+ replace_with="kornia.geometry.create_meshgrid",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",+)+def create_meshgrid(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""+ return _create_meshgrid(*args, **kwargs)+++@deprecated(+ replace_with="kornia.geometry.create_meshgrid3d",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",+)+def create_meshgrid3d(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.create_meshgrid3d` instead."""+ return _create_meshgrid3d(*args, **kwargs)+++@deprecated(+ replace_with="kornia.geometry.load_pointcloud_ply",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",+)+def load_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.load_pointcloud_ply` instead."""+ return _load_pointcloud_ply(*args, **kwargs)+++@deprecated(+ replace_with="kornia.geometry.save_pointcloud_ply",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",+)+def save_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.geometry.save_pointcloud_ply` instead."""+ return _save_pointcloud_ply(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_line",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def draw_line(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_line` instead."""+ return _draw_line(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_rectangle",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def draw_rectangle(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_rectangle` instead."""+ return _draw_rectangle(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_point2d",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def draw_point2d(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_point2d` instead."""+ return _draw_point2d(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.draw_convex_polygon",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def draw_convex_polygon(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.draw_convex_polygon` instead."""+ return _draw_convex_polygon(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.image_to_string",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def image_to_string(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.image_to_string` instead."""+ return _image_to_string(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.print_image",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def print_image(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.print_image` instead."""+ return _print_image(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.image_to_tensor",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def image_to_tensor(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.image_to_tensor` instead."""+ return _image_to_tensor(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.tensor_to_image",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def tensor_to_image(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.tensor_to_image` instead."""+ return _tensor_to_image(*args, **kwargs)+++@deprecated(+ replace_with="kornia.losses.one_hot",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.losses` instead.",+)+def one_hot(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.losses.one_hot` instead."""+ return _one_hot(*args, **kwargs)+__all__ = [- "CachedDownloader",- "ImageToTensor",- "_extract_device_dtype",- "batched_forward","create_meshgrid","create_meshgrid3d",- "dataclass_to_dict",- "deprecated",- "dict_to_dataclass","draw_convex_polygon","draw_line","draw_point2d","draw_rectangle",- "eye_like",- "get_cuda_device_if_available",- "get_cuda_or_mps_device_if_available",- "get_mps_device_if_available",- "get_sample_images",- "image_list_to_tensor","image_to_string","image_to_tensor",- "is_autocast_enabled",- "is_mps_tensor_safe","load_pointcloud_ply",- "map_location_to_cpu","one_hot","print_image",- "safe_inverse_with_mask",- "safe_solve_with_mask","save_pointcloud_ply","tensor_to_image",- "torch_meshgrid",- "vec_like",- "xla_is_available",]diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.pydeleted file mode 100644index fab710c3f..000000000--- a/kornia/utils/_compat.py+++ /dev/null@@ -1,87 +0,0 @@-# 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.-#--from typing import TYPE_CHECKING, Any, Callable, ContextManager, List, Optional, Tuple, TypeVar--import torch-from packaging import version-from torch import Tensor---def torch_version() -> str:- """Parse the `torch.__version__` variable and removes +cu*/cpu."""- return torch.__version__.partition("+")[0]---def torch_version_lt(major: int, minor: int, patch: int) -> bool:- _version = version.parse(torch_version())- return _version < version.parse(f"{major}.{minor}.{patch}")---def torch_version_le(major: int, minor: int, patch: int) -> bool:- _version = version.parse(torch_version())- return _version <= version.parse(f"{major}.{minor}.{patch}")---def torch_version_ge(major: int, minor: int, patch: Optional[int] = None) -> bool:- _version = version.parse(torch_version())- if patch is None:- return _version >= version.parse(f"{major}.{minor}")- else:- return _version >= version.parse(f"{major}.{minor}.{patch}")---if TYPE_CHECKING:- # TODO: remove this branch when kornia relies on torch >= 1.10.0- def torch_meshgrid(tensors: List[Tensor], indexing: Optional[str] = None) -> Tuple[Tensor, ...]: ...--elif torch_version_ge(1, 10, 0):-- def torch_meshgrid(tensors: List[Tensor], indexing: str):- return torch.meshgrid(tensors, indexing=indexing)--else:- # TODO: remove this branch when kornia relies on torch >= 1.10.0- def torch_meshgrid(tensors: List[Tensor], indexing: str):- return torch.meshgrid(tensors)---if TYPE_CHECKING:- # TODO: remove this branch when kornia relies on torch >= 1.10.0- _T = TypeVar("_T")- torch_inference_mode: Callable[..., ContextManager[_T]]-elif torch_version_ge(1, 10, 0):- torch_inference_mode = torch.inference_mode-else:- # TODO: remove this branch when kornia relies on torch >= 1.10.0- torch_inference_mode = torch.no_grad--if TYPE_CHECKING: # TODO (@johnnv1): remove this branch when bump the pytorch CI to support torch 2.4- custom_fwd: Callable[..., Any]- autocast: Callable[..., Any]-elif torch_version_ge(2, 4):- from functools import partial-- from torch.amp import autocast as _autocast- from torch.amp import custom_fwd as _custom_fwd-- custom_fwd = partial(_custom_fwd, device_type="cuda")- autocast = partial(_autocast, "cuda")--else:- custom_fwd = torch.cuda.amp.custom_fwd- autocast = torch.cuda.amp.autocastdiff --git a/kornia/utils/memory.py b/kornia/utils/memory.pydeleted file mode 100644index c555f63ea..000000000--- a/kornia/utils/memory.py+++ /dev/null@@ -1,75 +0,0 @@-# 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.-#--from typing import Any, Dict, Union--import torch-from torch import nn---def batched_forward(- model: nn.Module,- data: torch.Tensor,- device: Union[str, torch.device, None],- batch_size: int = 128,- **kwargs: Dict[str, Any],-) -> torch.Tensor:- r"""Run the forward in micro-batches.-- When the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.- In the end, it transfers the output to the device of the input data tensor.- E.g. running HardNet on 8000x1x32x32 tensor.-- Args:- model: Any torch model, which outputs a single tensor as an output.- data: Input data of Bx(Any) shape.- device: which device should we run on.- batch_size: "micro-batch" size.- **kwargs: any other arguments, which accepts model.-- Returns:- output of the model.-- Example:- >>> patches = torch.rand(8000, 1, 32, 32)- >>> sift = kornia.feature.SIFTDescriptor(32)- >>> desc_batched = batched_forward(sift, patches, torch.device('cpu'), 128)- >>> desc = sift(patches)- >>> assert torch.allclose(desc, desc_batched)-- """- model_dev = model.to(device)- B: int = len(data)- bs: int = batch_size- if B > batch_size:- out_list = []- n_batches = int(B // bs + 1)- for batch_idx in range(n_batches):- st = batch_idx * bs- if batch_idx == n_batches - 1:- if (batch_idx + 1) * bs > B:- end = B- else:- end = (batch_idx + 1) * bs- else:- end = (batch_idx + 1) * bs- if st >= end:- continue- out_list.append(model_dev(data[st:end].to(device), **kwargs))- out = torch.cat(out_list, 0)- return out.to(data.device)- return model(data, **kwargs)diff --git a/kornia/utils/sample.py b/kornia/utils/sample.pydeleted file mode 100644index b0b855a1d..000000000--- a/kornia/utils/sample.py+++ /dev/null@@ -1,116 +0,0 @@-# 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.-#-"""Utilities for downloading and loading sample images."""--import logging-import os-from typing import Any, List, Optional, Tuple, Union--import torch--import kornia-from kornia.core.external import PILImage as Image-from kornia.core.external import requests-from kornia.io import load_image--__all__ = [- "get_sample_images",-]--IMAGE_URLS: List[str] = [- "https://raw.githubusercontent.com/kornia/data/main/panda.jpg",- "https://raw.githubusercontent.com/kornia/data/main/simba.png",- "https://raw.githubusercontent.com/kornia/data/main/girona.png",- "https://raw.githubusercontent.com/kornia/data/main/baby_giraffe.png",- "https://raw.githubusercontent.com/kornia/data/main/persistencia_memoria.jpg",- "https://raw.githubusercontent.com/kornia/data/main/delorean.png",-]---def download_image(url: str, save_to: str) -> None:- """Download an image from a given URL and save it to a specified file path.-- Args:- url: The URL of the image to download.- save_to: The file path where the downloaded image will be saved.-- """- im = Image.open(requests.get(url, stream=True, timeout=30).raw) # type:ignore- im.save(save_to)---def get_sample_images(- resize: Optional[Tuple[int, int]] = None,- paths: List[str] = IMAGE_URLS,- download: bool = True,- cache_dir: Optional[str] = None,- as_list: Optional[bool] = None,- divisible_factor: Optional[int] = None,- **kwargs: Any,-) -> Union[torch.Tensor, List[torch.Tensor]]:- """Load multiple images from the given URLs.-- Optionally download them, resize them if specified, and return them as a batch of tensors or a list of tensors.-- Args:- paths: A list of path or URL from which to load or download images.- Defaults to a pre-defined constant `IMAGE_URLS` if not provided.- resize: Optional target size for resizing all images as a tuple (height, width).- If not provided, the images will not be resized, and their original sizes will be retained.- download: Whether to download the images if they are not already cached. Defaults to True.- cache_dir: The directory where the downloaded images will be cached.- Defaults to ".kornia_hub/images".- as_list: if to keep the output as a list. If None and `resize` is None, the output will be a list.- If None and `resize` is not None, the output will be a single tensor.- divisible_factor:- If not None, the images will be resized to the nearest multiple of `divisible_factor`.- **kwargs: Additional keyword arguments to pass to `kornia.geometry.resize`.-- Returns:- torch.Tensor | list[torch.Tensor]:- If `resize` is provided, returns a single stacked tensor with shape (B, C, H, W).- Otherwise, returns a list of tensors, each with its original shape (C, H, W).-- """- if cache_dir is None:- cache_dir = ".kornia_hub/images"- os.makedirs(cache_dir, exist_ok=True)- tensors = []- for path in paths:- if path.startswith("http"):- name = os.path.basename(path)- fname = os.path.join(cache_dir, name)- if not os.path.exists(fname) and download:- logging.info(f"Downloading `{path}` to `{fname}`.")- download_image(path, fname)- elif not os.path.exists(fname) and not download:- logging.error(- f"Image `{path}` not found at `{fname}`. You may want to set `download=True` to download it."- )- else:- fname = path- img_tensor = load_image(fname)- if resize is not None:- img_tensor = kornia.geometry.resize(img_tensor, resize, **kwargs)- if divisible_factor is not None:- img_tensor = kornia.geometry.transform.resize_to_be_divisible(img_tensor, divisible_factor, **kwargs)- tensors.append(img_tensor)-- if not as_list and resize is not None:- return torch.stack(tensors)-- return tensorsdiff --git a/testing/geometry/create.py b/testing/geometry/create.pyindex 46d3bd9fb..c70e1323b 100644--- a/testing/geometry/create.py+++ b/testing/geometry/create.py@@ -22,7 +22,7 @@ from typing import Optional, Unionimport torchimport kornia.geometry.epipolar as epi-from kornia.utils.misc import eye_like+from kornia.core.ops import eye_likedef create_random_homography(data: torch.Tensor, eye_size: int, std_val: float = 1e-3) -> torch.Tensor:diff --git a/tests/augmentation/_3d/test_random_equalize_3d.py b/tests/augmentation/_3d/test_random_equalize_3d.pyindex f7d49683c..a62a947b9 100644--- a/tests/augmentation/_3d/test_random_equalize_3d.py+++ b/tests/augmentation/_3d/test_random_equalize_3d.py@@ -48,7 +48,7 @@ class TestRandomEqualize3D(BaseTester):)expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected, device=device, dtype=dtype)- identity = kornia.eye_like(4, expected)+ identity = kornia.core.ops.eye_like(4, expected)self.assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)self.assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)@@ -66,7 +66,7 @@ class TestRandomEqualize3D(BaseTester):row_expected = torch.tensor([0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000])expected = self.build_input(channels, depth, height, width, bs, row=row_expected, device=device, dtype=dtype)- identity = kornia.eye_like(4, expected) # 2 x 4 x 4+ identity = kornia.core.ops.eye_like(4, expected) # 2 x 4 x 4self.assert_close(f(inputs3d), expected, rtol=1e-4, atol=1e-4)self.assert_close(f.transform_matrix, identity, rtol=1e-4, atol=1e-4)diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 6ffe546f5..7e66aecef 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -77,10 +77,9 @@ from kornia.augmentation import ()from kornia.augmentation._2d.base import AugmentationBase2Dfrom kornia.constants import Resample, pi-from kornia.geometry import transform_points-from kornia.utils import create_meshgrid-from kornia.utils._compat import torch_version, torch_version_le-from kornia.utils.helpers import _torch_inverse_cast+from kornia.core._compat import torch_version, torch_version_le+from kornia.core.utils import _torch_inverse_cast+from kornia.geometry import create_meshgrid, transform_pointsfrom testing.augmentation.datasets import DummyMPDatasetfrom testing.base import BaseTester@@ -295,7 +294,7 @@ class CommonTests(BaseTester):output = augmentation(input_tensor)transform = augmentation.transform_matrix- if (transform == kornia.eye_like(3, transform)).all():+ if (transform == kornia.core.ops.eye_like(3, transform)).all():pytest.skip("Test not relevant for intensity augmentations.")indices = create_meshgrid(@@ -404,7 +403,7 @@ class TestRandomEqualizeAlternative(CommonTests):)expected_output = expected_output.repeat(2, 3, 20, 1)- expected_transformation = kornia.eye_like(3, input_tensor)+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)parameters = {}self._test_random_p_1_implementation(input_tensor=input_tensor,@@ -685,7 +684,7 @@ class TestRandomRotationAlternative(CommonTests):dtype=self.dtype,).repeat((2, 1, 1, 1))expected_output = input_tensor- expected_transformation = kornia.eye_like(3, input_tensor)+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)parameters = {"degrees": (-360.0, -360.0), "align_corners": True}self._test_random_p_1_implementation(input_tensor=input_tensor,@@ -778,7 +777,7 @@ class TestRandomRotation90(CommonTests):dtype=self.dtype,).repeat((2, 1, 1, 1))expected_output = input_tensor- expected_transformation = kornia.eye_like(3, input_tensor)+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)parameters = {"times": (0, 0), "align_corners": True}self._test_random_p_1_implementation(input_tensor=input_tensor,@@ -851,7 +850,7 @@ class TestRandomGrayscaleAlternative(CommonTests):.repeat(1, 3, 1, 1))- expected_transformation = kornia.eye_like(3, input_tensor)+ expected_transformation = kornia.core.ops.eye_like(3, input_tensor)parameters = {}self._test_random_p_1_implementation(input_tensor=input_tensor,@@ -3813,7 +3812,7 @@ class TestRandomEqualize(BaseTester):])expected = self.build_input(channels, height, width, bs=1, row=row_expected, device=device, dtype=dtype)- identity = kornia.eye_like(3, expected) # 3 x 3+ identity = kornia.core.ops.eye_like(3, expected) # 3 x 3self.assert_close(f(inputs), expected, low_tolerance=True)self.assert_close(f.transform_matrix, identity, low_tolerance=True)@@ -3854,7 +3853,7 @@ class TestRandomEqualize(BaseTester):)expected = self.build_input(channels, height, width, bs, row=row_expected, device=device, dtype=dtype)- identity = kornia.eye_like(3, expected) # 2 x 3 x 3+ identity = kornia.core.ops.eye_like(3, expected) # 2 x 3 x 3self.assert_close(f(inputs), expected, low_tolerance=True)self.assert_close(f.transform_matrix, identity, low_tolerance=True)@@ -4417,7 +4416,7 @@ class TestNormalize(BaseTester):expected = (inputs - 1) * 2- identity = kornia.eye_like(3, expected)+ identity = kornia.core.ops.eye_like(3, expected)self.assert_close(f(inputs), expected)self.assert_close(f.transform_matrix, identity)@@ -4432,7 +4431,7 @@ class TestNormalize(BaseTester):expected = (inputs - 1) * 2- identity = kornia.eye_like(3, expected)+ identity = kornia.core.ops.eye_like(3, expected)self.assert_close(f(inputs), expected)self.assert_close(f.transform_matrix, identity)@@ -4467,7 +4466,7 @@ class TestDenormalize(BaseTester):expected = inputs / 2 + 1- identity = kornia.eye_like(3, expected)+ identity = kornia.core.ops.eye_like(3, expected)self.assert_close(f(inputs), expected)self.assert_close(f.transform_matrix, identity)@@ -4482,7 +4481,7 @@ class TestDenormalize(BaseTester):expected = inputs / 2 + 1- identity = kornia.eye_like(3, expected)+ identity = kornia.core.ops.eye_like(3, expected)self.assert_close(f(inputs), expected)self.assert_close(f.transform_matrix, identity)diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex e25f774a2..d563a0cfd 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -35,7 +35,7 @@ from kornia.augmentation.random_generator import (ResizedCropGenerator,center_crop_generator,)-from kornia.utils._compat import torch_version_ge+from kornia.core._compat import torch_version_gefrom testing.base import assert_closediff --git a/tests/color/test_gray.py b/tests/color/test_gray.pyindex 775d126b4..a8a93e109 100644--- a/tests/color/test_gray.py+++ b/tests/color/test_gray.py@@ -20,7 +20,7 @@ import torchfrom torch.autograd import gradcheckimport kornia-from kornia.utils._compat import torch_version+from kornia.core._compat import torch_versionfrom testing.base import BaseTester, assert_closediff --git a/tests/contrib/test_extract_tensor_patch.py b/tests/contrib/test_extract_tensor_patch.pyindex 28c3837f8..9f3e7dd06 100644--- a/tests/contrib/test_extract_tensor_patch.py+++ b/tests/contrib/test_extract_tensor_patch.py@@ -128,7 +128,7 @@ class TestExtractTensorPatches(BaseTester):return kornia.geometry.denormalize_pixel_coordinates(img, height, width)height, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True).to(device)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True).to(device)actual = op_script(grid, height, width)expected = kornia.denormalize_pixel_coordinates(grid, height, width)diff --git a/tests/utils/test_helpers.py b/tests/core/test_helpers.pysimilarity index 97%rename from tests/utils/test_helpers.pyrename to tests/core/test_helpers.pyindex fb816ff23..533504db9 100644--- a/tests/utils/test_helpers.py+++ b/tests/core/test_helpers.py@@ -18,8 +18,9 @@import pytestimport torch-from kornia.utils import _extract_device_dtype-from kornia.utils.helpers import (+from kornia.core.exceptions import DeviceError+from kornia.core.utils import (+ _extract_device_dtype,_torch_histc_cast,_torch_inverse_cast,_torch_solve_cast,@@ -70,7 +71,7 @@ def test_extract_device_dtype(tensor_list, out_device, out_dtype, will_throw_err# warnings.warn("Add GPU tests.")if will_throw_error:- with pytest.raises(ValueError):+ with pytest.raises(DeviceError):_extract_device_dtype(tensor_list)else:device, dtype = _extract_device_dtype(tensor_list)diff --git a/tests/core/test_tensor_wrapper.py b/tests/core/test_tensor_wrapper.pyindex 5fa14a390..f9e983ef4 100644--- a/tests/core/test_tensor_wrapper.py+++ b/tests/core/test_tensor_wrapper.py@@ -18,7 +18,8 @@import pytestimport torch-from kornia.core.tensor_wrapper import TensorWrapper, unwrap, wrap+from kornia.core.exceptions import TypeCheckError+from kornia.core.tensor_wrapper import TensorWrapper, _unwrap, _wrapfrom testing.base import BaseTester@@ -26,7 +27,7 @@ from testing.base import BaseTesterclass TestTensorWrapper(BaseTester):def test_smoke(self, device, dtype):data = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- tensor = wrap(data, TensorWrapper)+ tensor = _wrap(data, TensorWrapper)assert isinstance(tensor, TensorWrapper)assert isinstance(tensor.data, torch.Tensor)assert tensor.shape == (1, 2, 3, 4)@@ -34,18 +35,44 @@ class TestTensorWrapper(BaseTester):assert tensor.dtype == dtypeself.assert_close(data, tensor.unwrap())+ def test_init_validation(self):+ """Test that TensorWrapper validates input type."""+ with pytest.raises(TypeCheckError, match="Tensor"):+ TensorWrapper([1, 2, 3]) # type: ignore++ with pytest.raises(TypeCheckError, match="Tensor"):+ TensorWrapper("not a tensor") # type: ignore++ def test_repr(self, device, dtype):+ """Test string representation."""+ data = torch.rand(2, 3, device=device, dtype=dtype)+ tensor = TensorWrapper(data)+ repr_str = repr(tensor)+ assert "TensorWrapper" in repr_str+ assert str(data) in repr_str or repr(data) in repr_str++ def test_data_property(self, device, dtype):+ """Test data property access."""+ data = torch.rand(2, 3, device=device, dtype=dtype)+ tensor = TensorWrapper(data)+ assert tensor.data is data+ assert isinstance(tensor.data, torch.Tensor)+def test_serialization(self, device, dtype, tmp_path):data = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- tensor: TensorWrapper = wrap(data, TensorWrapper)+ tensor: TensorWrapper = _wrap(data, TensorWrapper)file_path = tmp_path / "tensor.pt"torch.save(tensor, file_path)- file_path.is_file()+ assert file_path.is_file()loaded_tensor: TensorWrapper = torch.load(file_path, weights_only=False)assert isinstance(loaded_tensor, TensorWrapper)self.assert_close(loaded_tensor.unwrap(), tensor.unwrap())+ # Check that used_attrs and used_calls are preserved+ assert hasattr(loaded_tensor, "used_attrs")+ assert hasattr(loaded_tensor, "used_calls")def test_wrap_list(self, device, dtype):data_list = [@@ -55,11 +82,11 @@ class TestTensorWrapper(BaseTester):1,0.5,]- tensor_list = wrap(data_list, TensorWrapper)+ tensor_list = _wrap(data_list, TensorWrapper)assert isinstance(tensor_list, list)assert len(tensor_list) == 5- tensor_list_data = unwrap(tensor_list)+ tensor_list_data = _unwrap(tensor_list)assert len(tensor_list_data) == 5self.assert_close(tensor_list_data[0], data_list[0])@@ -71,14 +98,26 @@ class TestTensorWrapper(BaseTester):for i in range(len(tensor_list_data[:3])):self.assert_close(tensor_list[i].unwrap(), data_list[i])+ def test_wrap_tuple(self, device, dtype):+ """Test wrapping tuples."""+ data_tuple = (+ torch.rand(2, device=device, dtype=dtype),+ torch.rand(3, device=device, dtype=dtype),+ )+ tensor_tuple = _wrap(data_tuple, TensorWrapper)+ assert isinstance(tensor_tuple, tuple)+ assert len(tensor_tuple) == 2+ assert isinstance(tensor_tuple[0], TensorWrapper)+ assert isinstance(tensor_tuple[1], TensorWrapper)+def test_accessors(self, device, dtype):data = torch.tensor([0.0, 1.0, 0.0], device=device, dtype=dtype)- x = wrap(data, TensorWrapper)- self.assert_close(x[1], torch.tensor(1.0, device=device, dtype=dtype))+ x = _wrap(data, TensorWrapper)+ self.assert_close(x[1].unwrap(), torch.tensor(1.0, device=device, dtype=dtype))y = x[0]- self.assert_close(y, torch.tensor(0.0, device=device, dtype=dtype))+ self.assert_close(y.unwrap(), torch.tensor(0.0, device=device, dtype=dtype))x[1] = 0.0- self.assert_close(x, torch.zeros_like(x))+ self.assert_close(x.unwrap(), torch.zeros_like(data))def test_unary_ops(self, device, dtype):data = torch.rand(2, device=device, dtype=dtype)@@ -86,30 +125,141 @@ class TestTensorWrapper(BaseTester):x1 = TensorWrapper(data)x2 = TensorWrapper(data)- self.assert_close(x.add(x), x + x)- self.assert_close(x.add(1), 1 + x)- self.assert_close(x.add(1), x + 1)- self.assert_close(x.mul(x), x * x)- self.assert_close(x.mul(1), 1 * x)- self.assert_close(x.mul(1), x * 1)- self.assert_close(x.sub(x), x - x)- self.assert_close(x.sub(1), x - 1)- self.assert_close(x.div(x), x / x)- self.assert_close(x.true_divide(x), x / x)- self.assert_close(x.floor_divide(x), x // x)- self.assert_close(x1.ge(x2), x1 >= x2)- self.assert_close(x1.gt(x2), x1 > x2)- self.assert_close(x1.lt(x2), x1 < x2)- self.assert_close(x1.le(x2), x1 <= x2)- self.assert_close(x1.eq(x2), x1 == x2)- self.assert_close(x1.ne(x2), x1 != x2)- self.assert_close(-x, -data)+ # Methods like x.add() return unwrapped tensors, operators return wrapped tensors+ self.assert_close(x.add(x), (x + x).unwrap())+ self.assert_close(x.add(1), (1 + x).unwrap())+ self.assert_close(x.add(1), (x + 1).unwrap())+ self.assert_close(x.mul(x), (x * x).unwrap())+ self.assert_close(x.mul(1), (1 * x).unwrap())+ self.assert_close(x.mul(1), (x * 1).unwrap())+ self.assert_close(x.sub(x), (x - x).unwrap())+ self.assert_close(x.sub(1), (x - 1).unwrap())+ self.assert_close(x.div(x), (x / x).unwrap())+ self.assert_close(x.true_divide(x), (x / x).unwrap())+ self.assert_close(x.floor_divide(x), (x // x).unwrap())+ self.assert_close(x1.ge(x2), (x1 >= x2).unwrap())+ self.assert_close(x1.gt(x2), (x1 > x2).unwrap())+ self.assert_close(x1.lt(x2), (x1 < x2).unwrap())+ self.assert_close(x1.le(x2), (x1 <= x2).unwrap())+ self.assert_close(x1.eq(x2), (x1 == x2).unwrap())+ self.assert_close(x1.ne(x2), (x1 != x2).unwrap())+ self.assert_close((-x).unwrap(), -data)++ def test_bool_int_conversion(self, device):+ """Test boolean and integer conversion."""+ # Test __bool__+ data_true = torch.tensor([1.0], device=device)+ tensor_true = TensorWrapper(data_true)+ assert bool(tensor_true) is True++ data_false = torch.tensor([0.0], device=device)+ tensor_false = TensorWrapper(data_false)+ assert bool(tensor_false) is False++ # Test __int__+ data_int = torch.tensor([42], device=device, dtype=torch.int32)+ tensor_int = TensorWrapper(data_int)+ assert int(tensor_int) == 42+ assert isinstance(int(tensor_int), int)++ def test_right_side_operations(self, device, dtype):+ """Test right-side operations (radd, rsub, rmul)."""+ data = torch.tensor([2.0, 3.0], device=device, dtype=dtype)+ x = TensorWrapper(data)+ scalar = 5.0++ # Test __radd__: scalar + tensor+ result_radd = scalar + x+ expected_radd = scalar + data+ self.assert_close(result_radd.unwrap(), expected_radd)++ # Test __rsub__: scalar - tensor+ result_rsub = scalar - x+ expected_rsub = scalar - data+ self.assert_close(result_rsub.unwrap(), expected_rsub)++ # Test __rmul__: scalar * tensor+ result_rmul = scalar * x+ expected_rmul = scalar * data+ self.assert_close(result_rmul.unwrap(), expected_rmul)++ def test_used_attrs_tracking(self, device, dtype):+ """Test that attribute usage is tracked."""+ data = torch.rand(2, 3, device=device, dtype=dtype)+ tensor = TensorWrapper(data)++ # Initially empty+ assert len(tensor.used_attrs) == 0++ # Access some attributes+ _ = tensor.shape+ _ = tensor.device+ _ = tensor.dtype++ # Check that they're tracked+ assert "shape" in tensor.used_attrs+ assert "device" in tensor.used_attrs+ assert "dtype" in tensor.used_attrs++ def test_used_calls_tracking(self, device, dtype):+ """Test that function calls are tracked."""+ data = torch.rand(2, 3, device=device, dtype=dtype)+ tensor = TensorWrapper(data)++ # Initially empty+ assert len(tensor.used_calls) == 0++ # Call some operations+ _ = tensor + tensor+ _ = tensor * 2+ _ = torch.sum(tensor)++ # Check that they're tracked+ assert len(tensor.used_calls) > 0+ assert torch.add in tensor.used_calls or torch.mul in tensor.used_calls++ def test_setattr_tracking(self, device, dtype):+ """Test that setattr doesn't track internal attributes."""+ data = torch.rand(2, 3, device=device, dtype=dtype)+ tensor = TensorWrapper(data)++ # Setting a new attribute on the underlying tensor should be tracked+ tensor.some_new_attr = 42+ assert "some_new_attr" in tensor.used_attrsdef test_callable(self, device, dtype):data = torch.ones(2, device=device, dtype=dtype)x = TensorWrapper(data)y = (x * x).sum(-1, True)- self.assert_close(y, torch.ones_like(y) * 2)+ # sum() method returns unwrapped tensor, so compare directly+ expected = torch.ones_like(y) * 2+ self.assert_close(y, expected)++ def test_len(self, device, dtype):+ """Test __len__ method."""+ data = torch.rand(5, device=device, dtype=dtype)+ tensor = TensorWrapper(data)+ assert len(tensor) == 5+ assert len(tensor) == len(data)++ def test_nested_wrapping(self, device, dtype):+ """Test that wrapping already-wrapped tensors works correctly."""+ data = torch.rand(2, 3, device=device, dtype=dtype)+ wrapped_once = TensorWrapper(data)+ wrapped_twice = _wrap(wrapped_once, TensorWrapper)++ # Should still unwrap to original data+ self.assert_close(_unwrap(wrapped_twice), data)++ def test_string_bytes_not_wrapped(self):+ """Test that strings and bytes are not treated as sequences in __torch_function__."""+ # This tests the fix for not treating strings/bytes as sequences+ data = torch.rand(2, 3)+ tensor = TensorWrapper(data)++ # Should not raise errors when strings/bytes are in args+ result = torch.cat([tensor, tensor])+ assert isinstance(result, TensorWrapper)@pytest.mark.skip(reason="not implemented yet")def test_cardinality(self, device, dtype):@@ -119,9 +269,10 @@ class TestTensorWrapper(BaseTester):def test_jit(self, device, dtype):pass- @pytest.mark.skip(reason="not implemented yet")- def test_exception(self, device, dtype):- pass+ def test_exception(self):+ """Test exception handling for invalid inputs."""+ with pytest.raises(TypeCheckError):+ TensorWrapper([1, 2, 3]) # type: ignore@pytest.mark.skip(reason="not implemented yet")def test_module(self, device, dtype):diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex 644a71a8a..bdc977504 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -1048,7 +1048,7 @@ class TestSharpness(BaseTester):self.assert_close(actual, expected)[email protected](kornia.xla_is_available(), reason="issues with xla device")[email protected](kornia.core.utils.xla_is_available(), reason="issues with xla device")class TestSolarize(BaseTester):f = kornia.enhance.solarize@@ -1165,7 +1165,7 @@ class TestPosterize(BaseTester):assert TestPosterize.f(img, 1.0)# TODO(jian): add better cases- @pytest.mark.skipif(kornia.xla_is_available(), reason="issues with xla device")+ @pytest.mark.skipif(kornia.core.utils.xla_is_available(), reason="issues with xla device")def test_value(self, device, dtype):torch.manual_seed(0)diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.pyindex 3f2f3ee15..e321bcfe3 100644--- a/tests/enhance/test_histogram.py+++ b/tests/enhance/test_histogram.py@@ -146,7 +146,7 @@ class TestHistogram2d(BaseTester):bandwidth = torch.tensor(2 * 0.4**2, device=device, dtype=dtype)pdf = TestHistogram2d.fcn(sample1, sample2, bins, bandwidth)- ans = 0.1 * kornia.eye_like(10, pdf)+ ans = 0.1 * kornia.core.ops.eye_like(10, pdf)self.assert_close(ans, pdf)diff --git a/tests/utils/test_misc.py b/tests/enhance/test_jpeg_misc.pysimilarity index 87%rename from tests/utils/test_misc.pyrename to tests/enhance/test_jpeg_misc.pyindex 0ee09a1dc..ba80a1045 100644--- a/tests/utils/test_misc.py+++ b/tests/enhance/test_jpeg_misc.py@@ -17,10 +17,14 @@import torch-from kornia.utils.misc import (- differentiable_clipping,- differentiable_polynomial_floor,- differentiable_polynomial_rounding,+from kornia.enhance.jpeg import (+ _differentiable_clipping as differentiable_clipping,+)+from kornia.enhance.jpeg import (+ _differentiable_polynomial_floor as differentiable_polynomial_floor,+)+from kornia.enhance.jpeg import (+ _differentiable_polynomial_rounding as differentiable_polynomial_rounding,)from testing.base import BaseTesterdiff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex 7567736b9..351fa7d10 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -22,6 +22,7 @@ import torchfrom torch import nnimport kornia+from kornia.core._compat import torch_version_lefrom kornia.feature import (DescriptorMatcher,GFTTAffNetHardNet,@@ -39,7 +40,6 @@ from kornia.feature import ()from kornia.feature.integrated import LocalFeatureMatcherfrom kornia.geometry import RANSAC, resize, transform_points-from kornia.utils._compat import torch_version_lefrom testing.base import BaseTesterfrom testing.casts import dict_todiff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.pyindex afd69910f..3af670b25 100644--- a/tests/feature/test_lightglue_onnx.py+++ b/tests/feature/test_lightglue_onnx.py@@ -18,9 +18,9 @@import pytestimport torch+from kornia.core._compat import torch_version_lefrom kornia.feature import OnnxLightGluefrom kornia.feature.lightglue_onnx.utils import normalize_keypoints-from kornia.utils._compat import torch_version_letry:import onnxruntime as ortdiff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.pyindex c587aaeff..44c9a9c06 100644--- a/tests/feature/test_loftr.py+++ b/tests/feature/test_loftr.py@@ -20,9 +20,9 @@ import sysimport pytestimport torch+from kornia.core._compat import torch_version_gefrom kornia.feature import LoFTRfrom kornia.geometry import resize-from kornia.utils._compat import torch_version_gefrom testing.base import BaseTesterfrom testing.casts import dict_todiff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.pyindex a6605d32f..7d286eaa4 100644--- a/tests/feature/test_matching.py+++ b/tests/feature/test_matching.py@@ -18,6 +18,7 @@import pytestimport torch+from kornia.core._compat import torch_version_lefrom kornia.feature.integrated import LightGlueMatcherfrom kornia.feature.laf import laf_from_center_scale_orifrom kornia.feature.matching import (@@ -32,7 +33,6 @@ from kornia.feature.matching import (match_snn,)from kornia.feature.steerers import DiscreteSteerer-from kornia.utils._compat import torch_version_lefrom testing.base import BaseTesterfrom testing.casts import dict_todiff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.pyindex e32ccef45..66dc2675f 100644--- a/tests/filters/test_canny.py+++ b/tests/filters/test_canny.py@@ -18,8 +18,8 @@import pytestimport torch+from kornia.core._compat import torch_versionfrom kornia.filters import Canny, canny-from kornia.utils._compat import torch_versionfrom testing.base import BaseTesterdiff --git a/tests/filters/test_dissolving.py b/tests/filters/test_dissolving.pyindex 6a3e325ed..fa16881fd 100644--- a/tests/filters/test_dissolving.py+++ b/tests/filters/test_dissolving.py@@ -18,8 +18,8 @@import pytestimport torch+from kornia.core._compat import torch_version_lefrom kornia.filters.dissolving import StableDiffusionDissolving-from kornia.utils._compat import torch_version_leWEIGHTS_CACHE_DIR = "weights/"diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex f910800df..12c8be7b0 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -18,8 +18,8 @@import pytestimport torch+from kornia.core._compat import torch_version_lefrom kornia.filters import filter2d, filter2d_separable, filter3d-from kornia.utils._compat import torch_version_lefrom testing.base import BaseTesterdiff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.pyindex 41a956e77..f70d6f16f 100644--- a/tests/filters/test_guided.py+++ b/tests/filters/test_guided.py@@ -18,8 +18,8 @@import pytestimport torch+from kornia.core._compat import torch_versionfrom kornia.filters import GuidedBlur, guided_blur-from kornia.utils._compat import torch_versionfrom testing.base import BaseTesterdiff --git a/tests/filters/test_in_range.py b/tests/filters/test_in_range.pyindex fc4bc90a5..1e531c2a5 100644--- a/tests/filters/test_in_range.py+++ b/tests/filters/test_in_range.py@@ -20,8 +20,8 @@ import reimport pytestimport torch+from kornia.core._compat import torch_versionfrom kornia.filters import InRange, in_range-from kornia.utils._compat import torch_versionfrom testing.base import BaseTester, assert_closediff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.pyindex 94b6af363..aea1a3021 100644--- a/tests/filters/test_sobel.py+++ b/tests/filters/test_sobel.py@@ -18,8 +18,8 @@import pytestimport torch+from kornia.core._compat import torch_versionfrom kornia.filters import Sobel, SpatialGradient, SpatialGradient3d, sobel, spatial_gradient, spatial_gradient3d-from kornia.utils._compat import torch_versionfrom testing.base import BaseTesterdiff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.pyindex cd2e13de3..c4313023d 100644--- a/tests/geometry/calibration/test_pnp.py+++ b/tests/geometry/calibration/test_pnp.py@@ -154,7 +154,7 @@ class TestSolvePnpDlt(BaseTester):pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)- pred_world_to_cam_4x4 = kornia.eye_like(4, pred_world_to_cam)+ pred_world_to_cam_4x4 = kornia.core.ops.eye_like(4, pred_world_to_cam)pred_world_to_cam_4x4[:, :3, :] = pred_world_to_camrepeated_intrinsics = intrinsics.unsqueeze(1).repeat(1, num_points, 1, 1)diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex 3e3fa762b..6716a018c 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -182,8 +182,8 @@ class TestRelativeCameraMotion(BaseTester):t1 = torch.tensor([[[10.0], [0.0], [0.0]]]).type_as(R1)- R2 = kornia.eye_like(3, R1)- t2 = kornia.vec_like(3, t1)+ R2 = kornia.core.ops.eye_like(3, R1)+ t2 = kornia.core.ops.vec_like(3, t1)R_expected = R1.clone()t_expected = -t1@@ -197,8 +197,8 @@ class TestRelativeCameraMotion(BaseTester):R2 = torch.tensor([[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)- t1 = kornia.vec_like(3, R1)- t2 = kornia.vec_like(3, R2)+ t1 = kornia.core.ops.vec_like(3, R1)+ t2 = kornia.core.ops.vec_like(3, R2)R_expected = R2.clone()t_expected = t1diff --git a/tests/geometry/epipolar/test_numeric.py b/tests/geometry/epipolar/test_numeric.pyindex 2ff9006fb..cf473def9 100644--- a/tests/geometry/epipolar/test_numeric.py+++ b/tests/geometry/epipolar/test_numeric.py@@ -77,7 +77,7 @@ class TestSkewSymmetric:class TestEyeLike:def test_smoke(self, device, dtype):image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)- identity = kornia.eye_like(3, image)+ identity = kornia.core.ops.eye_like(3, image)assert identity.shape == (1, 3, 3)assert identity.device == image.deviceassert identity.dtype == image.dtype@@ -86,7 +86,7 @@ class TestEyeLike:def test_shape(self, batch_size, eye_size, device, dtype):B, N = batch_size, eye_sizeimage = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)- identity = kornia.eye_like(N, image)+ identity = kornia.core.ops.eye_like(N, image)assert identity.shape == (B, N, N)assert identity.device == image.deviceassert identity.dtype == image.dtype@@ -95,7 +95,7 @@ class TestEyeLike:class TestVecLike:def test_smoke(self, device, dtype):image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)- vec = kornia.vec_like(3, image)+ vec = kornia.core.ops.vec_like(3, image)assert vec.shape == (1, 3, 1)assert vec.device == image.deviceassert vec.dtype == image.dtype@@ -104,7 +104,7 @@ class TestVecLike:def test_shape(self, batch_size, eye_size, device, dtype):B, N = batch_size, eye_sizeimage = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)- vec = kornia.vec_like(N, image)+ vec = kornia.core.ops.vec_like(N, image)assert vec.shape == (B, N, 1)assert vec.device == image.deviceassert vec.dtype == image.dtypediff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.pyindex e9e310478..d61c12136 100644--- a/tests/geometry/epipolar/test_triangulation.py+++ b/tests/geometry/epipolar/test_triangulation.py@@ -66,8 +66,8 @@ class TestTriangulation:def test_gradcheck(self, device):points1 = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)points2 = torch.rand(1, 8, 2, device=device, dtype=torch.float64)- P1 = kornia.eye_like(3, points1)+ P1 = kornia.core.ops.eye_like(3, points1)P1 = torch.nn.functional.pad(P1, [0, 1])- P2 = kornia.eye_like(3, points2)+ P2 = kornia.core.ops.eye_like(3, points2)P2 = torch.nn.functional.pad(P2, [0, 1])assert gradcheck(epi.triangulate_points, (P1, P2, points1, points2), raise_exception=True, fast_mode=True)diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex e7331aa2f..fa048004b 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -23,6 +23,8 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_version+from kornia.core.ops import eye_likefrom kornia.geometry.conversions import (ARKitQTVecs_to_ColmapQTVecs,Rt_to_matrix4x4,@@ -38,8 +40,6 @@ from kornia.geometry.conversions import (worldtocam_to_camtoworld_Rt,)from kornia.geometry.quaternion import Quaternion-from kornia.utils._compat import torch_version-from kornia.utils.misc import eye_likefrom testing.base import BaseTester, assert_close@@ -760,9 +760,11 @@ class TestNormalizePixelCoordinates(BaseTester):def test_tensor_bhw2(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsheight, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(+ dtype=dtype+ )- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)@@ -773,10 +775,12 @@ class TestNormalizePixelCoordinates(BaseTester):def test_list(self, device, dtype, atol, rtol):eps = torch.finfo(dtype).epsheight, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(+ dtype=dtype+ )grid = grid.contiguous().view(-1, 2)- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)expected = expected.contiguous().view(-1, 2)@@ -793,7 +797,9 @@ class TestNormalizePixelCoordinates(BaseTester):op_optimized = torch_optimizer(op)height, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(+ dtype=dtype+ )actual = op_optimized(grid, height, width)expected = op(grid, height, width)@@ -804,9 +810,11 @@ class TestNormalizePixelCoordinates(BaseTester):class TestDenormalizePixelCoordinates(BaseTester):def test_tensor_bhw2(self, device, dtype):height, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(+ dtype=dtype+ )- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)@@ -816,10 +824,12 @@ class TestDenormalizePixelCoordinates(BaseTester):def test_list(self, device, dtype):height, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(+ dtype=dtype+ )grid = grid.contiguous().view(-1, 2)- expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(+ expected = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)expected = expected.contiguous().view(-1, 2)@@ -836,7 +846,9 @@ class TestDenormalizePixelCoordinates(BaseTester):op_optimized = torch_optimizer(op)height, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(+ dtype=dtype+ )actual = op_optimized(grid, height, width)expected = op(grid, height, width)diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex c97195170..d936c48fe 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -138,7 +138,7 @@ class TestDepthTo3d(BaseTester):points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix)points2d = kornia.geometry.camera.project_points(points3d.permute(0, 2, 3, 1), camera_matrix[:, None, None])- points2d_expected = kornia.utils.create_meshgrid(4, 3, False, device=device).to(dtype=dtype)+ points2d_expected = kornia.geometry.create_meshgrid(4, 3, False, device=device).to(dtype=dtype)self.assert_close(points2d, points2d_expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device):diff --git a/tests/utils/test_grid.py b/tests/geometry/test_grid.pysimilarity index 85%rename from tests/utils/test_grid.pyrename to tests/geometry/test_grid.pyindex ff1146088..fb1ad8661 100644--- a/tests/utils/test_grid.py+++ b/tests/geometry/test_grid.py@@ -28,7 +28,7 @@ def test_create_meshgrid(device, dtype):normalized_coordinates = False# create the meshgrid and verify shape- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates, device=device, dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates, device=device, dtype=dtype)assert grid.device == deviceassert grid.dtype == dtype@@ -47,13 +47,13 @@ def test_normalize_pixel_grid(device, dtype):height, width = 2, 4# create points grid- grid_norm = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device, dtype=dtype)+ grid_norm = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device, dtype=dtype)assert grid_norm.device == deviceassert grid_norm.dtype == dtypegrid_norm = torch.unsqueeze(grid_norm, dim=0)- grid_pix = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)+ grid_pix = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)assert grid_pix.device == deviceassert grid_pix.dtype == dtype@@ -76,7 +76,7 @@ def test_create_meshgrid3d(device, dtype):normalized_coordinates = False# create the meshgrid and verify shape- grid = kornia.utils.create_meshgrid3d(depth, height, width, normalized_coordinates, device=device, dtype=dtype)+ grid = kornia.geometry.create_meshgrid3d(depth, height, width, normalized_coordinates, device=device, dtype=dtype)assert grid.device == deviceassert grid.dtype == dtypediff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex 979a0a018..90cf53626 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -21,6 +21,7 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_version_lefrom kornia.geometry.homography import (find_homography_dlt,find_homography_dlt_iterated,@@ -31,7 +32,6 @@ from kornia.geometry.homography import (sample_is_valid_for_homography,symmetric_transfer_error,)-from kornia.utils._compat import torch_version_lefrom testing.base import BaseTesterfrom testing.geometry.create import create_random_homography@@ -218,7 +218,7 @@ class TestFindHomographyDLT(BaseTester):def test_clean_points_svd(self, batch_size, device, dtype):# generate input datapoints_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)- H = kornia.eye_like(3, points_src)+ H = kornia.core.ops.eye_like(3, points_src)H = H * 0.3 * torch.rand_like(H)H = H / H[:, 2:3, 2:3]@@ -238,7 +238,7 @@ class TestFindHomographyDLT(BaseTester):def test_clean_points_lu(self, batch_size, device, dtype):# generate input datapoints_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)- H = kornia.eye_like(3, points_src)+ H = kornia.core.ops.eye_like(3, points_src)H = H * 0.3 * torch.rand_like(H)H = H / H[:, 2:3, 2:3]@@ -352,7 +352,7 @@ class TestFindHomographyFromLinesDLT(BaseTester):points_src_st = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)points_src_end = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)- H = kornia.eye_like(3, points_src_st)+ H = kornia.core.ops.eye_like(3, points_src_st)H = H * 0.3 * torch.rand_like(H)H = H / H[:, 2:3, 2:3]points_dst_st = kornia.geometry.transform_points(H, points_src_st)@@ -377,7 +377,7 @@ class TestFindHomographyFromLinesDLT(BaseTester):points_src_st = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)points_src_end = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)- H = kornia.eye_like(3, points_src_st)+ H = kornia.core.ops.eye_like(3, points_src_st)H = H * 0.3 * torch.rand_like(H)H = H / H[:, 2:3, 2:3]points_dst_st = kornia.geometry.transform_points(H, points_src_st)@@ -434,7 +434,7 @@ class TestFindHomographyDLTIter(BaseTester):def test_clean_points(self, batch_size, device, dtype):# generate input datapoints_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)- H = kornia.eye_like(3, points_src)+ H = kornia.core.ops.eye_like(3, points_src)H = H * 0.3 * torch.rand_like(H)H = H / H[:, 2:3, 2:3]@@ -459,7 +459,7 @@ class TestFindHomographyDLTIter(BaseTester):def test_dirty_points_and_gradcheck(self, batch_size, device, dtype):# generate input datapoints_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)- H = kornia.eye_like(3, points_src)+ H = kornia.core.ops.eye_like(3, points_src)H = H * (1 + torch.rand_like(H))H = H / H[:, 2:3, 2:3]diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.pyindex bc9a7f591..096039ada 100644--- a/tests/geometry/test_linalg.py+++ b/tests/geometry/test_linalg.py@@ -59,7 +59,7 @@ class TestTransformPoints(BaseTester):def test_dynamo(self, device, dtype, torch_optimizer):points = torch.ones(1, 2, 2, device=device, dtype=dtype)- transform = kornia.eye_like(3, points)+ transform = kornia.core.ops.eye_like(3, points)op = kornia.geometry.transform_pointsop_script = torch_optimizer(op)actual = op_script(transform, points)diff --git a/tests/utils/test_pointcloud_io.py b/tests/geometry/test_pointcloud_io.pysimilarity index 79%rename from tests/utils/test_pointcloud_io.pyrename to tests/geometry/test_pointcloud_io.pyindex ba9df360f..6fb02a9a9 100644--- a/tests/utils/test_pointcloud_io.py+++ b/tests/geometry/test_pointcloud_io.py@@ -32,9 +32,9 @@ class TestSaveLoadPointCloud:xyz_save = torch.rand(height, width, 3)filename = "pointcloud.ply"- kornia.utils.save_pointcloud_ply(filename, xyz_save)+ kornia.geometry.save_pointcloud_ply(filename, xyz_save)- xyz_load = kornia.utils.load_pointcloud_ply(filename)+ xyz_load = kornia.geometry.load_pointcloud_ply(filename)assert_close(xyz_save.reshape(-1, 3), xyz_load)if os.path.exists(filename):@@ -50,11 +50,11 @@ class TestSaveLoadPointCloud:xyz_save[1, 0, :-1] = float("inf") # partial inf β keptfilename = "pointcloud.ply"- kornia.utils.save_pointcloud_ply(filename, xyz_save)+ kornia.geometry.save_pointcloud_ply(filename, xyz_save)xyz_correct = xyz_save.reshape(-1, 3)[1:, :]- xyz_load = kornia.utils.load_pointcloud_ply(filename)+ xyz_load = kornia.geometry.load_pointcloud_ply(filename)assert_close(xyz_correct, xyz_load)if os.path.exists(filename):@@ -63,29 +63,29 @@ class TestSaveLoadPointCloud:def test_invalid_filename_type(self):xyz_save = torch.rand(10, 3)with pytest.raises(TypeError):- kornia.utils.save_pointcloud_ply(1234, xyz_save)+ kornia.geometry.save_pointcloud_ply(1234, xyz_save)def test_invalid_filename_extension(self):xyz_save = torch.rand(10, 3)with pytest.raises(TypeError):- kornia.utils.save_pointcloud_ply("pointcloud.txt", xyz_save)+ kornia.geometry.save_pointcloud_ply("pointcloud.txt", xyz_save)def test_invalid_pointcloud_type(self):with pytest.raises(TypeError):- kornia.utils.save_pointcloud_ply("pointcloud.ply", [[1, 2, 3]])+ kornia.geometry.save_pointcloud_ply("pointcloud.ply", [[1, 2, 3]])def test_invalid_pointcloud_shape(self):xyz_save = torch.rand(10, 4)with pytest.raises(TypeError):- kornia.utils.save_pointcloud_ply("pointcloud.ply", xyz_save)+ kornia.geometry.save_pointcloud_ply("pointcloud.ply", xyz_save)def test_save_pointcloud_with_nan(self):xyz_save = torch.rand(5, 3)xyz_save[0, :] = float("nan")xyz_save[1, 0] = float("nan")filename = "pointcloud_nan.ply"- kornia.utils.save_pointcloud_ply(filename, xyz_save)- xyz_load = kornia.utils.load_pointcloud_ply(filename)+ kornia.geometry.save_pointcloud_ply(filename, xyz_save)+ xyz_load = kornia.geometry.load_pointcloud_ply(filename)expected = xyz_save[torch.isfinite(xyz_save).any(dim=1)]# Use numpy to compare with NaNs considered equaldiff --git a/tests/geometry/transform/test_crop3d.py b/tests/geometry/transform/test_crop3d.pyindex 5b4d611f6..7bb2a6488 100644--- a/tests/geometry/transform/test_crop3d.py+++ b/tests/geometry/transform/test_crop3d.py@@ -19,7 +19,7 @@ import pytestimport torchimport kornia-from kornia.utils._compat import torch_version+from kornia.core._compat import torch_versionfrom testing.base import BaseTesterdiff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.pyindex 19a6cf7a0..fbd7e7ced 100644--- a/tests/geometry/transform/test_homography_warper.py+++ b/tests/geometry/transform/test_homography_warper.py@@ -19,8 +19,8 @@ import pytestimport torchimport kornia-from kornia.utils.helpers import _torch_inverse_cast-from kornia.utils.misc import eye_like+from kornia.core.ops import eye_like+from kornia.core.utils import _torch_inverse_castfrom testing.base import BaseTesterfrom testing.error import compute_patch_abs_error@@ -151,7 +151,7 @@ class TestHomographyWarper(BaseTester):def test_warp_grid_translation(self, shape, offset, device, dtype):# create input dataheight, width = shape- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)dst_homo_src = eye_like(3, grid)dst_homo_src[..., 0, 2] = offset # apply offset in xflow = kornia.geometry.transform.warp_grid(grid, dst_homo_src)@@ -282,7 +282,7 @@ class TestHomographyWarper(BaseTester):if (device == torch.device("cpu")and batch_size != 1- and kornia.utils._compat.torch_version() in {"2.3.0", "2.3.1"}+ and kornia.core._compat.torch_version() in {"2.3.0", "2.3.1"}):pytest.skip("Failing to compile batched inputs see pytorch/pytorch#126617")@@ -446,7 +446,7 @@ class TestHomographyWarper3D(BaseTester):def test_warp_grid_translation(self, shape, offset, device, dtype):# create input datadepth, height, width = shape- grid = kornia.utils.create_meshgrid3d(+ grid = kornia.geometry.create_meshgrid3d(depth, height, width, normalized_coordinates=False, dtype=dtype, device=device)dst_homo_src = eye_like(4, grid)diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.pyindex dbf157685..c05044933 100644--- a/tests/geometry/transform/test_image_registrator.py+++ b/tests/geometry/transform/test_image_registrator.py@@ -21,10 +21,10 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_versionfrom kornia.geometry import transform_pointsfrom kornia.geometry.conversions import denormalize_homographyfrom kornia.geometry.transform import ImageRegistrator-from kornia.utils._compat import torch_versionfrom testing.base import BaseTesterfrom testing.casts import dict_todiff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.pyindex c1b45266f..6a593128b 100644--- a/tests/geometry/transform/test_imgwarp.py+++ b/tests/geometry/transform/test_imgwarp.py@@ -21,8 +21,8 @@ import pytestimport torchimport kornia-from kornia.utils._compat import torch_version, torch_version_lt-from kornia.utils.helpers import _torch_inverse_cast+from kornia.core._compat import torch_version, torch_version_lt+from kornia.core.utils import _torch_inverse_castfrom testing.base import BaseTester@@ -332,7 +332,7 @@ class TestWarpPerspective(BaseTester):def test_smoke(self, device, dtype):batch_size, channels, height, width = 1, 2, 3, 4img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)- H_ab = kornia.eye_like(3, img_b)+ H_ab = kornia.core.ops.eye_like(3, img_b)img_a = kornia.geometry.warp_perspective(img_b, H_ab, (height, width))self.assert_close(img_b, img_a)@@ -342,7 +342,7 @@ class TestWarpPerspective(BaseTester):batch_size, channels, height, width = batch_shapeh_out, w_out = out_shapeimg_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)- H_ab = kornia.eye_like(3, img_b)+ H_ab = kornia.core.ops.eye_like(3, img_b)img_a = kornia.geometry.warp_perspective(img_b, H_ab, (h_out, w_out))assert img_a.shape == (batch_size, channels, h_out, w_out)@@ -370,7 +370,7 @@ class TestWarpPerspective(BaseTester):h, w = 3, 4img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)- homo_ab = kornia.eye_like(3, img_b)+ homo_ab = kornia.core.ops.eye_like(3, img_b)homo_ab[..., :2, -1] += offsetexpected = torch.zeros_like(img_b)@@ -385,7 +385,7 @@ class TestWarpPerspective(BaseTester):h, w = 3, 4img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)- homo_ab = kornia.eye_like(3, img_b)+ homo_ab = kornia.core.ops.eye_like(3, img_b)homo_ab[..., :2, -1] += offsetexpected = torch.zeros_like(img_b)@@ -495,7 +495,7 @@ class TestWarpPerspective(BaseTester):if dtype == torch.float64 and torch_version() in {"2.0.0", "2.0.1"} and sys.platform == "linux":pytest.xfail("Failing on CI on ubuntu with torch 2.0.0 for float64")img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)- H_ab = kornia.eye_like(3, img)+ H_ab = kornia.core.ops.eye_like(3, img)args = (img, H_ab, (4, 5))op = kornia.geometry.warp_perspectiveop_optimized = torch_optimizer(op)@@ -504,7 +504,7 @@ class TestWarpPerspective(BaseTester):def test_gradcheck(self, device):batch_size, channels, height, width = 1, 2, 3, 4img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)- H_ab = kornia.eye_like(3, img_b)+ H_ab = kornia.core.ops.eye_like(3, img_b)# TODO(dmytro/edgar): firgure out why gradient don't propagate for the tranaformself.gradcheck(kornia.geometry.warp_perspective, (img_b, H_ab, (height, width)), requires_grad=(True, False, False)@@ -515,7 +515,7 @@ class TestWarpPerspective(BaseTester):h, w = 3, 4img_b = torch.arange(float(3 * h * w), device=device, dtype=dtype).view(1, 3, h, w)- homo_ab = kornia.eye_like(3, img_b)+ homo_ab = kornia.core.ops.eye_like(3, img_b)homo_ab[..., :2, -1] += offset# normally fill_value will also be converted to the right device and type in warp_perspective@@ -532,7 +532,7 @@ class TestRemap(BaseTester):def test_smoke(self, device, dtype):height, width = 3, 4input_org = torch.ones(1, 1, height, width, device=device, dtype=dtype)- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)input_warped = kornia.geometry.remap(input_org, grid[..., 0], grid[..., 1], normalized_coordinates=False, align_corners=True)@@ -540,7 +540,7 @@ class TestRemap(BaseTester):def test_different_size(self, device, dtype):height, width = 3, 4- grid = kornia.utils.create_meshgrid(height, width, device=device, dtype=dtype)+ grid = kornia.geometry.create_meshgrid(height, width, device=device, dtype=dtype)img = torch.rand(1, 2, 6, 5, device=device, dtype=dtype)img_warped = kornia.geometry.remap(img, grid[..., 0], grid[..., 1])@@ -555,7 +555,7 @@ class TestRemap(BaseTester):[[[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]], device=device, dtype=dtype)- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)grid += 1.0 # apply shift in both x/y directioninput_warped = kornia.geometry.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)@@ -577,7 +577,7 @@ class TestRemap(BaseTester):)# generate a batch of grids- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)grid = grid.repeat(2, 1, 1, 1)grid[0, ..., 0] += 1.0 # apply shift in the x directiongrid[1, ..., 1] += 1.0 # apply shift in the y direction@@ -594,7 +594,7 @@ class TestRemap(BaseTester):[[[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)grid += 1.0 # apply shift in both x/y directioninput_warped = kornia.geometry.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)@@ -610,7 +610,7 @@ class TestRemap(BaseTester):[[[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)- grid = kornia.utils.create_meshgrid(+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=normalized_coordinates, device=device).to(dtype)@@ -624,7 +624,7 @@ class TestRemap(BaseTester):batch_size, channels, height, width = 1, 2, 3, 4img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)- grid = kornia.utils.create_meshgrid(+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=torch.float64)@@ -640,7 +640,7 @@ class TestRemap(BaseTester):batch_size, channels, height, width = 1, 1, 3, 4img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)grid += 1.0 # apply some shiftop = kornia.geometry.remapdiff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.pyindex 51c66703c..c8521fb96 100644--- a/tests/geometry/transform/test_imgwarp3d.py+++ b/tests/geometry/transform/test_imgwarp3d.py@@ -20,7 +20,7 @@ import torchimport korniaimport kornia.geometry.transform as proj-from kornia.utils.helpers import _torch_inverse_cast+from kornia.core.utils import _torch_inverse_castfrom testing.base import BaseTesterdiff --git a/tests/utils/test_draw.py b/tests/image/test_draw.pysimilarity index 99%rename from tests/utils/test_draw.pyrename to tests/image/test_draw.pyindex c8c45a5e4..26b9a5bd5 100644--- a/tests/utils/test_draw.py+++ b/tests/image/test_draw.py@@ -20,8 +20,9 @@ import mathimport pytestimport torch-from kornia.utils import create_meshgrid, draw_convex_polygon, draw_rectangle-from kornia.utils.draw import draw_line, draw_point2d+from kornia.geometry import create_meshgrid+from kornia.image import draw_convex_polygon, draw_rectangle+from kornia.image.draw import draw_line, draw_point2dfrom testing.base import assert_closediff --git a/tests/image/test_image.py b/tests/image/test_image.pyindex 4ea324fe7..7e5123b78 100644--- a/tests/image/test_image.py+++ b/tests/image/test_image.py@@ -21,9 +21,9 @@ import numpy as npimport pytestimport torch+from kornia.core._compat import torch_version_lefrom kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormatfrom kornia.image.image import Image-from kornia.utils._compat import torch_version_lefrom testing.base import BaseTesterdiff --git a/tests/utils/test_image_utils.py b/tests/image/test_image_utils.pysimilarity index 85%rename from tests/utils/test_image_utils.pyrename to tests/image/test_image_utils.pyindex 3ccad26b3..f61b71996 100644--- a/tests/utils/test_image_utils.py+++ b/tests/image/test_image_utils.py@@ -31,7 +31,7 @@ from testing.base import assert_close)def test_image_to_tensor_keep_dtype(input_dtype, expected_dtype):image = np.ones((1, 3, 4, 5), dtype=input_dtype)- tensor = kornia.image_to_tensor(image)+ tensor = kornia.image.image_to_tensor(image)assert tensor.dtype == expected_dtype@@ -40,15 +40,15 @@ def test_list_of_images_to_tensor(num_of_images, image_shape):images: List[np.array] = []if num_of_images == 0:with pytest.raises(ValueError):- kornia.utils.image_list_to_tensor([])+ kornia.image.image_list_to_tensor([])returnfor _ in range(num_of_images):images.append(np.ones(shape=image_shape))if len(image_shape) != 3:with pytest.raises(ValueError):- kornia.utils.image_list_to_tensor(images)+ kornia.image.image_list_to_tensor(images)return- tensor = kornia.utils.image_list_to_tensor(images)+ tensor = kornia.image.image_list_to_tensor(images)assert tensor.shape == (num_of_images, image_shape[-1], image_shape[-3], image_shape[-2])@@ -65,7 +65,7 @@ def test_list_of_images_to_tensor(num_of_images, image_shape):)def test_tensor_to_image(device, input_shape, expected):tensor = torch.ones(input_shape).to(device)- image = kornia.utils.tensor_to_image(tensor)+ image = kornia.image.tensor_to_image(tensor)assert image.shape == expectedassert isinstance(image, np.ndarray)@@ -83,7 +83,7 @@ def test_tensor_to_image(device, input_shape, expected):)def test_tensor_to_image_keepdim(device, input_shape, expected):tensor = torch.ones(input_shape).to(device)- image = kornia.utils.tensor_to_image(tensor, keepdim=True)+ image = kornia.image.tensor_to_image(tensor, keepdim=True)assert image.shape == expectedassert isinstance(image, np.ndarray)@@ -101,11 +101,11 @@ def test_tensor_to_image_keepdim(device, input_shape, expected):)def test_image_to_tensor(input_shape, expected):image = np.ones(input_shape)- tensor = kornia.utils.image_to_tensor(image, keepdim=False)+ tensor = kornia.image.image_to_tensor(image, keepdim=False)assert tensor.shape == expectedassert isinstance(tensor, torch.Tensor)- to_tensor = kornia.utils.ImageToTensor(keepdim=False)+ to_tensor = kornia.image.ImageToTensor(keepdim=False)assert_close(tensor, to_tensor(image))@@ -122,7 +122,7 @@ def test_image_to_tensor(input_shape, expected):)def test_image_to_tensor_keepdim(input_shape, expected):image = np.ones(input_shape)- tensor = kornia.utils.image_to_tensor(image, keepdim=True)+ tensor = kornia.image.image_to_tensor(image, keepdim=True)assert tensor.shape == expectedassert isinstance(tensor, torch.Tensor)@@ -130,8 +130,8 @@ def test_image_to_tensor_keepdim(input_shape, expected):def test_tensor_to_image_contiguous(device, dtype):tensor = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)- image = kornia.utils.tensor_to_image(tensor)+ image = kornia.image.tensor_to_image(tensor)assert not image.flags["C_CONTIGUOUS"]- image = kornia.utils.tensor_to_image(tensor, force_contiguous=True)+ image = kornia.image.tensor_to_image(tensor, force_contiguous=True)assert image.flags["C_CONTIGUOUS"]diff --git a/tests/utils/test_print.py b/tests/image/test_print.pysimilarity index 97%rename from tests/utils/test_print.pyrename to tests/image/test_print.pyindex b20000382..8edefed79 100644--- a/tests/utils/test_print.py+++ b/tests/image/test_print.py@@ -18,7 +18,7 @@import pytestimport torch-from kornia.utils import image_to_string, print_image+from kornia.image import image_to_string, print_imageclass TestImageToString:diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.pyindex 007dbbefa..a2800e455 100644--- a/tests/io/test_io_image.py+++ b/tests/io/test_io_image.py@@ -24,8 +24,8 @@ import pytestimport requestsimport torch+from kornia.core._compat import torch_version_gefrom kornia.io import ImageLoadType, load_image, write_image-from kornia.utils._compat import torch_version_getry:import kornia_rsdiff --git a/tests/utils/test_one_hot.py b/tests/losses/test_one_hot.pysimilarity index 70%rename from tests/utils/test_one_hot.pyrename to tests/losses/test_one_hot.pyindex 3a1d640d2..d58fd3e20 100644--- a/tests/utils/test_one_hot.py+++ b/tests/losses/test_one_hot.py@@ -17,7 +17,7 @@import torch-import kornia+from kornia.losses.one_hot import one_hotfrom testing.base import assert_close@@ -32,9 +32,9 @@ class TestOneHot:labels[1, 1, 0] = 3# convert labels to one hot tensor- one_hot = kornia.utils.one_hot(labels, num_classes, device, dtype)+ one_hot_tensor = one_hot(labels, num_classes, device, dtype)- assert_close(one_hot[0, labels[0, 0, 0], 0, 0].item(), 1.0)- assert_close(one_hot[0, labels[0, 1, 0], 1, 0].item(), 1.0)- assert_close(one_hot[1, labels[1, 0, 0], 0, 0].item(), 1.0)- assert_close(one_hot[1, labels[1, 1, 0], 1, 0].item(), 1.0)+ assert_close(one_hot_tensor[0, labels[0, 0, 0], 0, 0].item(), 1.0)+ assert_close(one_hot_tensor[0, labels[0, 1, 0], 1, 0].item(), 1.0)+ assert_close(one_hot_tensor[1, labels[1, 0, 0], 0, 0].item(), 1.0)+ assert_close(one_hot_tensor[1, labels[1, 1, 0], 1, 0].item(), 1.0)diff --git a/tests/losses/test_total_variation.py b/tests/losses/test_total_variation.pyindex e28ccc4a7..5cc3200cf 100644--- a/tests/losses/test_total_variation.py+++ b/tests/losses/test_total_variation.py@@ -19,7 +19,6 @@ import pytestimport torchimport kornia-from kornia.utils import torch_meshgridfrom testing.base import BaseTester@@ -138,7 +137,7 @@ class TestTotalVariation(BaseTester):@pytest.mark.parametrize("reduction, expected", [("sum", torch.tensor(20)), ("mean", torch.tensor(1))])def test_tv_reduction(self, device, dtype, reduction, expected):- pred, _ = torch_meshgrid([torch.arange(5), torch.arange(5)], "ij")+ pred, _ = torch.meshgrid([torch.arange(5), torch.arange(5)], indexing="ij")pred = pred.to(device, dtype)actual = kornia.losses.total_variation(pred, reduction=reduction)self.assert_close(actual, expected.to(device, dtype), rtol=1e-3, atol=1e-3)diff --git a/tests/models/test_efficient_vit.py b/tests/models/test_efficient_vit.pyindex d156b9edc..a357a4301 100644--- a/tests/models/test_efficient_vit.py+++ b/tests/models/test_efficient_vit.py@@ -19,9 +19,9 @@import pytestimport torch+from kornia.core._compat import torch_version_ltfrom kornia.models.efficient_vit import EfficientViT, EfficientViTConfigfrom kornia.models.efficient_vit import backbone as vit-from kornia.utils._compat import torch_version_ltclass TestEfficientViT:diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.pyindex 4c0caf9ed..76f1402f9 100644--- a/tests/models/test_object_detector.py+++ b/tests/models/test_object_detector.py@@ -22,8 +22,8 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_version_ltfrom kornia.models.rt_detr import RTDETR, DETRPostProcessor, RTDETRConfig-from kornia.utils._compat import torch_version_ltfrom testing.base import BaseTesterdiff --git a/tests/models/test_prompter.py b/tests/models/test_prompter.pyindex 5a398a14f..ac6ec4abd 100644--- a/tests/models/test_prompter.py+++ b/tests/models/test_prompter.py@@ -19,8 +19,8 @@ import pytestimport torchfrom kornia.contrib.visual_prompter import VisualPrompter+from kornia.core._compat import torch_versionfrom kornia.models.sam import SamConfig-from kornia.utils._compat import torch_versionfrom testing.base import BaseTesterdiff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.pyindex 6de49aa44..75e6dc2c6 100644--- a/tests/tracking/test_planar_tracking.py+++ b/tests/tracking/test_planar_tracking.py@@ -18,10 +18,10 @@import pytestimport torch+from kornia.core._compat import torch_version_lefrom kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, SIFTFeaturefrom kornia.geometry import rescale, transform_pointsfrom kornia.tracking import HomographyTracker-from kornia.utils._compat import torch_version_lefrom testing.base import assert_closediff --git a/tests/utils/test_memory.py b/tests/utils/test_memory.pydeleted file mode 100644index 78bfc0997..000000000--- a/tests/utils/test_memory.py+++ /dev/null@@ -1,45 +0,0 @@-# 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 torch--import kornia--from testing.base import BaseTester---class TestBatchedForward(BaseTester):- def test_runbatch(self, device):- patches = torch.rand(34, 1, 32, 32)- sift = kornia.feature.SIFTDescriptor(32)- desc_batched = kornia.utils.memory.batched_forward(sift, patches, device, 32)- desc = sift(patches)- assert torch.allclose(desc, desc_batched)-- def test_runone(self, device):- patches = torch.rand(16, 1, 32, 32)- sift = kornia.feature.SIFTDescriptor(32)- desc_batched = kornia.utils.memory.batched_forward(sift, patches, device, 32)- desc = sift(patches)- assert torch.allclose(desc, desc_batched)-- def test_gradcheck(self, device):- batch_size, channels, height, width = 3, 2, 5, 4- img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)- self.gradcheck(- kornia.utils.memory.batched_forward, (kornia.feature.BlobHessian(), img, device, 2), nondet_tol=1e-4- )diff --git a/tests/utils/test_parametrized_tester_poc.py b/tests/utils/test_parametrized_tester_poc.pydeleted file mode 100644index e67ce6cd9..000000000--- a/tests/utils/test_parametrized_tester_poc.py+++ /dev/null@@ -1,77 +0,0 @@-# 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.-#--"""Proof of Concept: Parametrized test automation using the new decorator.--This demonstrates the usage of the @parametrized_test decorator on existing-test classes to automatically generate test_smoke, test_cardinality, and-test_gradcheck methods parametrized across devices and dtypes.-"""--import torch--from kornia.utils.misc import differentiable_clipping, differentiable_polynomial_floor--from testing.base import BaseTester-from testing.parametrized_tester import parametrized_test---@parametrized_test(- smoke_inputs=lambda device, dtype: (torch.tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),- cardinality_tests=[- {- "inputs": lambda device, dtype: (torch.tensor([1.0, 6.0, 10.0, 12.0], device=device, dtype=dtype),),- "expected_shape": torch.Size([4]),- }- ],- gradcheck_inputs=lambda device: (torch.tensor([1.0, 6.0, 11.0, 12.0], device=device, dtype=torch.float64),),-)-class TestDifferentiableClippingAutomated(BaseTester):- """Demonstration of automated tests for differentiable_clipping function.-- The @parametrized_test decorator automatically generates:- - test_smoke: Runs the function with valid inputs- - test_cardinality: Verifies output shapes- - test_gradcheck: Validates gradient computation-- All tests are parametrized across devices and dtypes automatically.- """-- def setup_method(self) -> None:- """Set up test fixtures."""- self.func = lambda x: differentiable_clipping(x, min_val=5.0, max_val=10.0)---@parametrized_test(- smoke_inputs=lambda device, dtype: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),- cardinality_tests=[- {- "inputs": lambda device, dtype: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=dtype),),- "expected_shape": torch.Size([4]),- }- ],- gradcheck_inputs=lambda device: (torch.tensor([1.5, 3.1, 5.9, 6.6], device=device, dtype=torch.float64),),-)-class TestDifferentiablePolynomialFloorAutomated(BaseTester):- """Demonstration of automated tests for differentiable_polynomial_floor function.-- Uses the same @parametrized_test decorator pattern as TestDifferentiableClippingAutomated.- """-- def setup_method(self) -> None:- """Set up test fixtures."""- self.func = differentiable_polynomial_floor