π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Refactor kornia.models across repo (#3426)
Edgar Riba0b78c772b086
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex bbf528763..9a1f3a9f2 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -12,53 +12,53 @@ ModelsBase^^^^-.. autoclass:: kornia.contrib.models.base.ModelBase+.. autoclass:: kornia.models.base.ModelBase:members::undoc-members:EfficientViT^^^^^^^^^^^^-.. autoclass:: kornia.contrib.models.efficient_vit.EfficientViT+.. autoclass:: kornia.models.efficient_vit.EfficientViT:members: from_config, forward, load_checkpoint:undoc-members::special-members: __init__,-.. autoclass:: kornia.contrib.models.efficient_vit.EfficientViTConfig+.. autoclass:: kornia.models.efficient_vit.EfficientViTConfig:members::undoc-members:Backbones^^^^^^^^^-.. autoclass:: kornia.contrib.models.efficient_vit.backbone.EfficientViTBackbone+.. autoclass:: kornia.models.efficient_vit.backbone.EfficientViTBackbone:members::undoc-members:-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b0-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b1-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b2-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b3+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_b0+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_b1+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_b2+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_b3-.. autoclass:: kornia.contrib.models.efficient_vit.backbone.EfficientViTLargeBackbone+.. autoclass:: kornia.models.efficient_vit.backbone.EfficientViTLargeBackbone:members::undoc-members:-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l0-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l1-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l2-.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l3+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_l0+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_l1+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_l2+.. autofunction:: kornia.models.efficient_vit.backbone.efficientvit_backbone_l3Structures^^^^^^^^^^.. _anchor SegmentationResults:-.. autoclass:: kornia.contrib.models.SegmentationResults+.. autoclass:: kornia.models.structures.SegmentationResults:members::undoc-members:-.. autoclass:: kornia.contrib.models.Prompts+.. autoclass:: kornia.models.structures.Prompts:members::undoc-members:@@ -125,21 +125,21 @@ Object DetectionReal-Time Detection Transformer (RT-DETR)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-.. autoclass:: kornia.contrib.models.rt_detr.RTDETRModelType+.. autoclass:: kornia.models.rt_detr.RTDETRModelType:members::undoc-members::member-order: bysource-.. autoclass:: kornia.contrib.models.rt_detr.RTDETRConfig+.. autoclass:: kornia.models.rt_detr.RTDETRConfig:members::undoc-members:-.. autoclass:: kornia.contrib.models.rt_detr.RTDETR+.. autoclass:: kornia.models.rt_detr.RTDETR:members: from_config, forward, load_checkpoint:undoc-members::special-members: __init__,-.. autoclass:: kornia.contrib.models.rt_detr.DETRPostProcessor+.. autoclass:: kornia.models.rt_detr.DETRPostProcessor:members::undoc-members:@@ -150,16 +150,16 @@ Image SegmentationSegment Anything (SAM)^^^^^^^^^^^^^^^^^^^^^^-.. autoclass:: kornia.contrib.models.sam.SamModelType+.. autoclass:: kornia.models.sam.SamModelType:members::undoc-members::member-order: bysource-.. autoclass:: kornia.contrib.models.sam.SamConfig+.. autoclass:: kornia.models.sam.SamConfig:members::undoc-members:-.. autoclass:: kornia.contrib.models.sam.Sam+.. autoclass:: kornia.models.sam.Sam:members: from_config, forward, load_checkpoint:undoc-members::special-members: __init__,@@ -177,12 +177,11 @@ Image PatchesImage Classification---------------------.. autoclass:: VisionTransformer+.. autoclass:: kornia.models.vit.VisionTransformer:members:-.. autoclass:: MobileViT+.. autoclass:: kornia.models.vit_mobile.MobileViT.. autoclass:: TinyViT:members:-.. autoclass:: ClassificationHeadImage Stitching---------------diff --git a/docs/source/filters.rst b/docs/source/filters.rstindex ad790e9a5..a5a0ba11d 100644--- a/docs/source/filters.rst+++ b/docs/source/filters.rst@@ -47,7 +47,6 @@ Edge detection.. autoclass:: Canny.. autoclass:: SpatialGradient.. autoclass:: SpatialGradient3d-.. autoclass:: DexiNedInteractive Demodiff --git a/docs/source/index.rst b/docs/source/index.rstindex e9cdf14f4..e705e382f 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -47,10 +47,10 @@ Vision Transformer for image classification... code:: python>>> import torch.nn as nn- >>> import kornia.contrib as K+ >>> from kornia.models.vit import VisionTransformer>>> classifier = nn.Sequential(- ... K.VisionTransformer(image_size=224, patch_size=16),- ... K.ClassificationHead(num_classes=1000),+ ... VisionTransformer(image_size=224, patch_size=16),+ ... nn.Linear(768, 1000), # Example: 768 is the default hidden_dim, 1000 is num_classes... )>>> logits = classifier(img) # BxN>>> scores = logits.argmax(-1) # Bdiff --git a/docs/source/models.rst b/docs/source/models.rstindex ff0290065..cf6fac7a9 100644--- a/docs/source/models.rst+++ b/docs/source/models.rst@@ -20,7 +20,7 @@ The `RTDETRDetectorBuilder` class is a builder for constructing a detection mode- `build`: Constructs and returns an instance of the RTDETR detection model.- `save`: Saves the processed image or results after applying the detection model.-.. autoclass:: kornia.models.detection.rtdetr.RTDETRDetectorBuilder+.. autoclass:: kornia.contrib.object_detection.RTDETRDetectorBuilder:members::undoc-members::show-inheritance:@@ -33,35 +33,35 @@ The `RTDETRDetectorBuilder` class is a builder for constructing a detection modeimport korniaimage = kornia.utils.sample.get_sample_images()[0][None]- model = kornia.models.detection.rtdetr.RTDETRDetectorBuilder.build()+ model = kornia.contrib.object_detection.RTDETRDetectorBuilder.build()model.save(image)-.. _DexiNedBuilder:+.. _EdgeDetectorBuilder:-DexiNedBuilder---------------+EdgeDetectorBuilder+--------------------The `DexiNedBuilder` class implements a state-of-the-art edge detection model based on DexiNed, which excels at detecting fine-grained edges in images. This model is well-suited for tasks like medical imaging, object contour detection, and more.+The `EdgeDetectorBuilder` class implements a state-of-the-art edge detection model based on DexiNed, which excels at detecting fine-grained edges in images. This model is well-suited for tasks like medical imaging, object contour detection, and more.**Key Methods:**- `build`: Builds and returns an instance of the DexiNed edge detection model.- `save`: Saves the detected edges for further processing or visualization.-.. autoclass:: kornia.models.edge_detection.dexined.DexiNedBuilder+.. autoclass:: kornia.contrib.edge_detection.EdgeDetectorBuilder:members::undoc-members::show-inheritance:.. rubric:: Example- The following code shows how to use the `DexiNedBuilder` to detect edges in an image:+ The following code shows how to use the `EdgeDetectorBuilder` to detect edges in an image:.. code-block:: pythonimport korniaimage = kornia.utils.sample.get_sample_images()[0][None]- model = kornia.models.edge_detection.dexined.DexiNedBuilder.build()+ model = kornia.contrib.edge_detection.EdgeDetectorBuilder.build()model.save(image).. _SegmentationModels:@@ -115,7 +115,7 @@ The `BoxMotTracker` class is used for multi-object tracking in video streams. It- `max_lost`: (int) The maximum number of frames where an object can be lost before it is removed from the tracker.-.. autoclass:: kornia.models.tracking.boxmot_tracker.BoxMotTracker+.. autoclass:: kornia.contrib.boxmot_tracker.BoxMotTracker:members::undoc-members::show-inheritance:@@ -128,7 +128,7 @@ The `BoxMotTracker` class is used for multi-object tracking in video streams. Itimport korniaimage = kornia.utils.sample.get_sample_images()[0][None]- model = kornia.models.tracking.boxmot_tracker.BoxMotTracker()+ model = kornia.contrib.boxmot_tracker.BoxMotTracker()for i in range(4):model.update(image) # Update the tracker with new framesmodel.save(image) # Save the tracking resultdiff --git a/docs/source/models/mobile_sam.rst b/docs/source/models/mobile_sam.rstindex 6510bef20..c0828a3c8 100644--- a/docs/source/models/mobile_sam.rst+++ b/docs/source/models/mobile_sam.rst@@ -26,7 +26,7 @@ MobileSAM is integrated directly into our Segment-Anything implementation. Once.. code:: pythonimport torch- from kornia.contrib.models.sam import SamConfig+ from kornia.models.sam import SamConfigfrom kornia.contrib.visual_prompter import VisualPrompterimage = torch.randn(3, 512, 512)diff --git a/docs/source/models/rt_detr.rst b/docs/source/models/rt_detr.rstindex ca67cb06b..ee56f5587 100644--- a/docs/source/models/rt_detr.rst+++ b/docs/source/models/rt_detr.rst@@ -4,7 +4,7 @@ Real-Time Detection Transformer (RT-DETR).. code-block:: pythonfrom kornia.io import load_image- from kornia.models.detector.rtdetr import RTDETRDetectorBuilder+ from kornia.contrib.object_detection import RTDETRDetectorBuilderinput_img = load_image(img_path)[None] # Load image to BCHW@@ -20,7 +20,7 @@ Real-Time Detection Transformer (RT-DETR)output[0].save("Kornia-RTDETR-output.png")# convert the whole model to ONNX directly- RTDETRDetectorBuilder.to_onnx("RTDETR-640.onnx", model_name="rtdetr_r18vd", image_size=640)+ detector.to_onnx("RTDETR-640.onnx", image_size=640).. card::diff --git a/docs/source/models/segment_anything.rst b/docs/source/models/segment_anything.rstindex ce5e6f6be..c6bd35365 100644--- a/docs/source/models/segment_anything.rst+++ b/docs/source/models/segment_anything.rst@@ -91,7 +91,7 @@ to query the image masks from the SAM model.import torch- from kornia.contrib.models.sam import SamConfig+ from kornia.models.sam import SamConfigfrom kornia.contrib.visual_prompter import VisualPrompterfrom kornia.io import load_image, ImageLoadTypefrom kornia.geometry.keypoints import Keypoints@@ -179,13 +179,13 @@ parameters. If a checkpoint URL or path for a file is seted, the method will aut.. code-block:: python- from kornia.contrib.models.sam import Sam, SamConfig+ from kornia.models.sam import Sam, SamConfigfrom kornia.utils import get_cuda_or_mps_device_if_available# model_type can be:- # 0, 'vit_h' or `kornia.contrib.models.sam.SamModelType.vit_h`- # 1, 'vit_l' or `kornia.contrib.models.sam.SamModelType.vit_l`- # 2, 'vit_b' or `kornia.contrib.models.sam.SamModelType.vit_b`+ # 0, 'vit_h' or `kornia.models.sam.SamModelType.vit_h`+ # 1, 'vit_l' or `kornia.models.sam.SamModelType.vit_l`+ # 2, 'vit_b' or `kornia.models.sam.SamModelType.vit_b`model_type = 'vit_b'# The checkpoint can be a filepath or a url@@ -215,7 +215,7 @@ If a URL is passed the model will automatically download and cache the weights u.. code-block:: python- from kornia.contrib.models.sam import Sam, SamConfig+ from kornia.models.sam import Sam, SamConfigfrom kornia.utils import get_cuda_or_mps_device_if_availablemodel_type = 'vit_b'@@ -242,8 +242,8 @@ This is a simple example, of how to directly use the SAM model loaded. We recomm.. code-block:: python- from kornia.contrib.models.sam import Sam- from kornia.contrib.models import SegmentationResults+ from kornia.models.sam import Sam+ from kornia.models.structures import SegmentationResultsfrom kornia.io import load_image, ImageLoadTypefrom kornia.utils import get_cuda_or_mps_device_if_availablefrom kornia.geometry import resizediff --git a/docs/source/models/tiny_vit.rst b/docs/source/models/tiny_vit.rstindex 82f5fd286..e31e708af 100644--- a/docs/source/models/tiny_vit.rst+++ b/docs/source/models/tiny_vit.rst@@ -28,7 +28,7 @@ You can use TinyViT models as follows... code:: pythonimport torch- from kornia.contrib.models.tiny_vit import TinyViT+ from kornia.models.tiny_vit import TinyViTmodel = TinyViT.from_config("5m", pretrained=True) # ImageNet-1k pre-traineddiff --git a/docs/source/models/vit.rst b/docs/source/models/vit.rstindex 9b8c0a806..359fa2cc3 100644--- a/docs/source/models/vit.rst+++ b/docs/source/models/vit.rst@@ -28,7 +28,7 @@ Vision Transformer (ViT)Kornia-ViT-----------We provide the operator :py:class:`~kornia.contrib.VisionTransformer` that is meant to be used across tasks.+We provide the operator :py:class:`~kornia.models.vit.VisionTransformer` that is meant to be used across tasks.One can use the *ViT* in Kornia as follows:.. code:: python@@ -41,17 +41,16 @@ Usage~~~~~``kornia-vit`` does not include any classification head.-For this reason, we provide an :py:class:`~kornia.contrib.ClassificationHead` which can be easily combined-with a `nn.Sequential` in order to easily build a custom image classification pipeline.+You can easily add your own classification head using standard PyTorch modules... code:: pythonimport torch.nn as nn- import kornia.contrib as K+ from kornia.models.vit import VisionTransformerclassifier = nn.Sequential(- K.VisionTransformer(image_size=224, patch_size=16),- K.ClassificationHead(num_classes=1000)+ VisionTransformer(image_size=224, patch_size=16),+ nn.Linear(768, 1000) # Example: 768 is the default hidden_dim, 1000 is num_classes)img = torch.rand(1, 3, 224, 224)@@ -64,13 +63,15 @@ class with two different classification heads:.. code:: python+ from kornia.models.vit import VisionTransformer+class MultiTaskTransfornmer(nn.Module):def __init__(self) -> None:super().__init__()- self.transformer = K.VisionTransformer(+ self.transformer = VisionTransformer(image_size=224, patch_size=16)- self.head1 = K.ClassificationHead(num_classes=10)- self.head2 = K.ClassificationHead(num_classes=50)+ self.head1 = nn.Linear(768, 10) # Example: 768 is the default hidden_dim+ self.head2 = nn.Linear(768, 50)def forward(self, x: torch.Tensor):out = self.transformer(x)diff --git a/docs/source/models/vit_mobile.rst b/docs/source/models/vit_mobile.rstindex 4bab978a2..86987bb6c 100644--- a/docs/source/models/vit_mobile.rst+++ b/docs/source/models/vit_mobile.rst@@ -24,7 +24,7 @@ MobileViTKornia-MobileViT-----------------We provide :py:class:`~kornia.contrib.MobileViT` which can be used for many downstream tasks, e.g., classification, object detection and semantic segmentation.+We provide :py:class:`~kornia.models.vit_mobile.MobileViT` which can be used for many downstream tasks, e.g., classification, object detection and semantic segmentation.One can use the *MobileViT* in Kornia as follows:.. code:: python@@ -42,10 +42,10 @@ Similar to ``Kornia-ViT``, ``Kornia-MobileViT`` does not include any classificat.. code:: pythonimport torch.nn as nn- import kornia.contrib as K+ from kornia.models.vit_mobile import MobileViTclassifier = nn.Sequential(- K.MobileViT(mode='xxs'),+ MobileViT(mode='xxs'),nn.AvgPool2d(256 // 32, 1),nn.Flatten(),nn.Linear(320, 1000)diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex eb1d8ff6c..83d0b0b4b 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -20,11 +20,13 @@This subpackage provides community-contributed and experimental features."""-from .classification import ClassificationHead+from kornia.models.tiny_vit import TinyViT++from .boxmot_tracker import BoxMotTrackerfrom .connected_components import connected_componentsfrom .diamond_square import diamond_squarefrom .distance_transform import DistanceTransform, distance_transform-from .edge_detection import EdgeDetector+from .edge_detection import EdgeDetector, EdgeDetectorBuilderfrom .extract_patches import (CombineTensorPatches,ExtractTensorPatches,@@ -37,24 +39,25 @@ from .histogram_matching import histogram_matching, interpfrom .image_stitching import ImageStitcherfrom .kmeans import KMeansfrom .lambda_module import Lambda-from .models.tiny_vit import TinyViT-from .object_detection import ObjectDetector-from .vit import VisionTransformer-from .vit_mobile import MobileViT+from .object_detection import ObjectDetector, RTDETRDetectorBuilder+from .super_resolution import RRDBNetBuilder, SmallSRBuilder, SuperResolution__all__ = [- "ClassificationHead",+ "BoxMotTracker","CombineTensorPatches","DistanceTransform","EdgeDetector",+ "EdgeDetectorBuilder","ExtractTensorPatches","ImageStitcher","KMeans","Lambda",- "MobileViT","ObjectDetector",+ "RRDBNetBuilder",+ "RTDETRDetectorBuilder",+ "SmallSRBuilder",+ "SuperResolution","TinyViT",- "VisionTransformer","combine_tensor_patches","compute_padding","connected_components",diff --git a/kornia/models/tracking/boxmot_tracker.py b/kornia/contrib/boxmot_tracker.pysimilarity index 98%rename from kornia/models/tracking/boxmot_tracker.pyrename to kornia/contrib/boxmot_tracker.pyindex 0056b91f0..401ba28e7 100644--- a/kornia/models/tracking/boxmot_tracker.py+++ b/kornia/contrib/boxmot_tracker.py@@ -24,12 +24,11 @@ from pathlib import Pathfrom typing import Any, Optional, Unionfrom kornia.config import kornia_config+from kornia.contrib.object_detection import ObjectDetector, RTDETRDetectorBuilderfrom kornia.core import Tensor, tensorfrom kornia.core.external import boxmotfrom kornia.core.external import numpy as npfrom kornia.io import write_image-from kornia.models.detection.base import ObjectDetector-from kornia.models.detection.rtdetr import RTDETRDetectorBuilderfrom kornia.utils.image import tensor_to_image__all__ = ["BoxMotTracker"]diff --git a/kornia/contrib/classification.py b/kornia/contrib/classification.pydeleted file mode 100644index 14d9155b2..000000000--- a/kornia/contrib/classification.py+++ /dev/null@@ -1,46 +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.-#--"""Module containing utilities for classification."""--import torch-from torch import nn---class ClassificationHead(nn.Module):- """Module to be used as a classification head.-- Args:- embed_size: the logits tensor coming from the networks.- num_classes: an integer representing the numbers of classes to classify.-- Example:- >>> feat = torch.rand(1, 256, 256)- >>> head = ClassificationHead(256, 10)- >>> head(feat).shape- torch.Size([1, 10])-- """-- def __init__(self, embed_size: int = 768, num_classes: int = 10) -> None:- super().__init__()- self.norm = nn.LayerNorm(embed_size)- self.linear = nn.Linear(embed_size, num_classes)-- def forward(self, x: torch.Tensor) -> torch.Tensor:- out = x.mean(-2)- return self.linear(self.norm(out))diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.pyindex f86d49e95..d4e065da8 100644--- a/kornia/contrib/edge_detection.py+++ b/kornia/contrib/edge_detection.py@@ -15,43 +15,240 @@# limitations under the License.#-from kornia.core import Module, Tensor-from kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.filters.dexined import DexiNed+from __future__ import annotations+from typing import Any, Optional, Union-class EdgeDetector(Module):- r"""Detect edges in a given image using a CNN.+import torch- By default, it uses the method described in :cite:`xsoria2020dexined`.+from kornia.color.gray import grayscale_to_rgb+from kornia.core import Tensor, tensor+from kornia.core.external import PILImage as Image+from kornia.core.external import onnx+from kornia.core.mixin.onnx import ONNXExportMixin+from kornia.enhance.normalize import Normalize+from kornia.models.base import ModelBase+from kornia.models.dexined import DexiNed+from kornia.models.processors import ResizePostProcessor, ResizePreProcessor- Return:- A tensor of shape :math:`(B,1,H,W)`.+__all__ = ["EdgeDetector", "EdgeDetectorBuilder"]+++class EdgeDetector(ModelBase, ONNXExportMixin):+ """EdgeDetector is a module that wraps an edge detection model.++ This is a high-level API that wraps edge detection models like :py:class:`kornia.models.DexiNed`.++ Args:+ model: The edge detection model.+ pre_processor: Pre-processing module (e.g., ResizePreProcessor).+ post_processor: Post-processing module (e.g., ResizePostProcessor).+ name: Optional name for the detector.Example:+ >>> from kornia.models.dexined import DexiNed+ >>> from kornia.models.processors import ResizePreProcessor, ResizePostProcessor+ >>> model = DexiNed(pretrained=True)+ >>> detector = EdgeDetector(model, ResizePreProcessor(352, 352), ResizePostProcessor())>>> img = torch.rand(1, 3, 320, 320)- >>> detect = EdgeDetector()- >>> out = detect(img)- >>> out.shape- torch.Size([1, 1, 320, 320])+ >>> out = detector(img)"""- def __init__(self) -> None:+ name: str = "edge_detection"++ def __init__(+ self,+ model: torch.nn.Module,+ pre_processor: torch.nn.Module,+ post_processor: torch.nn.Module,+ name: Optional[str] = None,+ ) -> None:+ """Initialize EdgeDetector.++ Args:+ model: The edge detection model.+ pre_processor: Pre-processing module (e.g., ResizePreProcessor).+ post_processor: Post-processing module (e.g., ResizePostProcessor).+ name: Optional name for the detector.++ """super().__init__()- self.model = DexiNed(pretrained=True)+ self.model = model.eval()+ self.pre_processor = pre_processor+ self.post_processor = post_processor+ if name is not None:+ self.name = name++ @staticmethod+ def from_config(config: Any) -> EdgeDetector:+ """Build EdgeDetector from config.++ This is a placeholder to satisfy the abstract method requirement.+ Use EdgeDetectorBuilder.build() or instantiate EdgeDetector directly.++ Args:+ config: Configuration object (not used, kept for interface compatibility).++ Returns:+ EdgeDetector instance.++ """+ raise NotImplementedError(+ "EdgeDetector.from_config() is not implemented. "+ "Use EdgeDetectorBuilder.build() or instantiate EdgeDetector directly."+ )++ @torch.inference_mode()+ def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:+ """Forward pass of the edge detection model.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ output tensor.++ """+ images, image_sizes = self.pre_processor(images)+ out_images = self.model(images)+ return self.post_processor(out_images, image_sizes)++ def visualize(+ self,+ images: Union[Tensor, list[Tensor]],+ edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ output_type: str = "torch",+ ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ """Draw the edge detection results.++ Args:+ images: input tensor.+ edge_maps: detected edges.+ output_type: type of the output.++ Returns:+ output tensor.++ """+ if edge_maps is None:+ edge_maps = self.forward(images)+ output = []+ for edge_map in edge_maps:+ output.append(grayscale_to_rgb(edge_map)[0])++ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))++ def save(+ self,+ images: Union[Tensor, list[Tensor]],+ edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ directory: Optional[str] = None,+ output_type: str = "torch",+ ) -> None:+ """Save the edge detection results.++ Args:+ images: input tensor.+ edge_maps: detected edges.+ output_type: type of the output.+ directory: where to save outputs.++ Returns:+ output tensor.++ """+ outputs = self.visualize(images, edge_maps, output_type)+ self._save_outputs(images, directory, suffix="_src")+ self._save_outputs(outputs, directory, suffix="_edge")++ def to_onnx( # type: ignore[override]+ self,+ onnx_name: Optional[str] = None,+ image_size: Optional[int] = 352,+ include_pre_and_post_processor: bool = True,+ save: bool = True,+ additional_metadata: Optional[list[tuple[str, str]]] = None,+ **kwargs: Any,+ ) -> onnx.ModelProto: # type: ignore+ """Export the current edge detection model to an ONNX model file.++ Args:+ onnx_name:+ The name of the output ONNX file. If not provided, a default name in the+ format "Kornia-<ClassName>.onnx" will be used.+ image_size:+ The size to which input images will be resized during preprocessing.+ If None, image_size will be dynamic. For DexiNed, recommended scale is 352.+ include_pre_and_post_processor:+ Whether to include the pre-processor and post-processor in the exported model.+ save:+ If to save the model or load it.+ additional_metadata:+ Additional metadata to add to the ONNX model.+ kwargs: Additional arguments to convert to onnx.++ """+ if onnx_name is None:+ onnx_name = f"kornia_{self.name}_{image_size}.onnx"++ return ONNXExportMixin.to_onnx(+ self,+ onnx_name,+ input_shape=[-1, 3, image_size or -1, image_size or -1],+ output_shape=[-1, 1, image_size or -1, image_size or -1],+ pseudo_shape=[1, 3, image_size or 352, image_size or 352],+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )+++class EdgeDetectorBuilder:+ """EdgeDetectorBuilder is a class that builds an edge detection model.++ 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)+ """++ @staticmethod+ def build(model_name: str = "dexined", pretrained: bool = True, image_size: int = 352) -> EdgeDetector:+ """Build an edge detection model.++ Args:+ model_name: Name of the model to build. Currently only "dexined" is supported.+ pretrained: If True, loads pretrained weights.+ image_size: Size to which input images will be resized during preprocessing.++ Returns:+ EdgeDetector instance configured with the specified model.- def load(self, path_file: str) -> None:- self.model.load_from_file(path_file)+ Example:+ >>> detector = EdgeDetectorBuilder.build(pretrained=True, image_size=352)+ >>> img = torch.rand(1, 3, 320, 320)+ >>> out = detector(img)- def preprocess(self, image: Tensor) -> Tensor:- return image+ """+ if model_name.lower() == "dexined":+ # Normalize then scale to [0, 255]+ norm = Normalize(mean=tensor([[0.485, 0.456, 0.406]]), std=tensor([[1.0 / 255.0] * 3]))+ from torch import nn- def postprocess(self, data: Tensor) -> Tensor:- return data+ model = nn.Sequential(norm, DexiNed(pretrained=pretrained), nn.Sigmoid())+ else:+ raise ValueError(f"Model {model_name} not found. Please choose from 'dexined'.")- def forward(self, image: Tensor) -> Tensor:- KORNIA_CHECK_SHAPE(image, ["B", "3", "H", "W"])- img = self.preprocess(image)- out = self.model(img)- return self.postprocess(out)+ return EdgeDetector(+ model,+ ResizePreProcessor(image_size, image_size),+ ResizePostProcessor(),+ name="dexined",+ )diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.pyindex 5acc9f66c..29afd80e7 100644--- a/kornia/contrib/face_detection.py+++ b/kornia/contrib/face_detection.py@@ -15,23 +15,20 @@# limitations under the License.#-# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa-import mathfrom enum import Enum-from typing import Dict, List, Optional, Tuple+from typing import Dict, List, Optionalimport torch-import torch.nn.functional as Ffrom torch import nnfrom kornia.geometry.bbox import nms as nms_kornia+from kornia.models.yunet import YuNet+from kornia.models.yunet.processors import PriorBox+from kornia.models.yunet.processors import decode as _decode__all__ = ["FaceDetector", "FaceDetectorResult", "FaceKeypoint"]-url: str = "https://github.com/kornia/data/raw/main/yunet_final.pth"--class FaceKeypoint(Enum):r"""Define the keypoints detected in a face.@@ -145,8 +142,9 @@ class FaceDetectorResult:class FaceDetector(nn.Module):- r"""Detect faces in a given image using a CNN.+ r"""Detect faces in a given image using YuNet model.+ This is a high-level API that wraps the :py:class:`kornia.models.YuNet` model for face detection.By default, it uses the method described in :cite:`facedetect-yu`.Args:@@ -174,7 +172,7 @@ class FaceDetector(nn.Module):self.nms_threshold = nms_thresholdself.keep_top_k = keep_top_kself.config = {- "name": "YuFaceDetectNet",+ "name": "YuNet","min_sizes": [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]],"steps": [8, 16, 32, 64],"variance": [0.1, 0.2],@@ -184,7 +182,7 @@ class FaceDetector(nn.Module):self.steps = [8, 16, 32, 64]self.variance = [0.1, 0.2]self.clip = False- self.model = YuFaceDetectNet("test", pretrained=True)+ self.model = YuNet("test", pretrained=True)self.nms = nms_korniadef preprocess(self, image: torch.Tensor) -> torch.Tensor:@@ -199,7 +197,7 @@ class FaceDetector(nn.Module):dtype=loc.dtype,) # 14- priors = _PriorBox(self.min_sizes, self.steps, self.clip, image_size=(height, width))+ priors = PriorBox(self.min_sizes, self.steps, self.clip, image_size=(height, width))priors = priors.to(loc.device, loc.dtype)batched_dets: List[torch.Tensor] = []@@ -243,194 +241,3 @@ class FaceDetector(nn.Module):img = self.preprocess(image)out = self.model(img)return self.postprocess(out, img.shape[-2], img.shape[-1])---# utils for the network---class ConvDPUnit(nn.Sequential):- def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None:- super().__init__()- self.add_module("conv1", nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=True, groups=1))- self.add_module("conv2", nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=True, groups=out_channels))- if withBNRelu:- self.add_module("bn", nn.BatchNorm2d(out_channels))- self.add_module("relu", nn.ReLU(inplace=True))---class Conv_head(nn.Sequential):- def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:- super().__init__()- self.add_module("conv1", nn.Conv2d(in_channels, mid_channels, 3, 2, 1, bias=True, groups=1))- self.add_module("bn1", nn.BatchNorm2d(mid_channels))- self.add_module("relu", nn.ReLU(inplace=True))- self.add_module("conv2", ConvDPUnit(mid_channels, out_channels))---class Conv4layerBlock(nn.Sequential):- def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None:- super().__init__()- self.add_module("conv1", ConvDPUnit(in_channels, in_channels, True))- self.add_module("conv2", ConvDPUnit(in_channels, out_channels, withBNRelu))---class YuFaceDetectNet(nn.Module):- def __init__(self, phase: str, pretrained: bool) -> None:- super().__init__()- self.phase = phase- self.num_classes = 2-- self.model0 = Conv_head(3, 16, 16)- self.model1 = Conv4layerBlock(16, 64)- self.model2 = Conv4layerBlock(64, 64)- self.model3 = Conv4layerBlock(64, 64)- self.model4 = Conv4layerBlock(64, 64)- self.model5 = Conv4layerBlock(64, 64)- self.model6 = Conv4layerBlock(64, 64)-- self.head = nn.Sequential(- Conv4layerBlock(64, 3 * (14 + 2 + 1), False),- Conv4layerBlock(64, 2 * (14 + 2 + 1), False),- Conv4layerBlock(64, 2 * (14 + 2 + 1), False),- Conv4layerBlock(64, 3 * (14 + 2 + 1), False),- )-- if self.phase == "train":- for m in self.modules():- if isinstance(m, nn.Conv2d):- if m.bias is not None:- nn.init.xavier_normal_(m.weight.data)- m.bias.data.fill_(0.02)- else:- m.weight.data.normal_(0, 0.01)- elif isinstance(m, nn.BatchNorm2d):- m.weight.data.fill_(1)- m.bias.data.zero_()-- # use torch.hub to load pretrained model- if pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(url, map_location=torch.device("cpu"))- self.load_state_dict(pretrained_dict, strict=True)- self.eval()-- def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:- detection_sources, head_list = [], []-- x = self.model0(x)- x = F.max_pool2d(x, 2)- x = self.model1(x)- x = self.model2(x)- x = F.max_pool2d(x, 2)- x = self.model3(x)- detection_sources.append(x)-- x = F.max_pool2d(x, 2)- x = self.model4(x)- detection_sources.append(x)-- x = F.max_pool2d(x, 2)- x = self.model5(x)- detection_sources.append(x)-- x = F.max_pool2d(x, 2)- x = self.model6(x)- detection_sources.append(x)-- for i, h in enumerate(self.head):- x_tmp = h(detection_sources[i])- head_list.append(x_tmp.permute(0, 2, 3, 1).contiguous())-- head_data = torch.cat([o.view(o.size(0), -1) for o in head_list], 1)- head_data = head_data.view(head_data.size(0), -1, 17)-- loc_data, conf_data, iou_data = head_data.split((14, 2, 1), dim=-1)-- if self.phase == "test":- conf_data = torch.softmax(conf_data, dim=-1)- else:- loc_data = loc_data.view(loc_data.size(0), -1, 14)- conf_data = conf_data.view(conf_data.size(0), -1, self.num_classes)- iou_data = iou_data.view(iou_data.size(0), -1, 1)-- return {"loc": loc_data, "conf": conf_data, "iou": iou_data}---# utils for post-processing---# Adapted from https://github.com/Hakuyume/chainer-ssd-def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor:- """Decode locations from predictions using priors to undo the encoding for offset regression at train time.-- Args:- loc:location predictions for loc layers. Shape: [num_priors,4].- priors: Prior boxes in center-offset form. Shape: [num_priors,4].- variances: (list[float]) Variances of priorboxes.-- Return:- Tensor containing decoded bounding box predictions.-- """- boxes = torch.cat(- (- priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4],- priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]),- priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4],- priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4],- priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4],- priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4],- priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4],- ),- 1,- )- # prepare final output- tmp = boxes[:, 0:2] - boxes[:, 2:4] / 2- return torch.cat((tmp, boxes[:, 2:4] + tmp, boxes[:, 4:]), dim=-1)---class _PriorBox:- def __init__(self, min_sizes: List[List[int]], steps: List[int], clip: bool, image_size: Tuple[int, int]) -> None:- self.min_sizes = min_sizes- self.steps = steps- self.clip = clip- self.image_size = image_size-- self.device: torch.device = torch.device("cpu")- self.dtype: torch.dtype = torch.float32-- for i in range(4):- if self.steps[i] != math.pow(2, (i + 3)):- raise ValueError("steps must be [8,16,32,64]")-- self.feature_map_2th = [int(int((self.image_size[0] + 1) / 2) / 2), int(int((self.image_size[1] + 1) / 2) / 2)]- self.feature_map_3th = [int(self.feature_map_2th[0] / 2), int(self.feature_map_2th[1] / 2)]- self.feature_map_4th = [int(self.feature_map_3th[0] / 2), int(self.feature_map_3th[1] / 2)]- self.feature_map_5th = [int(self.feature_map_4th[0] / 2), int(self.feature_map_4th[1] / 2)]- self.feature_map_6th = [int(self.feature_map_5th[0] / 2), int(self.feature_map_5th[1] / 2)]-- self.feature_maps = [self.feature_map_3th, self.feature_map_4th, self.feature_map_5th, self.feature_map_6th]-- def to(self, device: torch.device, dtype: torch.dtype) -> "_PriorBox":- self.device = device- self.dtype = dtype- return self-- def __call__(self) -> torch.Tensor:- anchors: List[float] = []- for k, f in enumerate(self.feature_maps):- min_sizes: List[int] = self.min_sizes[k]- # NOTE: the nested loop it's to make torchscript happy- for i in range(f[0]):- for j in range(f[1]):- for min_size in min_sizes:- s_kx = min_size / self.image_size[1]- s_ky = min_size / self.image_size[0]-- cx = (j + 0.5) * self.steps[k] / self.image_size[1]- cy = (i + 0.5) * self.steps[k] / self.image_size[0]- anchors += [cx, cy, s_kx, s_ky]- # back to torch land- output = torch.tensor(anchors, device=self.device, dtype=self.dtype).view(-1, 4)- if self.clip:- output = output.clamp(max=1, min=0)- return outputdiff --git a/kornia/contrib/models/__init__.py b/kornia/contrib/models/__init__.pydeleted file mode 100644index e5405927d..000000000--- a/kornia/contrib/models/__init__.py+++ /dev/null@@ -1,23 +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.-#--"""Kornia Contrib Models β Experimental and contributed model structures for Kornia.--This subpackage provides contributed model classes and result structures.-"""--from kornia.contrib.models.structures import Prompts, SegmentationResultsdiff --git a/kornia/contrib/models/base.py b/kornia/contrib/models/base.pydeleted file mode 100644index a78316d24..000000000--- a/kornia/contrib/models/base.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 __future__ import annotations--import os-from abc import ABC, abstractmethod-from typing import Any, Generic, Optional, TypeVar, cast--import torch--from kornia.core import Module--ModelConfig = TypeVar("ModelConfig")---class ModelBase(ABC, Module, Generic[ModelConfig]):- """Abstract model class with some utilities function."""-- def load_checkpoint(self, checkpoint: str, device: Optional[torch.device] = None) -> None:- """Load checkpoint from a given url or file.-- Args:- checkpoint: The url or filepath for the respective checkpoint- device: The desired device to load the weights and move the model-- """- if os.path.isfile(checkpoint):- with open(checkpoint, "rb") as f:- state_dict = torch.load(f, map_location=device)- else:- state_dict = torch.hub.load_state_dict_from_url(checkpoint, map_location=device)-- self.load_state_dict(state_dict)-- @staticmethod- @abstractmethod- def from_config(config: ModelConfig) -> ModelBase[ModelConfig]:- """Build/load the model.-- Args:- config: The specifications for the model be build/loaded-- """- raise NotImplementedError-- def compile(- self,- *,- fullgraph: bool = False,- dynamic: bool = False,- backend: str = "inductor",- mode: Optional[str] = None,- options: Optional[dict[Any, Any]] = None,- disable: bool = False,- ) -> ModelBase[ModelConfig]:- compiled = torch.compile(- self, fullgraph=fullgraph, dynamic=dynamic, backend=backend, mode=mode, options=options, disable=disable- )- compiled = cast(ModelBase[ModelConfig], compiled)- return compileddiff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex ff99a8c4c..1c1f5473a 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -17,85 +17,451 @@from __future__ import annotations-import warnings-from typing import Any--from kornia.models.detection.base import (- BoundingBox as BoundingBoxBase,-)-from kornia.models.detection.base import (- BoundingBoxDataFormat,-)-from kornia.models.detection.base import (- ObjectDetector as ObjectDetectorBase,-)-from kornia.models.detection.base import (- ObjectDetectorResult as ObjectDetectorResultBase,-)-from kornia.models.detection.base import (- results_from_detections as results_from_detections_base,-)-from kornia.models.utils import ResizePreProcessor as ResizePreProcessorBase+from dataclasses import dataclass+from enum import Enum+from typing import Any, ClassVar, List, Optional, Tuple, Union++import torch++from kornia.core import Module, Tensor, rand, tensor+from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.external import PILImage as Image+from kornia.core.external import onnx+from kornia.core.mixin.onnx import ONNXExportMixin+from kornia.models.base import ModelBase+from kornia.models.processors import ResizePreProcessor+from kornia.utils.draw import draw_rectangle__all__ = ["BoundingBox","BoundingBoxDataFormat",+ "BoxFiltering","ObjectDetector","ObjectDetectorResult",- "ResizePreProcessor",+ "RTDETRDetectorBuilder","results_from_detections",]-class BoundingBox(BoundingBoxBase):- def __init__(self, *args: Any, **kwargs: Any) -> None:- super().__init__(*args, **kwargs)- warnings.warn(- "BoundingBox is deprecated and will be removed in v0.8.0. Use kornia.models.detection.BoundingBox instead.",- DeprecationWarning,- stacklevel=1,+class BoundingBoxDataFormat(Enum):+ """Enum class that maps bounding box data format."""++ XYWH = 0+ XYXY = 1+ CXCYWH = 2+ CENTER_XYWH = 2+++# NOTE: probably we should use a more generic name like BoundingBox2D+# and add a BoundingBox3D class for 3D bounding boxes. Also for serialization+# we should have an explicit class for each format to make it more production ready+# specially to serialize to protobuf and not saturate at a high rates.+++@dataclass(frozen=True)+class BoundingBox:+ """Bounding box data class.++ Useful for representing bounding boxes in different formats for object detection.++ Args:+ data: tuple of bounding box data. The length of the tuple depends on the data format.+ data_format: bounding box data format.++ """++ data: tuple[float, float, float, float]+ data_format: BoundingBoxDataFormat+++@dataclass(frozen=True)+class ObjectDetectorResult:+ """Object detection result.++ Args:+ class_id: class id of the detected object.+ confidence: confidence score of the detected object.+ bbox: bounding box of the detected object in xywh format.++ """++ class_id: int+ confidence: float+ bbox: BoundingBox+++def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFormat) -> list[ObjectDetectorResult]:+ """Convert a detection tensor to a list of :py:class:`ObjectDetectorResult`.++ Args:+ detections: tensor with shape :math:`(D, 6)`, where :math:`D` is the number of detections in the given image,+ :math:`6` represents class id, score, and `xywh` bounding box.+ format: detection format.++ Returns:+ list of :py:class:`ObjectDetectorResult`.++ """+ KORNIA_CHECK_SHAPE(detections, ["D", "6"])++ if isinstance(format, str):+ format = BoundingBoxDataFormat[format.upper()]++ results: list[ObjectDetectorResult] = []+ for det in detections:+ det = det.squeeze().tolist()+ if len(det) != 6:+ continue+ results.append(+ ObjectDetectorResult(+ class_id=int(det[0]),+ confidence=det[1],+ bbox=BoundingBox(data=(det[2], det[3], det[4], det[5]), data_format=format),+ ))+ return results+++class ObjectDetector(ModelBase, ONNXExportMixin):+ """Wrap an object detection model and perform pre-processing and post-processing."""++ name: str = "detection"++ def __init__(self, model: Module, pre_processor: Module, post_processor: Module) -> None:+ """Initialize ObjectDetector.++ Args:+ model: The object detection model.+ pre_processor: Pre-processing module (e.g., ResizePreProcessor).+ post_processor: Post-processing module (e.g., DETRPostProcessor).+ """+ super().__init__()+ self.model = model.eval()+ self.pre_processor = pre_processor+ self.post_processor = post_processor++ @staticmethod+ def from_config(config: Any) -> ObjectDetector:+ """Build ObjectDetector from config.++ This is a placeholder to satisfy the abstract method requirement.+ Use kornia.contrib.object_detection.RTDETRDetectorBuilder.build() or instantiate ObjectDetector directly.++ Args:+ config: Configuration object (not used, kept for interface compatibility).++ Returns:+ ObjectDetector instance.++ """+ raise NotImplementedError(+ "ObjectDetector.from_config() is not implemented. "+ "Use kornia.contrib.object_detection.RtdetrBuilder.build() or instantiate ObjectDetector directly."+ )++ @torch.inference_mode()+ def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:+ """Detect objects in a given list of images.++ Args:+ images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.+ If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the+ number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.++ """+ images, images_sizes = self.pre_processor(images)+ logits, boxes = self.model(images)+ detections = self.post_processor(logits, boxes, images_sizes)+ return detections++ def visualize(+ self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, output_type: str = "torch"+ ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ """Very simple drawing.+ Needs to be more fancy later.+ """+ dets = detections or self.forward(images)+ output = []+ for image, detection in zip(images, dets):+ out_img = image[None].clone()+ for out in detection:+ out_img = draw_rectangle(+ out_img,+ torch.Tensor([[[out[-4], out[-3], out[-4] + out[-2], out[-3] + out[-1]]]]),+ )+ output.append(out_img[0])-def results_from_detections(*args: Any, **kwargs: Any) -> list[ObjectDetectorResultBase]:- """Return detector results."""- warnings.warn(- "results_from_detections is deprecated and will be removed in v0.8.0. "- "Use kornia.models.detection.results_from_detections instead.",- DeprecationWarning,- stacklevel=1,- )- return results_from_detections_base(*args, **kwargs)---class ResizePreProcessor(ResizePreProcessorBase):- def __init__(self, *args: Any, **kwargs: Any) -> None:- super().__init__(*args, **kwargs)- warnings.warn(- "ResizePreProcessor is deprecated and will be removed in v0.8.0. "- "Use kornia.models.utils.ResizePreProcessor instead.",- DeprecationWarning,- stacklevel=1,+ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))++ def save(+ self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, directory: Optional[str] = None+ ) -> None:+ """Save the output image(s) to a directory.++ Args:+ images: input tensor.+ detections: detection tensor.+ directory: directory to save the images.++ """+ outputs = self.visualize(images, detections)+ self._save_outputs(outputs, directory)++ def to_onnx( # type: ignore[override]+ self,+ onnx_name: Optional[str] = None,+ image_size: Optional[int] = 640,+ include_pre_and_post_processor: bool = True,+ save: bool = True,+ additional_metadata: Optional[list[tuple[str, str]]] = None,+ **kwargs: Any,+ ) -> onnx.ModelProto: # type: ignore+ """Export an RT-DETR object detection model to ONNX format.++ Either `model_name` or `config` must be provided. If neither is provided,+ a default pretrained model (`rtdetr_r18vd`) will be built.++ Args:+ onnx_name:+ The name of the output ONNX file. If not provided, a default name in the+ format "Kornia-<ClassName>.onnx" will be used.+ image_size:+ The size to which input images will be resized during preprocessing.+ If None, image_size will be dynamic.+ For RTDETR, recommended scales include [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].+ include_pre_and_post_processor:+ Whether to include the pre-processor and post-processor in the exported model.+ save:+ If to save the model or load it.+ additional_metadata:+ Additional metadata to add to the ONNX model.+ kwargs: Additional arguments to convert to onnx.++ """+ if onnx_name is None:+ onnx_name = f"kornia_{self.name}_{image_size}.onnx"++ return ONNXExportMixin.to_onnx(+ self,+ onnx_name,+ input_shape=[-1, 3, image_size or -1, image_size or -1],+ output_shape=[-1, -1, 6],+ pseudo_shape=[1, 3, image_size or 352, image_size or 352],+ model=self if include_pre_and_post_processor else self.model,+ save=save,+ additional_metadata=additional_metadata,+ **kwargs,+ )++ def compile(+ self,+ *,+ fullgraph: bool = False,+ dynamic: bool = False,+ backend: str = "inductor",+ mode: Optional[str] = None,+ options: Optional[dict[str, str | int | bool]] = None,+ disable: bool = False,+ ) -> None:+ """Compile the internal object detection model with :py:func:`torch.compile()`."""+ self.model = torch.compile( # type: ignore+ self.model,+ fullgraph=fullgraph,+ dynamic=dynamic,+ backend=backend,+ mode=mode,+ options=options,+ disable=disable,)-class ObjectDetector(ObjectDetectorBase):- def __init__(self, *args: Any, **kwargs: Any) -> None:- super().__init__(*args, **kwargs)- warnings.warn(- "ObjectDetector is deprecated and will be removed in v0.8.0. "- "Use kornia.models.detection.ObjectDetector instead.",- DeprecationWarning,- stacklevel=1,+class BoxFiltering(Module, ONNXExportMixin):+ """Filter boxes according to the desired threshold.++ Args:+ confidence_threshold: an 0-d scalar that represents the desired threshold.+ classes_to_keep: a 1-d list of classes to keep. If None, keep all classes.+ filter_as_zero: whether to filter boxes as zero.++ """++ ONNX_DEFAULT_INPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]+ ONNX_EXPORT_PSEUDO_SHAPE: ClassVar[List[int]] = [5, 20, 6]++ def __init__(+ self,+ confidence_threshold: Optional[Union[Tensor, float]] = None,+ classes_to_keep: Optional[Union[Tensor, List[int]]] = None,+ filter_as_zero: bool = False,+ ) -> None:+ super().__init__()+ self.filter_as_zero = filter_as_zero+ self.classes_to_keep = None+ self.confidence_threshold = None+ if classes_to_keep is not None:+ self.classes_to_keep = classes_to_keep if isinstance(classes_to_keep, Tensor) else tensor(classes_to_keep)+ if confidence_threshold is not None:+ self.confidence_threshold = (+ confidence_threshold or confidence_threshold+ if isinstance(confidence_threshold, Tensor)+ else tensor(confidence_threshold)+ )++ def forward(+ self, boxes: Tensor, confidence_threshold: Optional[Tensor] = None, classes_to_keep: Optional[Tensor] = None+ ) -> Union[Tensor, List[Tensor]]:+ """Filter boxes according to the desired threshold.++ To be ONNX-friendly, the inputs for direct forwarding need to be all tensors.++ Args:+ boxes: [B, D, 6], where B is the batchsize, D is the number of detections in the image,+ 6 represent (class_id, confidence_score, x, y, w, h).+ confidence_threshold: an 0-d scalar that represents the desired threshold.+ classes_to_keep: a 1-d tensor of classes to keep. If None, keep all classes.++ Returns:+ Union[Tensor, List[Tensor]]+ If `filter_as_zero` is True, return a tensor of shape [D, 6], where D is the total number of+ detections as input.+ If `filter_as_zero` is False, return a list of tensors of shape [D, 6], where D is the number of+ valid detections for each element in the batch.++ """+ # Apply confidence filtering+ zero_tensor = tensor(0.0, device=boxes.device, dtype=boxes.dtype)+ confidence_threshold = (+ confidence_threshold or self.confidence_threshold or zero_tensor+ ) # If None, use 0 as threshold+ confidence_mask = boxes[:, :, 1] > confidence_threshold # [B, D]++ # Apply class filtering+ classes_to_keep = classes_to_keep or self.classes_to_keep+ if classes_to_keep is not None:+ class_ids = boxes[:, :, 0:1] # [B, D, 1]+ classes_to_keep = classes_to_keep.view(1, 1, -1) # [1, 1, C] for broadcasting+ class_mask = (class_ids == classes_to_keep).any(dim=-1) # [B, D]+ else:+ # If no class filtering is needed, just use a mask of all `True`+ class_mask = (confidence_mask * 0 + 1).bool()++ # Combine the confidence and class masks+ combined_mask = confidence_mask & class_mask # [B, D]++ if self.filter_as_zero:+ filtered_boxes = boxes * combined_mask[:, :, None]+ return filtered_boxes++ filtered_boxes_list = []+ for i in range(boxes.shape[0]):+ box = boxes[i]+ mask = combined_mask[i] # [D]+ valid_boxes = box[mask]+ filtered_boxes_list.append(valid_boxes)++ return filtered_boxes_list++ def _create_dummy_input(+ self, input_shape: List[int], pseudo_shape: Optional[List[int]] = None+ ) -> Union[Tuple[Any, ...], Tensor]:+ pseudo_input = rand(+ *[+ ((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim)+ for i, dim in enumerate(input_shape)+ ])+ if self.confidence_threshold is None:+ return pseudo_input, 0.1+ return pseudo_input+++class RTDETRDetectorBuilder:+ """A builder class for constructing RT-DETR object detection models.++ This class provides static methods to:+ - 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)+ """++ @staticmethod+ def build(+ model_name: Optional[str] = None,+ config: Optional[Any] = None,+ pretrained: bool = True,+ image_size: Optional[int] = None,+ confidence_threshold: Optional[float] = None,+ confidence_filtering: Optional[bool] = None,+ ) -> ObjectDetector:+ """Build and returns an RT-DETR object detector model.++ Either `model_name` or `config` must be provided. If neither is provided,+ a default pretrained model (`rtdetr_r18vd`) will be built.++ Args:+ model_name:+ Name of the RT-DETR model to load. Can be one of the available pretrained models.+ Including 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.+ config:+ A custom configuration object for building the RT-DETR model.+ pretrained:+ Whether to load a pretrained version of the model (applies when `model_name` is provided).+ image_size:+ The size to which input images will be resized during preprocessing.+ If None, no resizing will be inferred from config file. Recommended scales include+ [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].+ confidence_threshold: Threshold to filter results based on confidence scores.+ confidence_filtering: Whether to filter results based on confidence scores.+++ Returns:+ ObjectDetector+ An object detector instance initialized with the specified model, preprocessor, and post-processor.++ """+ import warnings++ from kornia.models.rt_detr import DETRPostProcessor+ from kornia.models.rt_detr.model import RTDETR, RTDETRConfig++ if model_name is not None and config is not None:+ raise ValueError("Either `model_name` or `config` should be `None`.")++ if config is not None:+ model = RTDETR.from_config(config)+ image_size = image_size or config.input_size+ elif model_name is not None:+ if pretrained:+ model = RTDETR.from_pretrained(model_name)+ image_size = RTDETRConfig.from_name(model_name).input_size+ else:+ model = RTDETR.from_name(model_name)+ image_size = RTDETRConfig.from_name(model_name).input_size+ else:+ warnings.warn("No `model_name` or `config` found. Will build pretrained `rtdetr_r18vd`.", stacklevel=1)+ model = RTDETR.from_pretrained("rtdetr_r18vd")+ image_size = RTDETRConfig.from_name("rtdetr_r18vd").input_size+ if confidence_threshold is None:+ confidence_threshold = config.confidence_threshold if config is not None else 0.3-class ObjectDetectorResult(ObjectDetectorResultBase):- def __init__(self, *args: Any, **kwargs: Any) -> None:- super().__init__(*args, **kwargs)- warnings.warn(- "ObjectDetectorResult is deprecated and will be removed in v0.8.0. "- "Use kornia.models.detection.ObjectDetectorResult instead.",- DeprecationWarning,- stacklevel=1,+ return ObjectDetector(+ model,+ ResizePreProcessor(image_size, image_size),+ DETRPostProcessor(+ confidence_threshold=confidence_threshold,+ confidence_filtering=confidence_filtering or not torch.onnx.is_in_onnx_export(),+ num_classes=model.decoder.num_classes,+ num_top_queries=model.decoder.num_queries,+ ),)diff --git a/kornia/models/super_resolution/base.py b/kornia/contrib/super_resolution.pysimilarity index 57%rename from kornia/models/super_resolution/base.pyrename to kornia/contrib/super_resolution.pyindex 42e9355dd..b012626e9 100644--- a/kornia/models/super_resolution/base.py+++ b/kornia/contrib/super_resolution.py@@ -18,17 +18,30 @@from typing import Any, List, Optional, Tuple, Unionimport torch+from torch import nn+from kornia.config import kornia_configfrom kornia.core import Tensorfrom kornia.core.external import PILImage as Image-from kornia.core.external import onnx+from kornia.core.external import basicsr, onnx+from kornia.core.mixin.onnx import ONNXExportMixinfrom kornia.models.base import ModelBase+from kornia.models.processors import OutputRangePostProcessor, ResizePreProcessor+from kornia.models.small_sr import SmallSRNetWrapper+from kornia.utils.download import CachedDownloader-__all__ = ["SuperResolution"]+__all__ = ["RRDBNetBuilder", "SmallSRBuilder", "SuperResolution"]++URLs = {+ "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",+ "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",+ "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",+ "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",+}# TODO: support patching -> SR -> unpatching pipeline-class SuperResolution(ModelBase):+class SuperResolution(ModelBase, ONNXExportMixin):"""SuperResolution is a module that wraps an super resolution model."""name: str = "super_resolution"@@ -49,13 +62,7 @@ class SuperResolution(ModelBase):"""output = self.pre_processor(images)- if isinstance(- output,- (- list,- tuple,- ),- ):+ if isinstance(output, list | tuple):images = output[0]else:images = output@@ -143,7 +150,8 @@ class SuperResolution(ModelBase):if onnx_name is None:onnx_name = f"kornia_{self.name}.onnx"- return super().to_onnx(+ return ONNXExportMixin.to_onnx(+ self,onnx_name,input_shape=[-1, 3, self.input_image_size or -1, self.input_image_size or -1],output_shape=[-1, 3, self.output_image_size or -1, self.output_image_size or -1],@@ -153,3 +161,70 @@ class SuperResolution(ModelBase):additional_metadata=additional_metadata,**kwargs,)+++class RRDBNetBuilder:+ @staticmethod+ def build(model_name: str = "RealESRNet_x4plus", pretrained: bool = True) -> SuperResolution:+ if model_name == "RealESRGAN_x4plus":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4+ )+ elif model_name == "RealESRNet_x4plus":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4+ )+ elif model_name == "RealESRGAN_x4plus_anime_6B":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4+ )+ elif model_name == "RealESRGAN_x2plus":+ model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore+ num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2+ )+ else:+ raise ValueError(+ f"Model {model_name} not found. Please choose from "+ "'RealESRGAN_x4plus', 'RealESRNet_x4plus', 'RealESRGAN_x4plus_anime_6B', 'RealESRGAN_x2plus'."+ )++ model_path = None+ if pretrained:+ url = URLs[model_name]+ model_path = CachedDownloader.download_to_cache(+ url, model_name, download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir+ )+ model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu"))["params_ema"], strict=True)+ model.eval()++ return SuperResolution(+ model,+ pre_processor=nn.Identity(),+ post_processor=OutputRangePostProcessor(min_val=0.0, max_val=1.0),+ name=model_name,+ )+++class SmallSRBuilder:+ @staticmethod+ def build(+ model_name: str = "small_sr", pretrained: bool = True, upscale_factor: int = 3, image_size: Optional[int] = None+ ) -> SuperResolution:+ if model_name.lower() == "small_sr":+ model = SmallSRNetWrapper(upscale_factor, pretrained=pretrained)+ else:+ raise ValueError(f"Model {model_name} not found. Please choose from 'small_sr'.")++ sr = SuperResolution(+ model,+ pre_processor=ResizePreProcessor(224, 224),+ post_processor=nn.Identity(),+ name=model_name,+ )+ if image_size is None:+ sr.pseudo_image_size = 224+ else:+ sr.input_image_size = image_size+ sr.output_image_size = image_size * 3+ sr.pseudo_image_size = image_size+ return srdiff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.pyindex d1aab6728..e2d7fb224 100644--- a/kornia/contrib/visual_prompter.py+++ b/kornia/contrib/visual_prompter.py@@ -23,13 +23,13 @@ import torchfrom kornia.augmentation import LongestMaxSizefrom kornia.augmentation.container.augment import AugmentationSequential-from kornia.contrib.models import Prompts, SegmentationResults-from kornia.contrib.models.sam import Sam, SamConfigfrom kornia.core import Tensor, pad, tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.enhance import normalizefrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints+from kornia.models.sam import Sam, SamConfig+from kornia.models.structures import Prompts, SegmentationResultsclass VisualPrompter:diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex 183dafaa9..3e7c5d898 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -33,7 +33,6 @@ from .blur_pool import (max_blur_pool2d,)from .canny import Canny, canny-from .dexined import DexiNedfrom .dissolving import StableDiffusionDissolvingfrom .filter import filter2d, filter2d_separable, filter3dfrom .gaussian import GaussianBlur2d, gaussian_blur2d, gaussian_blur2d_t@@ -75,7 +74,6 @@ __all__ = ["BlurPool2D","BoxBlur","Canny",- "DexiNed","EdgeAwareBlurPool2D","GaussianBlur2d","GuidedBlur",diff --git a/kornia/models/__init__.py b/kornia/models/__init__.pyindex c8bdff143..76d8e063b 100644--- a/kornia/models/__init__.py+++ b/kornia/models/__init__.py@@ -17,16 +17,6 @@"""Models submodule for Kornia.-This package provides model architectures and utilities for tasks such as depth estimation,-detection, segmentation, super-resolution, and tracking.+This package provides model architectures and utilities for state-of-the-art models for Visual Language+Models and Vision Language Action Models."""--from . import (- depth_estimation,- detection,- edge_detection,- segmentation,- super_resolution,- tracking,-)-from .utils import *diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.pyindex c9532e0aa..0e5a15adb 100644--- a/kornia/models/_hf_models/hf_onnx_community.py+++ b/kornia/models/_hf_models/hf_onnx_community.py@@ -20,8 +20,10 @@ from __future__ import annotationsimport osfrom typing import Any, Optional+import torch+from kornia.config import kornia_config-from kornia.core import ImageSequential, Tensor+from kornia.core import ImageSequentialfrom kornia.core.external import onnxfrom kornia.geometry.transform import resizefrom kornia.models.base import ModelBaseMixin@@ -115,7 +117,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):self.pre_processor = pre_processorself.post_processor = post_processor- def resize_back(self, images: Tensor, target_images: Tensor) -> Tensor:+ def resize_back(self, images: torch.Tensor, target_images: torch.Tensor) -> torch.Tensor:"""Resize the input images back to the original size of target images.Args:@@ -126,7 +128,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):The resized images."""- if isinstance(target_images, Tensor):+ if isinstance(target_images, torch.Tensor):return resize(images, target_images.shape[-2:])raise RuntimeErrordiff --git a/kornia/models/_hf_models/preprocessor.py b/kornia/models/_hf_models/preprocessor.pyindex fb9f23483..c0af70748 100644--- a/kornia/models/_hf_models/preprocessor.py+++ b/kornia/models/_hf_models/preprocessor.py@@ -19,7 +19,10 @@ from __future__ import annotationsfrom typing import Any-from kornia.core import ImageSequential, Module, Tensor, tensor+import torch+from torch import nn++from kornia.core import ImageSequentialfrom kornia.enhance.normalize import Normalizefrom kornia.enhance.rescale import Rescalefrom kornia.geometry.transform import Resize@@ -27,7 +30,7 @@ from kornia.geometry.transform import Resizeclass PreprocessingLoader:@staticmethod- def normalize(mean: Tensor, std: Tensor) -> Normalize:+ def normalize(mean: torch.Tensor, std: torch.Tensor) -> Normalize:return Normalize(mean=mean, std=std)@staticmethod@@ -48,7 +51,7 @@ class PreprocessingLoader:class DPTImageProcessor(PreprocessingLoader):@staticmethoddef from_json(json_data: dict[str, Any]) -> ImageSequential:- preproc_list: list[Module] = []+ preproc_list: list[nn.Module] = []if json_data["do_pad"]:raise NotImplementedErrorif json_data["do_resize"]:@@ -61,7 +64,7 @@ class DPTImageProcessor(PreprocessingLoader):if json_data["do_normalize"]:preproc_list.append(PreprocessingLoader.normalize(- mean=tensor([json_data["image_mean"]]), std=tensor([json_data["image_std"]])+ mean=torch.tensor([json_data["image_mean"]]), std=torch.tensor([json_data["image_std"]])))return ImageSequential(*preproc_list)diff --git a/kornia/models/base.py b/kornia/models/base.pyindex a53a05e42..729cf0cb4 100644--- a/kornia/models/base.py+++ b/kornia/models/base.py@@ -15,27 +15,32 @@# limitations under the License.#+from __future__ import annotations+import datetimeimport loggingimport os-from typing import List, Optional, Union+from abc import ABC, abstractmethod+from typing import Any, Generic, List, Optional, TypeVar, Union, cast++import torch+from torch import nn-from kornia.core import Module, Tensor, stackfrom kornia.core.external import PILImage as Image-from kornia.core.external import numpy as np-from kornia.core.mixin.onnx import ONNXExportMixinfrom kornia.io import write_imagefrom kornia.utils.image import tensor_to_imagelogger = logging.getLogger(__name__)+ModelConfig = TypeVar("ModelConfig")+class ModelBaseMixin:name: str = "model"def _tensor_to_type(- self, output: Union[Tensor, List[Tensor]], output_type: str, is_batch: bool = False- ) -> Union[Tensor, List[Tensor], List["Image.Image"]]: # type: ignore+ self, output: Union[torch.Tensor, List[torch.Tensor]], output_type: str, is_batch: bool = False+ ) -> Union[torch.Tensor, List[torch.Tensor], List[Image.Image]]: # type: ignore"""Convert the output tensor to the desired type.Args:@@ -51,63 +56,100 @@ class ModelBaseMixin:"""if output_type == "torch":- if is_batch and not isinstance(output, Tensor):- return stack(output)- elif is_batch and isinstance(output, Tensor):- return output- elif not is_batch and isinstance(output, Tensor):- return list(output)- elif not is_batch and not isinstance(output, Tensor):- return outputreturn outputelif output_type == "pil":- out = [Image.fromarray((tensor_to_image(out_img) * 255).astype(np.uint8)) for out_img in output] # type: ignore- return list(out)+ if isinstance(output, list):+ return [tensor_to_image(t) for t in output]+ else:+ return tensor_to_image(output)+ else:+ raise RuntimeError(f"Output type {output_type} is not supported. Accepted values are 'torch' and 'pil'.")- raise RuntimeError(f"Unsupported output type `{output_type}`.")+ def save(self, output: Union[torch.Tensor, List[torch.Tensor]], directory: str, is_batch: bool = False) -> None:+ """Save the output tensor to a directory.++ Args:+ output: The output tensor or list of tensors.+ directory: The directory to save the output.+ is_batch: If True, the output is expected to be a batch of tensors.++ """+ os.makedirs(directory, exist_ok=True)+ timestamp = datetime.datetime.now(tz=datetime.UTC).strftime("%Y%m%d_%H%M%S")+ if isinstance(output, list):+ for i, out in enumerate(output):+ write_image(out, os.path.join(directory, f"{self.name}_{timestamp}_{i}.png"))+ else:+ write_image(output, os.path.join(directory, f"{self.name}_{timestamp}.png"))+ logger.info(f"Outputs are saved in {directory}")def _save_outputs(- self, outputs: Union[Tensor, List[Tensor]], directory: Optional[str] = None, suffix: str = ""+ self, output: Union[torch.Tensor, List[torch.Tensor]], directory: Optional[str] = None, suffix: str = "") -> None:- """Save the output image(s) to a directory.+ """Save the output tensor to a directory with an optional suffix.Args:- outputs: output tensor.- directory: directory to save the images.- suffix: filename suffix.+ output: The output tensor or list of tensors.+ directory: The directory to save the output. If None, a default directory is used.+ suffix: Optional suffix to add to the filename."""if directory is None:- name = f"{self.name}_{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}"+ name = f"{self.name}{suffix}_{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}"directory = os.path.join("kornia_outputs", name)os.makedirs(directory, exist_ok=True)- for i, out_image in enumerate(outputs):- write_image(- os.path.join(directory, f"{str(i).zfill(6)}{suffix}.jpg"),- out_image.mul(255.0).byte(),- )+ timestamp = datetime.datetime.now(tz=datetime.UTC).strftime("%Y%m%d_%H%M%S")+ if isinstance(output, list):+ for i, out in enumerate(output):+ write_image(out, os.path.join(directory, f"{self.name}{suffix}_{timestamp}_{i}.png"))+ else:+ write_image(output, os.path.join(directory, f"{self.name}{suffix}_{timestamp}.png"))logger.info(f"Outputs are saved in {directory}")-class ModelBase(Module, ONNXExportMixin, ModelBaseMixin):- """Wrap a model and perform pre-processing and post-processing."""+class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):+ """Abstract model class with some utilities function."""- def __init__(- self, model: Module, pre_processor: Module, post_processor: Module, name: Optional[str] = None- ) -> None:- """Construct an Object Detector object.+ def load_checkpoint(self, checkpoint: str, device: Optional[torch.device] = None) -> None:+ """Load checkpoint from a given url or file.++ Args:+ checkpoint: The url or filepath for the respective checkpoint+ device: The desired device to load the weights and move the model++ """+ if os.path.isfile(checkpoint):+ with open(checkpoint, "rb") as f:+ state_dict = torch.load(f, map_location=device)+ else:+ state_dict = torch.hub.load_state_dict_from_url(checkpoint, map_location=device)++ self.load_state_dict(state_dict)++ @staticmethod+ @abstractmethod+ def from_config(config: ModelConfig) -> ModelBase[ModelConfig]:+ """Build/load the model.Args:- model: an object detection model.- pre_processor: a pre-processing module- post_processor: a post-processing module.- name: name of a model.+ config: The specifications for the model be build/loaded"""- super().__init__()- self.model = model.eval()- self.pre_processor = pre_processor.eval()- self.post_processor = post_processor.eval()- if name is not None:- self.name = name+ raise NotImplementedError++ def compile(+ self,+ *,+ fullgraph: bool = False,+ dynamic: bool = False,+ backend: str = "inductor",+ mode: Optional[str] = None,+ options: Optional[dict[Any, Any]] = None,+ disable: bool = False,+ ) -> ModelBase[ModelConfig]:+ compiled = torch.compile(+ self, fullgraph=fullgraph, dynamic=dynamic, backend=backend, mode=mode, options=options, disable=disable+ )+ compiled = cast(ModelBase[ModelConfig], compiled)+ return compileddiff --git a/kornia/contrib/models/common.py b/kornia/models/common.pysimilarity index 91%rename from kornia/contrib/models/common.pyrename to kornia/models/common.pyindex 176d3ab96..9df194052 100644--- a/kornia/contrib/models/common.py+++ b/kornia/models/common.py@@ -21,8 +21,6 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core import Module, Tensor, pad-class ConvNormAct(nn.Sequential):def __init__(@@ -60,7 +58,7 @@ class ConvNormAct(nn.Sequential):# Lightly adapted from# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py-class MLP(Module):+class MLP(nn.Module):def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False) -> None:@@ -70,7 +68,7 @@ class MLP(Module):self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim, *h], [*h, output_dim]))self.sigmoid_output = sigmoid_output- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:for i, layer in enumerate(self.layers):x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)if self.sigmoid_output:@@ -80,7 +78,7 @@ class MLP(Module):# Adapted from timm# https://github.com/huggingface/pytorch-image-models/blob/v0.9.2/timm/layers/drop.py#L137-class DropPath(Module):+class DropPath(nn.Module):"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True) -> None:@@ -88,7 +86,7 @@ class DropPath(Module):self.drop_prob = drop_probself.scale_by_keep = scale_by_keep- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:if self.drop_prob == 0.0 or not self.training:return xkeep_prob = 1 - self.drop_prob@@ -101,14 +99,14 @@ class DropPath(Module):# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa-class LayerNorm2d(Module):+class LayerNorm2d(nn.Module):def __init__(self, num_channels: int, eps: float = 1e-6) -> None:super().__init__()self.weight = nn.Parameter(torch.ones(num_channels))self.bias = nn.Parameter(torch.zeros(num_channels))self.eps = eps- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:u = x.mean(1, keepdim=True)s = (x - u).pow(2).mean(1, keepdim=True)x = (x - u) / (s + self.eps).sqrt()@@ -116,7 +114,7 @@ class LayerNorm2d(Module):return x-def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, int]]:+def window_partition(x: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:"""Partition into non-overlapping windows with padding if needed.Args:@@ -133,7 +131,7 @@ def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, inpad_h = (window_size - H % window_size) % window_sizepad_w = (window_size - W % window_size) % window_sizeif pad_h > 0 or pad_w > 0:- x = pad(x, (0, 0, 0, pad_w, 0, pad_h))+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))Hp, Wp = H + pad_h, W + pad_wx = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)@@ -141,7 +139,9 @@ def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, inreturn windows, (Hp, Wp)-def window_unpartition(windows: Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int]) -> Tensor:+def window_unpartition(+ windows: torch.Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int]+) -> torch.Tensor:"""Window unpartition into original sequences and removing padding.Args:diff --git a/kornia/models/depth_estimation/base.py b/kornia/models/depth_estimation/base.pyindex ace99d33a..3953d9ef7 100644--- a/kornia/models/depth_estimation/base.py+++ b/kornia/models/depth_estimation/base.py@@ -19,8 +19,9 @@ from __future__ import annotationsfrom typing import Optional, Union+import torch+from kornia.color.gray import grayscale_to_rgb-from kornia.core import Tensor, tensorfrom kornia.core.external import PILImage as Imagefrom kornia.models._hf_models import HFONNXComunnityModel@@ -30,12 +31,12 @@ __all__ = ["DepthEstimation"]class DepthEstimation(HFONNXComunnityModel):name: str = "depth_estimation"- def __call__(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]: # type: ignore[override]+ def __call__(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]: # type: ignore[override]"""Detect objects in a given list of images.Args:- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.+ images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.Returns:list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the@@ -51,23 +52,23 @@ class DepthEstimation(HFONNXComunnityModel):):results = [super(DepthEstimation, self).__call__(image[None].cpu().numpy())[0] for image in images]results = [- self.resize_back(tensor(result, device=image.device, dtype=image.dtype), image)+ self.resize_back(torch.tensor(result, device=image.device, dtype=image.dtype), image)for result, image in zip(results, images)]return resultsresult = super().__call__(images.cpu().numpy())[0]- result = tensor(result, device=images.device, dtype=images.dtype)+ result = torch.tensor(result, device=images.device, dtype=images.dtype)return self.resize_back(result, images)def visualize(self,- images: Tensor,- depth_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ images: torch.Tensor,+ depth_maps: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,output_type: str = "torch",depth_type: str = "relative",max_depth: int = 80,- ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore"""Draw the segmentation results.Args:@@ -93,12 +94,12 @@ class DepthEstimation(HFONNXComunnityModel):raise ValueError(f"Unsupported depth type `{depth_type}`.")output.append(grayscale_to_rgb(depth_map))- return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))+ return self._tensor_to_type(output, output_type, is_batch=isinstance(images, torch.Tensor))def save(self,- images: Tensor,- depth_maps: Optional[Union[Tensor, list[Tensor]]] = None,+ images: torch.Tensor,+ depth_maps: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,directory: Optional[str] = None,output_type: str = "torch",depth_type: str = "relative",diff --git a/kornia/models/detection/__init__.py b/kornia/models/detection/__init__.pydeleted file mode 100644index ca1c992b4..000000000--- a/kornia/models/detection/__init__.py+++ /dev/null@@ -1,25 +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.-#--"""Detection models submodule for Kornia.--This package provides model architectures and utilities for object detection tasks.-"""--from .base import *-from .rtdetr import *-from .utils import *diff --git a/kornia/models/detection/base.py b/kornia/models/detection/base.pydeleted file mode 100644index 79557b572..000000000--- a/kornia/models/detection/base.py+++ /dev/null@@ -1,242 +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 __future__ import annotations--from dataclasses import dataclass-from enum import Enum-from typing import Any, Optional, Union--import torch--from kornia.core import Tensor-from kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.core.external import PILImage as Image-from kornia.core.external import onnx-from kornia.models.base import ModelBase-from kornia.utils.draw import draw_rectangle--__all__ = [- "BoundingBox",- "BoundingBoxDataFormat",- "ObjectDetector",- "ObjectDetectorResult",- "results_from_detections",-]---class BoundingBoxDataFormat(Enum):- """Enum class that maps bounding box data format."""-- XYWH = 0- XYXY = 1- CXCYWH = 2- CENTER_XYWH = 2---# NOTE: probably we should use a more generic name like BoundingBox2D-# and add a BoundingBox3D class for 3D bounding boxes. Also for serialization-# we should have an explicit class for each format to make it more production ready-# specially to serialize to protobuf and not saturate at a high rates.---@dataclass(frozen=True)-class BoundingBox:- """Bounding box data class.-- Useful for representing bounding boxes in different formats for object detection.-- Args:- data: tuple of bounding box data. The length of the tuple depends on the data format.- data_format: bounding box data format.-- """-- data: tuple[float, float, float, float]- data_format: BoundingBoxDataFormat---@dataclass(frozen=True)-class ObjectDetectorResult:- """Object detection result.-- Args:- class_id: class id of the detected object.- confidence: confidence score of the detected object.- bbox: bounding box of the detected object in xywh format.-- """-- class_id: int- confidence: float- bbox: BoundingBox---def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFormat) -> list[ObjectDetectorResult]:- """Convert a detection tensor to a list of :py:class:`ObjectDetectorResult`.-- Args:- detections: tensor with shape :math:`(D, 6)`, where :math:`D` is the number of detections in the given image,- :math:`6` represents class id, score, and `xywh` bounding box.- format: detection format.-- Returns:- list of :py:class:`ObjectDetectorResult`.-- """- KORNIA_CHECK_SHAPE(detections, ["D", "6"])-- if isinstance(format, str):- format = BoundingBoxDataFormat[format.upper()]-- results: list[ObjectDetectorResult] = []- for det in detections:- det = det.squeeze().tolist()- if len(det) != 6:- continue- results.append(- ObjectDetectorResult(- class_id=int(det[0]),- confidence=det[1],- bbox=BoundingBox(data=(det[2], det[3], det[4], det[5]), data_format=format),- )- )- return results---class ObjectDetector(ModelBase):- """Wrap an object detection model and perform pre-processing and post-processing."""-- name: str = "detection"-- @torch.inference_mode()- def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:- """Detect objects in a given list of images.-- Args:- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.-- Returns:- list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the- number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.-- """- images, images_sizes = self.pre_processor(images)- logits, boxes = self.model(images)- detections = self.post_processor(logits, boxes, images_sizes)- return detections-- def visualize(- self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, output_type: str = "torch"- ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore- """Very simple drawing.-- Needs to be more fancy later.- """- dets = detections or self.forward(images)- output = []- for image, detection in zip(images, dets):- out_img = image[None].clone()- for out in detection:- out_img = draw_rectangle(- out_img,- torch.Tensor([[[out[-4], out[-3], out[-4] + out[-2], out[-3] + out[-1]]]]),- )- output.append(out_img[0])-- return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))-- def save(- self, images: Union[Tensor, list[Tensor]], detections: Optional[Tensor] = None, directory: Optional[str] = None- ) -> None:- """Save the output image(s) to a directory.-- Args:- images: input tensor.- detections: detection tensor.- directory: directory to save the images.-- """- outputs = self.visualize(images, detections)- self._save_outputs(outputs, directory)-- def to_onnx( # type: ignore[override]- self,- onnx_name: Optional[str] = None,- image_size: Optional[int] = 640,- include_pre_and_post_processor: bool = True,- save: bool = True,- additional_metadata: Optional[list[tuple[str, str]]] = None,- **kwargs: Any,- ) -> onnx.ModelProto: # type: ignore- """Export an RT-DETR object detection model to ONNX format.-- Either `model_name` or `config` must be provided. If neither is provided,- a default pretrained model (`rtdetr_r18vd`) will be built.-- Args:- onnx_name:- The name of the output ONNX file. If not provided, a default name in the- format "Kornia-<ClassName>.onnx" will be used.- image_size:- The size to which input images will be resized during preprocessing.- If None, image_size will be dynamic.- For RTDETR, recommended scales include [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].- include_pre_and_post_processor:- Whether to include the pre-processor and post-processor in the exported model.- save:- If to save the model or load it.- additional_metadata:- Additional metadata to add to the ONNX model.- kwargs: Additional arguments to convert to onnx.-- """- if onnx_name is None:- onnx_name = f"kornia_{self.name}_{image_size}.onnx"-- return super().to_onnx(- onnx_name,- input_shape=[-1, 3, image_size or -1, image_size or -1],- output_shape=[-1, -1, 6],- pseudo_shape=[1, 3, image_size or 352, image_size or 352],- model=self if include_pre_and_post_processor else self.model,- save=save,- additional_metadata=additional_metadata,- **kwargs,- )-- def compile(- self,- *,- fullgraph: bool = False,- dynamic: bool = False,- backend: str = "inductor",- mode: Optional[str] = None,- options: Optional[dict[str, str | int | bool]] = None,- disable: bool = False,- ) -> None:- """Compile the internal object detection model with :py:func:`torch.compile()`."""- self.model = torch.compile( # type: ignore- self.model,- fullgraph=fullgraph,- dynamic=dynamic,- backend=backend,- mode=mode,- options=options,- disable=disable,- )diff --git a/kornia/models/detection/rtdetr.py b/kornia/models/detection/rtdetr.pydeleted file mode 100644index e812e029c..000000000--- a/kornia/models/detection/rtdetr.py+++ /dev/null@@ -1,110 +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 warnings-from typing import Optional--import torch--from kornia.contrib.models.rt_detr import DETRPostProcessor-from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig-from kornia.models.detection.base import ObjectDetector-from kornia.models.utils import ResizePreProcessor--__all__ = ["RTDETRDetectorBuilder"]---class RTDETRDetectorBuilder:- """A builder class for constructing RT-DETR object detection models.-- This class provides static methods to:- - 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)- """-- @staticmethod- def build(- model_name: Optional[str] = None,- config: Optional[RTDETRConfig] = None,- pretrained: bool = True,- image_size: Optional[int] = None,- confidence_threshold: Optional[float] = None,- confidence_filtering: Optional[bool] = None,- ) -> ObjectDetector:- """Build and returns an RT-DETR object detector model.-- Either `model_name` or `config` must be provided. If neither is provided,- a default pretrained model (`rtdetr_r18vd`) will be built.-- Args:- model_name:- Name of the RT-DETR model to load. Can be one of the available pretrained models.- Including 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.- config:- A custom configuration object for building the RT-DETR model.- pretrained:- Whether to load a pretrained version of the model (applies when `model_name` is provided).- image_size:- The size to which input images will be resized during preprocessing.- If None, no resizing will be inferred from config file. Recommended scales include- [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].- confidence_threshold: Threshold to filter results based on confidence scores.- confidence_filtering: Whether to filter results based on confidence scores.--- Returns:- ObjectDetector- An object detector instance initialized with the specified model, preprocessor, and post-processor.-- """- if model_name is not None and config is not None:- raise ValueError("Either `model_name` or `config` should be `None`.")-- if config is not None:- model = RTDETR.from_config(config)- image_size = image_size or config.input_size- elif model_name is not None:- if pretrained:- model = RTDETR.from_pretrained(model_name)- image_size = RTDETRConfig.from_name(model_name).input_size- else:- model = RTDETR.from_name(model_name)- image_size = RTDETRConfig.from_name(model_name).input_size- else:- warnings.warn("No `model_name` or `config` found. Will build pretrained `rtdetr_r18vd`.", stacklevel=1)- model = RTDETR.from_pretrained("rtdetr_r18vd")- image_size = RTDETRConfig.from_name("rtdetr_r18vd").input_size-- if confidence_threshold is None:- confidence_threshold = config.confidence_threshold if config is not None else 0.3-- return ObjectDetector(- model,- ResizePreProcessor(image_size, image_size),- DETRPostProcessor(- confidence_threshold=confidence_threshold,- confidence_filtering=confidence_filtering or not torch.onnx.is_in_onnx_export(),- num_classes=model.decoder.num_classes,- num_top_queries=model.decoder.num_queries,- ),- )diff --git a/kornia/models/detection/utils.py b/kornia/models/detection/utils.pydeleted file mode 100644index c7db63154..000000000--- a/kornia/models/detection/utils.py+++ /dev/null@@ -1,124 +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, ClassVar, List, Optional, Tuple, Union--from kornia.core import Module, Tensor, rand, tensor-from kornia.core.mixin.onnx import ONNXExportMixin--__all__ = ["BoxFiltering"]---class BoxFiltering(Module, ONNXExportMixin):- """Filter boxes according to the desired threshold.-- Args:- confidence_threshold: an 0-d scalar that represents the desired threshold.- classes_to_keep: a 1-d list of classes to keep. If None, keep all classes.- filter_as_zero: whether to filter boxes as zero.-- """-- ONNX_DEFAULT_INPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]- ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[List[int]] = [-1, -1, 6]- ONNX_EXPORT_PSEUDO_SHAPE: ClassVar[List[int]] = [5, 20, 6]-- def __init__(- self,- confidence_threshold: Optional[Union[Tensor, float]] = None,- classes_to_keep: Optional[Union[Tensor, List[int]]] = None,- filter_as_zero: bool = False,- ) -> None:- super().__init__()- self.filter_as_zero = filter_as_zero- self.classes_to_keep = None- self.confidence_threshold = None- if classes_to_keep is not None:- self.classes_to_keep = classes_to_keep if isinstance(classes_to_keep, Tensor) else tensor(classes_to_keep)- if confidence_threshold is not None:- self.confidence_threshold = (- confidence_threshold or confidence_threshold- if isinstance(confidence_threshold, Tensor)- else tensor(confidence_threshold)- )-- def forward(- self, boxes: Tensor, confidence_threshold: Optional[Tensor] = None, classes_to_keep: Optional[Tensor] = None- ) -> Union[Tensor, List[Tensor]]:- """Filter boxes according to the desired threshold.-- To be ONNX-friendly, the inputs for direct forwarding need to be all tensors.-- Args:- boxes: [B, D, 6], where B is the batchsize, D is the number of detections in the image,- 6 represent (class_id, confidence_score, x, y, w, h).- confidence_threshold: an 0-d scalar that represents the desired threshold.- classes_to_keep: a 1-d tensor of classes to keep. If None, keep all classes.-- Returns:- Union[Tensor, List[Tensor]]- If `filter_as_zero` is True, return a tensor of shape [D, 6], where D is the total number of- detections as input.- If `filter_as_zero` is False, return a list of tensors of shape [D, 6], where D is the number of- valid detections for each element in the batch.-- """- # Apply confidence filtering- zero_tensor = tensor(0.0, device=boxes.device, dtype=boxes.dtype)- confidence_threshold = (- confidence_threshold or self.confidence_threshold or zero_tensor- ) # If None, use 0 as threshold- confidence_mask = boxes[:, :, 1] > confidence_threshold # [B, D]-- # Apply class filtering- classes_to_keep = classes_to_keep or self.classes_to_keep- if classes_to_keep is not None:- class_ids = boxes[:, :, 0:1] # [B, D, 1]- classes_to_keep = classes_to_keep.view(1, 1, -1) # [1, 1, C] for broadcasting- class_mask = (class_ids == classes_to_keep).any(dim=-1) # [B, D]- else:- # If no class filtering is needed, just use a mask of all `True`- class_mask = (confidence_mask * 0 + 1).bool()-- # Combine the confidence and class masks- combined_mask = confidence_mask & class_mask # [B, D]-- if self.filter_as_zero:- filtered_boxes = boxes * combined_mask[:, :, None]- return filtered_boxes-- filtered_boxes_list = []- for i in range(boxes.shape[0]):- box = boxes[i]- mask = combined_mask[i] # [D]- valid_boxes = box[mask]- filtered_boxes_list.append(valid_boxes)-- return filtered_boxes_list-- def _create_dummy_input(- self, input_shape: List[int], pseudo_shape: Optional[List[int]] = None- ) -> Union[Tuple[Any, ...], Tensor]:- pseudo_input = rand(- *[- ((self.ONNX_EXPORT_PSEUDO_SHAPE[i] if pseudo_shape is None else pseudo_shape[i]) if dim == -1 else dim)- for i, dim in enumerate(input_shape)- ]- )- if self.confidence_threshold is None:- return pseudo_input, 0.1- return pseudo_inputdiff --git a/kornia/models/dexined.py b/kornia/models/dexined.pynew file mode 100644index 000000000..c34db3884--- /dev/null+++ b/kornia/models/dexined.py@@ -0,0 +1,302 @@+# 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.+#++# adapted from: https://github.com/xavysp/DexiNed/blob/d944b70eb6eaf40e22f8467c1e12919aa600d8e4/model.py++from __future__ import annotations++from collections import OrderedDict+from typing import ClassVar, Optional++import torch+import torch.nn.functional as F+from torch import nn++from kornia.core.check import KORNIA_CHECK++__all__ = ["DexiNed"]++url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"+++def weight_init(m: nn.Module) -> None:+ """Initialize weights."""+ if isinstance(m, nn.Conv2d):+ # torch.nn.init.xavier_uniform_(m.weight, gain=1.0)+ torch.nn.init.xavier_normal_(m.weight, gain=1.0)+ # torch.nn.init.normal_(m.weight, mean=0.0, std=0.01)+ if m.weight.data.shape[1] == torch.Size([1]):+ torch.nn.init.normal_(m.weight, mean=0.0)++ if m.bias is not None:+ torch.nn.init.zeros_(m.bias)++ # for fusion layer+ if isinstance(m, nn.ConvTranspose2d):+ # torch.nn.init.xavier_uniform_(m.weight, gain=1.0)+ torch.nn.init.xavier_normal_(m.weight, gain=1.0)+ # torch.nn.init.normal_(m.weight, mean=0.0, std=0.01)++ if m.weight.data.shape[1] == torch.Size([1]):+ torch.nn.init.normal_(m.weight, std=0.1)+ if m.bias is not None:+ torch.nn.init.zeros_(m.bias)+++class CoFusion(nn.Module):+ def __init__(self, in_ch: int, out_ch: int) -> None:+ super().__init__()+ self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=3, stride=1, padding=1)+ self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)+ self.conv3 = nn.Conv2d(64, out_ch, kernel_size=3, stride=1, padding=1)+ self.relu = nn.ReLU()+ self.norm_layer1 = nn.GroupNorm(4, 64)+ self.norm_layer2 = nn.GroupNorm(4, 64)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ # fusecat = torch.cat(x, dim=1)+ attn = self.relu(self.norm_layer1(self.conv1(x)))+ attn = self.relu(self.norm_layer2(self.conv2(attn)))+ attn = F.softmax(self.conv3(attn), dim=1)++ # return ((fusecat * attn).sum(1)).unsqueeze(1)+ return ((x * attn).sum(1))[:, None, ...]+++class _DenseLayer(nn.Sequential):+ def __init__(self, input_features: int, out_features: int) -> None:+ super().__init__(+ OrderedDict(+ [+ ("relu1", nn.ReLU(inplace=True)),+ ("conv1", nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)),+ ("norm1", nn.BatchNorm2d(out_features)),+ ("relu2", nn.ReLU(inplace=True)),+ ("conv2", nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),+ ("norm2", nn.BatchNorm2d(out_features)),+ ]+ )+ )++ def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor]:+ x1, x2 = x[0], x[1]+ x3: torch.Tensor = x1+ for mod in self:+ x3 = mod(x3)+ return [0.5 * (x3 + x2), x2]+++class _DenseBlock(nn.Sequential):+ def __init__(self, num_layers: int, input_features: int, out_features: int) -> None:+ super().__init__()+ for i in range(num_layers):+ layer = _DenseLayer(input_features, out_features)+ self.add_module(f"denselayer{(i + 1)}", layer)+ input_features = out_features++ def forward(self, x: list[torch.Tensor]) -> list[torch.Tensor]:+ x_out = x+ for mod in self:+ x_out = mod(x_out)+ return x_out+++class UpConvBlock(nn.Module):+ def __init__(self, in_features: int, up_scale: int) -> None:+ super().__init__()+ self.up_factor = 2+ self.constant_features = 16++ layers = self.make_deconv_layers(in_features, up_scale)+ KORNIA_CHECK(layers is not None, "layers cannot be none")+ self.features = nn.Sequential(*layers)++ def make_deconv_layers(self, in_features: int, up_scale: int) -> nn.ModuleList:+ layers = nn.ModuleList([])+ all_pads = [0, 0, 1, 3, 7]+ for i in range(up_scale):+ kernel_size = 2**up_scale+ pad = all_pads[up_scale] # kernel_size-1+ out_features = self.compute_out_features(i, up_scale)+ layers.append(nn.Conv2d(in_features, out_features, 1))+ layers.append(nn.ReLU(inplace=True))+ layers.append(nn.ConvTranspose2d(out_features, out_features, kernel_size, stride=2, padding=pad))+ in_features = out_features+ return layers++ def compute_out_features(self, idx: int, up_scale: int) -> int:+ return 1 if idx == up_scale - 1 else self.constant_features++ def forward(self, x: torch.Tensor, out_shape: list[int]) -> torch.Tensor:+ out = self.features(x)+ out = F.interpolate(out, out_shape, mode="bilinear")+ return out+++class SingleConvBlock(nn.Module):+ def __init__(self, in_features: int, out_features: int, stride: int, use_bs: bool = True) -> None:+ super().__init__()+ self.use_bn = use_bs+ self.conv = nn.Conv2d(in_features, out_features, 1, stride=stride, bias=True)+ self.bn = nn.BatchNorm2d(out_features)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ x = self.conv(x)+ if self.use_bn:+ x = self.bn(x)+ return x+++class DoubleConvBlock(nn.Sequential):+ def __init__(+ self,+ in_features: int,+ mid_features: int,+ out_features: Optional[int] = None,+ stride: int = 1,+ use_act: bool = True,+ ) -> None:+ super().__init__()+ if out_features is None:+ out_features = mid_features+ self.add_module("conv1", nn.Conv2d(in_features, mid_features, 3, padding=1, stride=stride))+ self.add_module("bn1", nn.BatchNorm2d(mid_features))+ self.add_module("relu1", nn.ReLU(inplace=True))+ self.add_module("conv2", nn.Conv2d(mid_features, out_features, 3, padding=1))+ self.add_module("bn2", nn.BatchNorm2d(out_features))+ if use_act:+ self.add_module("relu2", nn.ReLU(inplace=True))+++class DexiNed(nn.Module):+ r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.++ Return:+ A list of tensor with the intermediate features which the last element+ is the edges map with shape :math:`(B,1,H,W)`.++ Example:+ >>> img = torch.rand(1, 3, 320, 320)+ >>> net = DexiNed(pretrained=False)+ >>> out = net(img)+ >>> out.shape+ torch.Size([1, 1, 320, 320])++ """++ ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]+ ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, 1, -1, -1]++ def __init__(self, pretrained: bool) -> None:+ super().__init__()+ self.block_1 = DoubleConvBlock(3, 32, 64, stride=2)+ self.block_2 = DoubleConvBlock(64, 128, use_act=False)+ self.dblock_3 = _DenseBlock(2, 128, 256) # [128,256,100,100]+ self.dblock_4 = _DenseBlock(3, 256, 512)+ self.dblock_5 = _DenseBlock(3, 512, 512)+ self.dblock_6 = _DenseBlock(3, 512, 256)+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)++ # left skip connections, figure in Journal+ self.side_1 = SingleConvBlock(64, 128, 2)+ self.side_2 = SingleConvBlock(128, 256, 2)+ self.side_3 = SingleConvBlock(256, 512, 2)+ self.side_4 = SingleConvBlock(512, 512, 1)+ self.side_5 = SingleConvBlock(512, 256, 1)++ # right skip connections, figure in Journal paper+ self.pre_dense_2 = SingleConvBlock(128, 256, 2)+ self.pre_dense_3 = SingleConvBlock(128, 256, 1)+ self.pre_dense_4 = SingleConvBlock(256, 512, 1)+ self.pre_dense_5 = SingleConvBlock(512, 512, 1)+ self.pre_dense_6 = SingleConvBlock(512, 256, 1)++ # USNet+ self.up_block_1 = UpConvBlock(64, 1)+ self.up_block_2 = UpConvBlock(128, 1)+ self.up_block_3 = UpConvBlock(256, 2)+ self.up_block_4 = UpConvBlock(512, 3)+ self.up_block_5 = UpConvBlock(512, 4)+ self.up_block_6 = UpConvBlock(256, 4)+ self.block_cat = SingleConvBlock(6, 1, stride=1, use_bs=False) # hed fusion method+ # self.block_cat = CoFusion(6,6)# cats fusion method++ if pretrained:+ self.load_from_file(url)+ else:+ self.apply(weight_init)++ def load_from_file(self, path_file: str) -> None:+ # use torch.hub to load pretrained model+ pretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=torch.device("cpu"))+ self.load_state_dict(pretrained_dict, strict=True)+ self.eval()++ def get_features(self, x: torch.Tensor) -> list[torch.Tensor]:+ # Block 1+ block_1 = self.block_1(x)+ block_1_side = self.side_1(block_1)++ # Block 2+ block_2 = self.block_2(block_1)+ block_2_down = self.maxpool(block_2)+ block_2_add = block_2_down + block_1_side+ block_2_side = self.side_2(block_2_add)++ # Block 3+ block_3_pre_dense = self.pre_dense_3(block_2_down)+ block_3, _ = self.dblock_3([block_2_add, block_3_pre_dense])+ block_3_down = self.maxpool(block_3) # [128,256,50,50]+ block_3_add = block_3_down + block_2_side+ block_3_side = self.side_3(block_3_add)++ # Block 4+ block_2_resize_half = self.pre_dense_2(block_2_down)+ block_4_pre_dense = self.pre_dense_4(block_3_down + block_2_resize_half)+ block_4, _ = self.dblock_4([block_3_add, block_4_pre_dense])+ block_4_down = self.maxpool(block_4)+ block_4_add = block_4_down + block_3_side+ block_4_side = self.side_4(block_4_add)++ # Block 5+ block_5_pre_dense = self.pre_dense_5(block_4_down) # block_5_pre_dense_512 +block_4_down+ block_5, _ = self.dblock_5([block_4_add, block_5_pre_dense])+ block_5_add = block_5 + block_4_side++ # Block 6+ block_6_pre_dense = self.pre_dense_6(block_5)+ block_6, _ = self.dblock_6([block_5_add, block_6_pre_dense])++ # upsampling blocks+ out_shape = x.shape[-2:]+ out_1 = self.up_block_1(block_1, out_shape)+ out_2 = self.up_block_2(block_2, out_shape)+ out_3 = self.up_block_3(block_3, out_shape)+ out_4 = self.up_block_4(block_4, out_shape)+ out_5 = self.up_block_5(block_5, out_shape)+ out_6 = self.up_block_6(block_6, out_shape)+ results = [out_1, out_2, out_3, out_4, out_5, out_6]+ return results++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ features = self.get_features(x)++ # concatenate multiscale outputs+ block_cat = torch.cat(features, dim=1) # Bx6xHxW+ block_cat = self.block_cat(block_cat) # Bx1xHxW++ return block_catdiff --git a/kornia/models/edge_detection/__init__.py b/kornia/models/edge_detection/__init__.pydeleted file mode 100644index 25c41b02c..000000000--- a/kornia/models/edge_detection/__init__.py+++ /dev/null@@ -1,24 +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.-#--"""Edge detection models submodule for Kornia.--This package provides model architectures and utilities for edge detection tasks.-"""--from .base import *-from .dexined import *diff --git a/kornia/models/edge_detection/base.py b/kornia/models/edge_detection/base.pydeleted file mode 100644index 7d8dfb6f4..000000000--- a/kornia/models/edge_detection/base.py+++ /dev/null@@ -1,141 +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 __future__ import annotations--from typing import Any, Optional, Union--import torch--from kornia.color.gray import grayscale_to_rgb-from kornia.core import Tensor-from kornia.core.external import PILImage as Image-from kornia.core.external import onnx-from kornia.models.base import ModelBase--__all__ = ["EdgeDetector"]---class EdgeDetector(ModelBase):- """EdgeDetector is a module that wraps an edge detection model."""-- name: str = "edge_detection"-- @torch.inference_mode()- def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:- """Forward pass of the edge detection model.-- Args:- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.-- Returns:- output tensor.-- """- images, image_sizes = self.pre_processor(images)- out_images = self.model(images)- return self.post_processor(out_images, image_sizes)-- def visualize(- self,- images: Union[Tensor, list[Tensor]],- edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,- output_type: str = "torch",- ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore- """Draw the edge detection results.-- Args:- images: input tensor.- edge_maps: detected edges.- output_type: type of the output.-- Returns:- output tensor.-- """- if edge_maps is None:- edge_maps = self.forward(images)- output = []- for edge_map in edge_maps:- output.append(grayscale_to_rgb(edge_map)[0])-- return self._tensor_to_type(output, output_type, is_batch=isinstance(images, Tensor))-- def save(- self,- images: Union[Tensor, list[Tensor]],- edge_maps: Optional[Union[Tensor, list[Tensor]]] = None,- directory: Optional[str] = None,- output_type: str = "torch",- ) -> None:- """Save the edge detection results.-- Args:- images: input tensor.- edge_maps: detected edges.- output_type: type of the output.- directory: where to save outputs.-- Returns:- output tensor.-- """- outputs = self.visualize(images, edge_maps, output_type)- self._save_outputs(images, directory, suffix="_src")- self._save_outputs(outputs, directory, suffix="_edge")-- def to_onnx( # type: ignore[override]- self,- onnx_name: Optional[str] = None,- image_size: Optional[int] = 352,- include_pre_and_post_processor: bool = True,- save: bool = True,- additional_metadata: Optional[list[tuple[str, str]]] = None,- **kwargs: Any,- ) -> onnx.ModelProto: # type: ignore- """Export the current edge detection model to an ONNX model file.-- Args:- onnx_name:- The name of the output ONNX file. If not provided, a default name in the- format "Kornia-<ClassName>.onnx" will be used.- image_size:- The size to which input images will be resized during preprocessing.- If None, image_size will be dynamic. For DexiNed, recommended scale is 352.- include_pre_and_post_processor:- Whether to include the pre-processor and post-processor in the exported model.- save:- If to save the model or load it.- additional_metadata:- Additional metadata to add to the ONNX model.- kwargs: Additional arguments to convert to onnx.-- """- if onnx_name is None:- onnx_name = f"kornia_{self.name}_{image_size}.onnx"-- return super().to_onnx(- onnx_name,- input_shape=[-1, 3, image_size or -1, image_size or -1],- output_shape=[-1, 1, image_size or -1, image_size or -1],- pseudo_shape=[1, 3, image_size or 352, image_size or 352],- model=self if include_pre_and_post_processor else self.model,- save=save,- additional_metadata=additional_metadata,- **kwargs,- )diff --git a/kornia/models/edge_detection/dexined.py b/kornia/models/edge_detection/dexined.pydeleted file mode 100644index 063eb22b9..000000000--- a/kornia/models/edge_detection/dexined.py+++ /dev/null@@ -1,53 +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 torch import nn--from kornia.core import tensor-from kornia.enhance.normalize import Normalize-from kornia.filters.dexined import DexiNed-from kornia.models.edge_detection.base import EdgeDetector-from kornia.models.utils import ResizePostProcessor, ResizePreProcessor--__all__ = ["DexiNedBuilder"]---class DexiNedBuilder:- """DexiNedBuilder is a class that builds a DexiNed model.-- .. code-block:: python-- images = kornia.utils.sample.get_sample_images()- model = DexiNedBuilder.build()- model.save(images)- """-- @staticmethod- def build(model_name: str = "dexined", pretrained: bool = True, image_size: int = 352) -> EdgeDetector:- if model_name.lower() == "dexined":- # Normalize then scale to [0, 255]- norm = Normalize(mean=tensor([[0.485, 0.456, 0.406]]), std=tensor([[1.0 / 255.0] * 3]))- model = nn.Sequential(norm, DexiNed(pretrained=pretrained), nn.Sigmoid())- else:- raise ValueError(f"Model {model_name} not found. Please choose from 'DexiNed'.")-- return EdgeDetector(- model,- ResizePreProcessor(image_size, image_size),- ResizePostProcessor(),- name="dexined",- )diff --git a/kornia/contrib/models/efficient_vit/__init__.py b/kornia/models/efficient_vit/__init__.pysimilarity index 100%rename from kornia/contrib/models/efficient_vit/__init__.pyrename to kornia/models/efficient_vit/__init__.pydiff --git a/kornia/contrib/models/efficient_vit/backbone.py b/kornia/models/efficient_vit/backbone.pysimilarity index 98%rename from kornia/contrib/models/efficient_vit/backbone.pyrename to kornia/models/efficient_vit/backbone.pyindex 2159b40fc..27cd94453 100644--- a/kornia/contrib/models/efficient_vit/backbone.py+++ b/kornia/models/efficient_vit/backbone.py@@ -25,7 +25,7 @@ from typing import Anyimport torchfrom torch import nn-from kornia.contrib.models.efficient_vit.nn.ops import ( # type: ignore+from kornia.models.efficient_vit.nn.ops import ( # type: ignoreConvLayer,DSConv,EfficientViTBlock,@@ -36,7 +36,7 @@ from kornia.contrib.models.efficient_vit.nn.ops import ( # type: ignoreResBlock,ResidualBlock,)-from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config+from kornia.models.efficient_vit.utils import build_kwargs_from_configclass EfficientViTBackbone(nn.Module):diff --git a/kornia/contrib/models/efficient_vit/model.py b/kornia/models/efficient_vit/model.pysimilarity index 93%rename from kornia/contrib/models/efficient_vit/model.pyrename to kornia/models/efficient_vit/model.pyindex 253bf9096..d1c4cf08f 100644--- a/kornia/contrib/models/efficient_vit/model.py+++ b/kornia/models/efficient_vit/model.py@@ -22,9 +22,8 @@ from typing import Literalimport torch-from kornia.contrib.models.base import ModelBase-from kornia.contrib.models.efficient_vit import backbone as vit-from kornia.core import Tensor+from kornia.models.base import ModelBase+from kornia.models.efficient_vit import backbone as vitdef _get_base_url(model_type: Literal["b1", "b2", "b3"] = "b1", resolution: Literal[224, 256, 288] = 224) -> str:@@ -97,14 +96,14 @@ class EfficientViT(ModelBase[EfficientViTConfig]):return EfficientViT(backbone=model)- def forward(self, images: Tensor) -> Tensor:+ def forward(self, images: torch.Tensor) -> torch.Tensor:"""Extract features from the input images.Args:images: input images tensor of shape :math:`(B, C, H, W)`.Returns:- Dict[str, Tensor]: a dictionary containing the features.+ Dict[str, torch.Tensor]: a dictionary containing the features."""feats = self.backbone(images)diff --git a/kornia/contrib/models/efficient_vit/nn/__init__.py b/kornia/models/efficient_vit/nn/__init__.pysimilarity index 100%rename from kornia/contrib/models/efficient_vit/nn/__init__.pyrename to kornia/models/efficient_vit/nn/__init__.pydiff --git a/kornia/contrib/models/efficient_vit/nn/act.py b/kornia/models/efficient_vit/nn/act.pysimilarity index 95%rename from kornia/contrib/models/efficient_vit/nn/act.pyrename to kornia/models/efficient_vit/nn/act.pyindex 0faa48c38..5cf39f7b8 100644--- a/kornia/contrib/models/efficient_vit/nn/act.py+++ b/kornia/models/efficient_vit/nn/act.py@@ -25,7 +25,7 @@ from typing import Any, Optional, Unionfrom torch import nn-from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config+from kornia.models.efficient_vit.utils import build_kwargs_from_config# register activation function hereREGISTERED_ACT_DICT: dict[str, type[nn.Module]] = {diff --git a/kornia/contrib/models/efficient_vit/nn/norm.py b/kornia/models/efficient_vit/nn/norm.pysimilarity index 96%rename from kornia/contrib/models/efficient_vit/nn/norm.pyrename to kornia/models/efficient_vit/nn/norm.pyindex 6e8b721c9..0afc34b22 100644--- a/kornia/contrib/models/efficient_vit/nn/norm.py+++ b/kornia/models/efficient_vit/nn/norm.py@@ -25,7 +25,7 @@ from typing import Any, Optionalimport torchfrom torch import nn-from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config+from kornia.models.efficient_vit.utils import build_kwargs_from_configclass LayerNorm2d(nn.LayerNorm):diff --git a/kornia/contrib/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.pysimilarity index 98%rename from kornia/contrib/models/efficient_vit/nn/ops.pyrename to kornia/models/efficient_vit/nn/ops.pyindex bc7a68045..455504c8d 100644--- a/kornia/contrib/models/efficient_vit/nn/ops.py+++ b/kornia/models/efficient_vit/nn/ops.py@@ -26,9 +26,9 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.contrib.models.efficient_vit.nn.act import build_act-from kornia.contrib.models.efficient_vit.nn.norm import build_norm-from kornia.contrib.models.efficient_vit.utils import get_same_padding, val2tuple+from kornia.models.efficient_vit.nn.act import build_act+from kornia.models.efficient_vit.nn.norm import build_norm+from kornia.models.efficient_vit.utils import get_same_padding, val2tuplefrom kornia.utils._compat import autocast__all__ = [diff --git a/kornia/contrib/models/efficient_vit/utils/__init__.py b/kornia/models/efficient_vit/utils/__init__.pysimilarity index 100%rename from kornia/contrib/models/efficient_vit/utils/__init__.pyrename to kornia/models/efficient_vit/utils/__init__.pydiff --git a/kornia/contrib/models/efficient_vit/utils/list.py b/kornia/models/efficient_vit/utils/list.pysimilarity index 100%rename from kornia/contrib/models/efficient_vit/utils/list.pyrename to kornia/models/efficient_vit/utils/list.pydiff --git a/kornia/contrib/models/efficient_vit/utils/network.py b/kornia/models/efficient_vit/utils/network.pysimilarity index 100%rename from kornia/contrib/models/efficient_vit/utils/network.pyrename to kornia/models/efficient_vit/utils/network.pydiff --git a/kornia/models/utils.py b/kornia/models/processors.pysimilarity index 83%rename from kornia/models/utils.pyrename to kornia/models/processors.pyindex 0fa0513a9..df55e5913 100644--- a/kornia/models/utils.py+++ b/kornia/models/processors.py@@ -19,15 +19,14 @@ import warningsfrom typing import List, Tuple, Unionimport torch-from torch import Tensor+from torch import nn-from kornia.core import Module, concatenatefrom kornia.geometry.transform import resize__all__ = ["OutputRangePostProcessor", "ResizePostProcessor", "ResizePreProcessor"]-class ResizePreProcessor(Module):+class ResizePreProcessor(nn.Module):"""Resize a list of image tensors to the given size.Additionally, also returns the original image sizes for further post-processing.@@ -47,7 +46,7 @@ class ResizePreProcessor(Module):self.size = (height, width)self.interpolation_mode = interpolation_mode- def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Tuple[Tensor, Tensor]:+ def forward(self, imgs: Union[torch.Tensor, List[torch.Tensor]]) -> Tuple[torch.Tensor, torch.Tensor]:"""Run forward.Returns:@@ -56,7 +55,7 @@ class ResizePreProcessor(Module):"""# TODO: support other input formats e.g. file path, numpy- resized_imgs: list[Tensor] = []+ resized_imgs: list[torch.Tensor] = []iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]original_sizes = imgs[0].new_zeros((iters, 2))@@ -65,15 +64,17 @@ class ResizePreProcessor(Module):original_sizes[i, 0] = img.shape[-2] # Heightoriginal_sizes[i, 1] = img.shape[-1] # Widthresized_imgs.append(resize(img[None], size=self.size, interpolation=self.interpolation_mode))- return concatenate(resized_imgs), original_sizes+ return torch.cat(resized_imgs), original_sizes-class ResizePostProcessor(Module):+class ResizePostProcessor(nn.Module):def __init__(self, interpolation_mode: str = "bilinear") -> None:super().__init__()self.interpolation_mode = interpolation_mode- def forward(self, imgs: Union[Tensor, List[Tensor]], original_sizes: Tensor) -> Union[Tensor, List[Tensor]]:+ def forward(+ self, imgs: Union[torch.Tensor, List[torch.Tensor]], original_sizes: torch.Tensor+ ) -> Union[torch.Tensor, List[torch.Tensor]]:"""Run forward.Returns:@@ -82,7 +83,7 @@ class ResizePostProcessor(Module):"""# TODO: support other input formats e.g. file path, numpy- resized_imgs: list[Tensor] = []+ resized_imgs: list[torch.Tensor] = []if torch.onnx.is_in_onnx_export():warnings.warn(@@ -102,13 +103,13 @@ class ResizePostProcessor(Module):return resized_imgs-class OutputRangePostProcessor(Module):+class OutputRangePostProcessor(nn.Module):def __init__(self, min_val: float = 0.0, max_val: float = 1.0) -> None:super().__init__()self.min_val = min_valself.max_val = max_val- def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Union[Tensor, List[Tensor]]:- if isinstance(imgs, Tensor):+ def forward(self, imgs: Union[torch.Tensor, List[torch.Tensor]]) -> Union[torch.Tensor, List[torch.Tensor]]:+ if isinstance(imgs, torch.Tensor):return torch.clamp(imgs, self.min_val, self.max_val)return [img.clamp_(self.min_val, self.max_val) for img in imgs]diff --git a/kornia/contrib/models/rt_detr/__init__.py b/kornia/models/rt_detr/__init__.pysimilarity index 83%rename from kornia/contrib/models/rt_detr/__init__.pyrename to kornia/models/rt_detr/__init__.pyindex 7aa256fd1..29b6e9224 100644--- a/kornia/contrib/models/rt_detr/__init__.py+++ b/kornia/models/rt_detr/__init__.py@@ -20,5 +20,5 @@This subpackage provides RT-DETR model classes, configs, and post-processors."""-from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig, RTDETRModelType-from kornia.contrib.models.rt_detr.post_processor import DETRPostProcessor+from kornia.models.rt_detr.model import RTDETR, RTDETRConfig, RTDETRModelType+from kornia.models.rt_detr.post_processor import DETRPostProcessordiff --git a/kornia/contrib/models/rt_detr/architecture/__init__.py b/kornia/models/rt_detr/architecture/__init__.pysimilarity index 100%rename from kornia/contrib/models/rt_detr/architecture/__init__.pyrename to kornia/models/rt_detr/architecture/__init__.pydiff --git a/kornia/contrib/models/rt_detr/architecture/hgnetv2.py b/kornia/models/rt_detr/architecture/hgnetv2.pysimilarity index 92%rename from kornia/contrib/models/rt_detr/architecture/hgnetv2.pyrename to kornia/models/rt_detr/architecture/hgnetv2.pyindex 7529b13eb..cc0252aeb 100644--- a/kornia/contrib/models/rt_detr/architecture/hgnetv2.py+++ b/kornia/models/rt_detr/architecture/hgnetv2.py@@ -24,14 +24,14 @@ from __future__ import annotationsfrom typing import NamedTuple+import torchfrom torch import nn-from kornia.contrib.models.common import ConvNormAct-from kornia.core import Module, Tensor, concatenatefrom kornia.core.check import KORNIA_CHECK+from kornia.models.common import ConvNormAct-class StemBlock(Module):+class StemBlock(nn.Module):def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:super().__init__()self.stem1 = ConvNormAct(in_channels, mid_channels, 3, 2)@@ -41,9 +41,9 @@ class StemBlock(Module):self.stem4 = ConvNormAct(mid_channels, out_channels, 1)self.pool = nn.Sequential(nn.ZeroPad2d((0, 1, 0, 1)), nn.MaxPool2d(2, 1))- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:x = self.stem1(x)- x = concatenate([self.pool(x), self.stem2b(self.stem2a(x))], 1)+ x = torch.cat([self.pool(x), self.stem2b(self.stem2a(x))], 1)x = self.stem4(self.stem3(x))return x@@ -67,7 +67,7 @@ class StageConfig(NamedTuple):layer_num: int-class HGBlock(Module):+class HGBlock(nn.Module):def __init__(self, in_channels: int, config: StageConfig, identity: bool) -> None:super().__init__()self.identity = identity@@ -82,11 +82,11 @@ class HGBlock(Module):self.aggregation_squeeze_conv = ConvNormAct(total_channels, config.out_channels // 2, 1)self.aggregation_excitation_conv = ConvNormAct(config.out_channels // 2, config.out_channels, 1)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:feats = [x]for layer in self.layers:feats.append(layer(feats[-1]))- out = concatenate(feats, 1)+ out = torch.cat(feats, 1)out = self.aggregation_squeeze_conv(out)out = self.aggregation_excitation_conv(out)return x + out if self.identity else out@@ -103,7 +103,7 @@ class HGStage(nn.Sequential):)-class PPHGNetV2(Module):+class PPHGNetV2(nn.Module):def __init__(self, stem_channels: list[int], stage_configs: list[StageConfig]) -> None:KORNIA_CHECK(len(stem_channels) == 3)KORNIA_CHECK(len(stage_configs) == 4)@@ -114,7 +114,7 @@ class PPHGNetV2(Module):for cfg in stage_configs:self.stages.append(HGStage(cfg))- def forward(self, x: Tensor) -> list[Tensor]:+ def forward(self, x: torch.Tensor) -> list[torch.Tensor]:x = self.stem(x)s2 = self.stages[0](x)s3 = self.stages[1](s2)diff --git a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py b/kornia/models/rt_detr/architecture/hybrid_encoder.pysimilarity index 89%rename from kornia/contrib/models/rt_detr/architecture/hybrid_encoder.pyrename to kornia/models/rt_detr/architecture/hybrid_encoder.pyindex aa0e8d1c8..e5fc07e6f 100644--- a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py+++ b/kornia/models/rt_detr/architecture/hybrid_encoder.py@@ -30,12 +30,11 @@ import torch.nn.functional as Ffrom torch import nnfrom torch.nn.utils.fusion import fuse_conv_bn_weights-from kornia.contrib.models.common import ConvNormAct-from kornia.core import Module, Tensor, concatenate, pad+from kornia.models.common import ConvNormActfrom kornia.utils._compat import torch_meshgrid-class RepVggBlock(Module):+class RepVggBlock(nn.Module):def __init__(self, in_channels: int, out_channels: int) -> None:super().__init__()self.conv1 = ConvNormAct(in_channels, out_channels, 3, act="none")@@ -43,7 +42,7 @@ class RepVggBlock(Module):self.act = nn.SiLU(inplace=True)self.conv: Optional[nn.Conv2d] = None- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:if self.conv is not None:out = self.act(self.conv(x))else:@@ -68,7 +67,7 @@ class RepVggBlock(Module):kernel3x3, bias3x3 = _fuse_conv_bn_weights(self.conv1)kernel1x1, bias1x1 = _fuse_conv_bn_weights(self.conv2)- kernel3x3.add_(pad(kernel1x1, [1, 1, 1, 1]))+ kernel3x3.add_(F.pad(kernel1x1, [1, 1, 1, 1]))bias3x3.add_(bias1x1)self.conv = nn.Conv2d(kernel3x3.shape[1], kernel3x3.shape[0], 3, 1, 1)@@ -76,7 +75,7 @@ class RepVggBlock(Module):self.conv.bias = bias3x3-class CSPRepLayer(Module):+class CSPRepLayer(nn.Module):def __init__(self, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0) -> None:super().__init__()hidden_channels = int(out_channels * expansion)@@ -89,13 +88,13 @@ class CSPRepLayer(Module):else nn.Identity())- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:return self.conv3(self.bottlenecks(self.conv1(x)) + self.conv2(x))# almost identical to nn.TransformerEncoderLayer# but add positional embeddings to q and k-class AIFI(Module):+class AIFI(nn.Module):def __init__(self, embed_dim: int, num_heads: int, dim_feedforward: int, dropout: float = 0.0) -> None:super().__init__()self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout) # NOTE: batch_first = False@@ -110,7 +109,7 @@ class AIFI(Module):self.norm2 = nn.LayerNorm(embed_dim)self.act = nn.GELU()- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:# using post-normN, C, H, W = x.shapex = x.permute(2, 3, 0, 1).flatten(0, 1) # (N, C, H, W) -> (H * W, N, C)@@ -126,7 +125,7 @@ class AIFI(Module):x = x.view(H, W, N, C).permute(2, 3, 0, 1) # (H * W, N, C) -> (N, C, H, W)return x- def ffn(self, x: Tensor) -> Tensor:+ def ffn(self, x: torch.Tensor) -> torch.Tensor:return self.linear2(self.dropout(self.act(self.linear1(x))))# TODO: make this into a reusable function@@ -140,7 +139,7 @@ class AIFI(Module):temp: float = 10_000.0,device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,- ) -> Tensor:+ ) -> torch.Tensor:"""Construct 2D sin-cos positional embeddings.Args:@@ -166,7 +165,7 @@ class AIFI(Module):out_x = grid_x.reshape(-1, 1) * omega.view(1, -1)out_y = grid_y.reshape(-1, 1) * omega.view(1, -1)- pos_emb = concatenate([out_x.sin(), out_x.cos(), out_y.sin(), out_y.cos()], 1)+ pos_emb = torch.cat([out_x.sin(), out_x.cos(), out_y.sin(), out_y.cos()], 1)return pos_emb.unsqueeze(1) # (H * W, 1, C)@@ -176,7 +175,9 @@ class TransformerEncoder(nn.Module):self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(num_layers)])self.num_layers = num_layers- def forward(self, src: Tensor) -> Tensor: # NOTE: Missing src_mask: Tensor = None, pos_embed: Tensor = None+ def forward(+ self, src: torch.Tensor+ ) -> torch.Tensor: # NOTE: Missing src_mask: torch.Tensor = None, pos_embed: torch.Tensor = Noneoutput = srcfor layer in self.layers:output = layer(output)@@ -184,7 +185,7 @@ class TransformerEncoder(nn.Module):return output-class CCFM(Module):+class CCFM(nn.Module):def __init__(self, num_fmaps: int, hidden_dim: int, expansion: float = 1.0) -> None:super().__init__()self.lateral_convs = nn.ModuleList()@@ -199,7 +200,7 @@ class CCFM(Module):self.downsample_convs.append(ConvNormAct(hidden_dim, hidden_dim, 3, 2, "silu"))self.pan_blocks.append(CSPRepLayer(hidden_dim * 2, hidden_dim, 3, expansion))- def forward(self, fmaps: list[Tensor]) -> list[Tensor]:+ def forward(self, fmaps: list[torch.Tensor]) -> list[torch.Tensor]:# fmaps is ordered from hi-res to low-resfmaps = list(fmaps) # shallow clone@@ -210,7 +211,7 @@ class CCFM(Module):up_lowres_fmap = F.interpolate(new_fmaps[-1], scale_factor=2.0, mode="nearest")hires_fmap = fmaps.pop()- concat_fmap = concatenate([up_lowres_fmap, hires_fmap], 1)+ concat_fmap = torch.cat([up_lowres_fmap, hires_fmap], 1)new_fmaps.append(self.fpn_blocks[len(new_fmaps) - 1](concat_fmap))fmaps = [new_fmaps.pop()]@@ -218,13 +219,13 @@ class CCFM(Module):down_hires_fmap = self.downsample_convs[len(fmaps) - 1](fmaps[-1])lowres_fmap = new_fmaps.pop()- concat_fmap = concatenate([down_hires_fmap, lowres_fmap], 1)+ concat_fmap = torch.cat([down_hires_fmap, lowres_fmap], 1)fmaps.append(self.pan_blocks[len(fmaps) - 1](concat_fmap))return fmaps-class HybridEncoder(Module):+class HybridEncoder(nn.Module):def __init__(self, in_channels: list[int], hidden_dim: int, dim_feedforward: int, expansion: float = 1.0) -> None:super().__init__()self.input_proj = nn.ModuleList(@@ -239,7 +240,7 @@ class HybridEncoder(Module):self.encoder = nn.Sequential(TransformerEncoder(encoder_layer, 1))self.ccfm = CCFM(len(in_channels), hidden_dim, expansion)- def forward(self, fmaps: list[Tensor]) -> list[Tensor]:+ def forward(self, fmaps: list[torch.Tensor]) -> list[torch.Tensor]:projected_maps = [proj(fmap) for proj, fmap in zip(self.input_proj, fmaps)]projected_maps[-1] = self.encoder(projected_maps[-1])new_fmaps = self.ccfm(projected_maps)diff --git a/kornia/contrib/models/rt_detr/architecture/resnet_d.py b/kornia/models/rt_detr/architecture/resnet_d.pysimilarity index 92%rename from kornia/contrib/models/rt_detr/architecture/resnet_d.pyrename to kornia/models/rt_detr/architecture/resnet_d.pyindex a9cead84f..f74d0d697 100644--- a/kornia/contrib/models/rt_detr/architecture/resnet_d.py+++ b/kornia/models/rt_detr/architecture/resnet_d.py@@ -25,14 +25,14 @@ from __future__ import annotationsfrom collections import OrderedDict+import torchfrom torch import nn-from kornia.contrib.models.common import ConvNormAct-from kornia.core import Module, Tensorfrom kornia.core.check import KORNIA_CHECK+from kornia.models.common import ConvNormAct-def _make_shortcut(in_channels: int, out_channels: int, stride: int) -> Module:+def _make_shortcut(in_channels: int, out_channels: int, stride: int) -> nn.Module:return (nn.Sequential(OrderedDict([("pool", nn.AvgPool2d(2, 2)), ("conv", ConvNormAct(in_channels, out_channels, 1, act="none"))])@@ -42,7 +42,7 @@ def _make_shortcut(in_channels: int, out_channels: int, stride: int) -> Module:)-class BasicBlockD(Module):+class BasicBlockD(nn.Module):expansion = 1def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None:@@ -59,11 +59,11 @@ class BasicBlockD(Module):self.short = nn.Identity() if shortcut else _make_shortcut(in_channels, out_channels, stride)self.relu = nn.ReLU(inplace=True)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:return self.relu(self.convs(x) + self.short(x))-class BottleneckD(Module):+class BottleneckD(nn.Module):expansion = 4def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None:@@ -82,17 +82,17 @@ class BottleneckD(Module):self.short = nn.Identity() if shortcut else _make_shortcut(in_channels, expanded_out_channels, stride)self.relu = nn.ReLU(inplace=True)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:return self.relu(self.convs(x) + self.short(x))class Block(nn.Sequential):- def __init__(self, blocks: Module) -> None:+ def __init__(self, blocks: nn.Module) -> None:super().__init__()self.blocks = blocks-class ResNetD(Module):+class ResNetD(nn.Module):def __init__(self, n_blocks: list[int], block: type[BasicBlockD | BottleneckD]) -> None:KORNIA_CHECK(len(n_blocks) == 4)super().__init__()@@ -120,7 +120,7 @@ class ResNetD(Module):@staticmethoddef make_stage(in_channels: int, out_channels: int, stride: int, n_blocks: int, block: type[BasicBlockD | BottleneckD]- ) -> tuple[Module, int]:+ ) -> tuple[nn.Module, int]:stage = Block(nn.Sequential(block(in_channels, out_channels, stride, False),@@ -129,7 +129,7 @@ class ResNetD(Module):)return stage, out_channels * block.expansion- def forward(self, x: Tensor) -> list[Tensor]:+ def forward(self, x: torch.Tensor) -> list[torch.Tensor]:x = self.conv1(x)res2 = self.res_layers[0](x)res3 = self.res_layers[1](res2)diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/models/rt_detr/architecture/rtdetr_head.pysimilarity index 88%rename from kornia/contrib/models/rt_detr/architecture/rtdetr_head.pyrename to kornia/models/rt_detr/architecture/rtdetr_head.pyindex b70b2245c..e7f7429b5 100644--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py+++ b/kornia/models/rt_detr/architecture/rtdetr_head.py@@ -26,8 +26,7 @@ from typing import Optionalimport torchfrom torch import nn-from kornia.contrib.models.common import MLP, ConvNormAct-from kornia.core import Module, Tensor, concatenate+from kornia.models.common import MLP, ConvNormActfrom kornia.utils._compat import torch_meshgrid@@ -47,8 +46,11 @@ def _inverse_sigmoid(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor:def _deformable_attention_kernel(- value: Tensor, value_spatial_shapes: list[tuple[int, int]], sampling_locations: Tensor, attention_weights: Tensor-) -> Tensor:+ value: torch.Tensor,+ value_spatial_shapes: list[tuple[int, int]],+ sampling_locations: torch.Tensor,+ attention_weights: torch.Tensor,+) -> torch.Tensor:"""Deformable Attention Kernel used in Deformable DETR.Described in https://arxiv.org/abs/2010.04159.@@ -70,7 +72,7 @@ def _deformable_attention_kernel(value_list = value.split(split_shape, dim=1)sampling_grids = 2 * sampling_locations - 1- sampling_value_list: list[Tensor] = []+ sampling_value_list: list[torch.Tensor] = []for level, (h, w) in enumerate(value_spatial_shapes):# N_, H_*W_, M_, D_ -> N_, H_*W_, M_*D_ -> N_, M_*D_, H_*W_ -> N_*M_, D_, H_, W_value_l_ = value_list[level].flatten(2).permute(0, 2, 1).reshape(bs * n_head, c, h, w)@@ -93,7 +95,7 @@ def _deformable_attention_kernel(return output.permute(0, 2, 1)-class MultiScaleDeformableAttention(Module):+class MultiScaleDeformableAttention(nn.Module):"""Multi-scale Deformable Attention used in Deformable DETR.Described in https://arxiv.org/abs/2010.04159.@@ -116,8 +118,12 @@ class MultiScaleDeformableAttention(Module):self.output_proj = nn.Linear(embed_dim, embed_dim)def forward(- self, query: Tensor, reference_points: Tensor, value: Tensor, value_spatial_shapes: list[tuple[int, int]]- ) -> Tensor:+ self,+ query: torch.Tensor,+ reference_points: torch.Tensor,+ value: torch.Tensor,+ value_spatial_shapes: list[tuple[int, int]],+ ) -> torch.Tensor:"""Run forward.Args:@@ -158,7 +164,7 @@ class MultiScaleDeformableAttention(Module):return out-class TransformerDecoderLayer(Module):+class TransformerDecoderLayer(nn.Module):"""Deformable Transformer Decoder layer used in Deformable DETR.Described in: https://arxiv.org/abs/2010.04159.@@ -184,20 +190,20 @@ class TransformerDecoderLayer(Module):self.dropout4 = nn.Dropout(dropout)self.norm3 = nn.LayerNorm(embed_dim)- def _ffn(self, x: Tensor) -> Tensor:+ def _ffn(self, x: torch.Tensor) -> torch.Tensor:return self.linear2(self.dropout3(self.activation(self.linear1(x))))def forward(self,- tgt: Tensor,- ref_points: Tensor,- memory: Tensor,+ tgt: torch.Tensor,+ ref_points: torch.Tensor,+ memory: torch.Tensor,memory_spatial_shapes: list[tuple[int, int]],memory_level_start_index: Optional[list[int]] = None,- attn_mask: Optional[Tensor] = None,- memory_mask: Optional[Tensor] = None,- query_pos_embed: Optional[Tensor] = None,- ) -> Tensor:+ attn_mask: Optional[torch.Tensor] = None,+ memory_mask: Optional[torch.Tensor] = None,+ query_pos_embed: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:# TODO: rename variables because is confusing# self attentionq = k = tgt + query_pos_embed@@ -214,7 +220,7 @@ class TransformerDecoderLayer(Module):return out-class TransformerDecoder(Module):+class TransformerDecoder(nn.Module):def __init__(self, hidden_dim: int, decoder_layer: nn.Module, num_layers: int, eval_idx: int = -1) -> None:super().__init__()self.layers = nn.ModuleList([copy.deepcopy(decoder_layer) for _ in range(num_layers)])@@ -224,25 +230,25 @@ class TransformerDecoder(Module):def forward(self,- tgt: Tensor,- ref_points_unact: Tensor,- memory: Tensor,+ tgt: torch.Tensor,+ ref_points_unact: torch.Tensor,+ memory: torch.Tensor,memory_spatial_shapes: list[tuple[int, int]],memory_level_start_index: list[int],bbox_head: nn.ModuleList,score_head: nn.ModuleList,query_pos_head: nn.Module,- attn_mask: Optional[Tensor] = None,- memory_mask: Optional[Tensor] = None,- ) -> tuple[Tensor, Tensor]:- output: Tensor = tgt- dec_out_bboxes: list[Tensor] = []- dec_out_logits: list[Tensor] = []+ attn_mask: Optional[torch.Tensor] = None,+ memory_mask: Optional[torch.Tensor] = None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ output: torch.Tensor = tgt+ dec_out_bboxes: list[torch.Tensor] = []+ dec_out_logits: list[torch.Tensor] = []ref_points_detach = torch.sigmoid(ref_points_unact)for i, layer in enumerate(self.layers):ref_points_input = ref_points_detach.unsqueeze(2)- query_pos_embed: Tensor = query_pos_head(ref_points_detach)+ query_pos_embed: torch.Tensor = query_pos_head(ref_points_detach)output = layer(output,@@ -280,7 +286,7 @@ class TransformerDecoder(Module):return torch.stack(dec_out_bboxes), torch.stack(dec_out_logits)-class RTDETRHead(Module):+class RTDETRHead(nn.Module):def __init__(self,num_classes: int,@@ -342,7 +348,7 @@ class RTDETRHead(Module):[MLP(hidden_dim, hidden_dim, 4, num_layers=3) for _ in range(num_decoder_layers)])- def forward(self, feats: Tensor) -> tuple[Tensor, Tensor]:+ def forward(self, feats: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:# input projection and embeddingmemory, spatial_shapes, level_start_index = self._get_encoder_input(feats)@@ -368,9 +374,9 @@ class RTDETRHead(Module):return out_logits[-1], out_bboxes[-1]- def _get_encoder_input(self, feats: Tensor) -> tuple[Tensor, list[tuple[int, int]], list[int]]:+ def _get_encoder_input(self, feats: torch.Tensor) -> tuple[torch.Tensor, list[tuple[int, int]], list[int]]:# get projection features- proj_feats: list[Tensor] = [self.input_proj[i](feat) for i, feat in enumerate(feats)]+ proj_feats: list[torch.Tensor] = [self.input_proj[i](feat) for i, feat in enumerate(feats)]if self.num_levels > len(proj_feats):len_srcs = len(proj_feats)@@ -381,7 +387,7 @@ class RTDETRHead(Module):proj_feats.append(self.input_proj[i](proj_feats[-1]))# get encoder inputs- feat_flatten_list: list[Tensor] = []+ feat_flatten_list: list[torch.Tensor] = []spatial_shapes: list[tuple[int, int]] = []level_start_index: list[int] = [0]@@ -395,18 +401,18 @@ class RTDETRHead(Module):level_start_index.append(h * w + level_start_index[-1])# [b, l, c]- feat_flatten: Tensor = concatenate(feat_flatten_list, 1)+ feat_flatten: torch.Tensor = torch.cat(feat_flatten_list, 1)level_start_index.pop()return feat_flatten, spatial_shapes, level_start_indexdef _get_decoder_input(self,- memory: Tensor,+ memory: torch.Tensor,spatial_shapes: list[tuple[int, int]],- denoising_class: Optional[Tensor] = None,- denoising_bbox_unact: Optional[Tensor] = None,- ) -> tuple[Tensor, Tensor, Tensor, Tensor]:+ denoising_class: Optional[torch.Tensor] = None,+ denoising_bbox_unact: Optional[torch.Tensor] = None,+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:# prepare input for decoder# TODO: cache anchors and valid_mask as buffersanchors, valid_mask = self._generate_anchors(spatial_shapes, device=memory.device, dtype=memory.dtype)@@ -448,7 +454,7 @@ class RTDETRHead(Module):eps: float = 0.01,device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,- ) -> tuple[Tensor, Tensor]:+ ) -> tuple[torch.Tensor, torch.Tensor]:"""Generate anchors for RT-DETR.Args:@@ -463,7 +469,7 @@ class RTDETRHead(Module):"""# TODO: might make this (or some parts of it) into a separate reusable function- anchors_list: list[Tensor] = []+ anchors_list: list[torch.Tensor] = []for i, (h, w) in enumerate(spatial_shapes):# TODO: fix later kornia.utils.create_meshgrid()@@ -480,9 +486,9 @@ class RTDETRHead(Module):grid_xy = (grid_xy + 0.5) / wh # normalize to [0, 1]grid_wh = torch.ones_like(grid_xy) * grid_size * (2.0**i)- anchors_list.append(concatenate([grid_xy, grid_wh], -1).reshape(-1, h * w, 4))+ anchors_list.append(torch.cat([grid_xy, grid_wh], -1).reshape(-1, h * w, 4))- anchors = concatenate(anchors_list, 1)+ anchors = torch.cat(anchors_list, 1)valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)anchors = torch.log(anchors / (1 - anchors)) # anchors.logit() fails ONNX exportdiff --git a/kornia/contrib/models/rt_detr/model.py b/kornia/models/rt_detr/model.pysimilarity index 95%rename from kornia/contrib/models/rt_detr/model.pyrename to kornia/models/rt_detr/model.pyindex d23cdeb11..1e1fe3a17 100644--- a/kornia/contrib/models/rt_detr/model.py+++ b/kornia/models/rt_detr/model.py@@ -26,12 +26,11 @@ from typing import Optionalimport torch-from kornia.contrib.models.base import ModelBase-from kornia.contrib.models.rt_detr.architecture.hgnetv2 import PPHGNetV2-from kornia.contrib.models.rt_detr.architecture.hybrid_encoder import HybridEncoder-from kornia.contrib.models.rt_detr.architecture.resnet_d import ResNetD-from kornia.contrib.models.rt_detr.architecture.rtdetr_head import RTDETRHead-from kornia.core import Tensor+from kornia.models.base import ModelBase+from kornia.models.rt_detr.architecture.hgnetv2 import PPHGNetV2+from kornia.models.rt_detr.architecture.hybrid_encoder import HybridEncoder+from kornia.models.rt_detr.architecture.resnet_d import ResNetD+from kornia.models.rt_detr.architecture.rtdetr_head import RTDETRHeadURLs = {"rtdetr_r18vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r18vd_dec3_6x_coco_from_paddle.pth",@@ -251,7 +250,7 @@ class RTDETR(ModelBase[RTDETRConfig]):return new_name- def _state_dict_proc(state_dict: dict[str, Tensor]) -> dict[str, Tensor]:+ def _state_dict_proc(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:state_dict = state_dict["ema"]["module"] # type:ignorenew_state_dict = {}@@ -279,7 +278,7 @@ class RTDETR(ModelBase[RTDETRConfig]):model = RTDETR.from_config(RTDETRConfig.from_name(model_name, num_classes))return model- def forward(self, images: Tensor) -> tuple[Tensor, Tensor]:+ def forward(self, images: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:"""Detect objects in an image.Args:diff --git a/kornia/contrib/models/rt_detr/post_processor.py b/kornia/models/rt_detr/post_processor.pysimilarity index 88%rename from kornia/contrib/models/rt_detr/post_processor.pyrename to kornia/models/rt_detr/post_processor.pyindex e57323885..969544432 100644--- a/kornia/contrib/models/rt_detr/post_processor.py+++ b/kornia/models/rt_detr/post_processor.py@@ -22,12 +22,12 @@ from __future__ import annotationsfrom typing import Optional, Unionimport torch+from torch import nn-from kornia.core import Module, Tensor, concatenate, tensor-from kornia.models.detection.utils import BoxFiltering+from kornia.contrib.object_detection import BoxFiltering-def mod(a: Tensor, b: int) -> Tensor:+def mod(a: torch.Tensor, b: int) -> torch.Tensor:"""Compute the element-wise remainder of tensor `a` divided by integer `b`.This function requires `a` to be a `torch.Tensor` and `b` to be an `int`.@@ -51,7 +51,7 @@ def mod(a: Tensor, b: int) -> Tensor:# TODO: deprecate the confidence threshold and add the num_top_queries as a parameter and num_classes as a parameter-class DETRPostProcessor(Module):+class DETRPostProcessor(nn.Module):def __init__(self,confidence_threshold: Optional[float] = None,@@ -66,10 +66,13 @@ class DETRPostProcessor(Module):self.confidence_filtering = confidence_filteringself.num_top_queries = num_top_queriesself.box_filtering = BoxFiltering(- tensor(confidence_threshold) if confidence_threshold is not None else None, filter_as_zero=filter_as_zero+ torch.tensor(confidence_threshold) if confidence_threshold is not None else None,+ filter_as_zero=filter_as_zero,)- def forward(self, logits: Tensor, boxes: Tensor, original_sizes: Tensor) -> Union[Tensor, list[Tensor]]:+ def forward(+ self, logits: torch.Tensor, boxes: torch.Tensor, original_sizes: torch.Tensor+ ) -> Union[torch.Tensor, list[torch.Tensor]]:"""Post-process outputs from DETR.Args:@@ -94,7 +97,7 @@ class DETRPostProcessor(Module):# bboxes[..., :2] -= bboxes[..., 2:] * 0.5 # in-place operation is not torch.compile()-friendly# TODO: replace using kornia BoundingBoxcxcy, wh = boxes[..., :2], boxes[..., 2:]- boxes_xy = concatenate([cxcy - wh * 0.5, wh], -1)+ boxes_xy = torch.cat([cxcy - wh * 0.5, wh], -1)# Get dynamic size from the input tensor itselfsizes_wh = original_sizes[0].flip(0).unsqueeze(0).unsqueeze(0).repeat(1, 1, 2)@@ -109,7 +112,7 @@ class DETRPostProcessor(Module):index = index // self.num_classesboxes = boxes_xy.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes_xy.shape[-1]))- all_boxes = concatenate([labels[..., None], scores[..., None], boxes], -1)+ all_boxes = torch.cat([labels[..., None], scores[..., None], boxes], -1)if not self.confidence_filtering or self.confidence_threshold == 0:return all_boxesdiff --git a/kornia/contrib/models/sam/__init__.py b/kornia/models/sam/__init__.pysimilarity index 91%rename from kornia/contrib/models/sam/__init__.pyrename to kornia/models/sam/__init__.pyindex d16bedc4e..681ea9470 100644--- a/kornia/contrib/models/sam/__init__.py+++ b/kornia/models/sam/__init__.py@@ -20,4 +20,4 @@This subpackage provides SAM model classes and configuration for segmentation tasks."""-from kornia.contrib.models.sam.model import Sam, SamConfig, SamModelType+from kornia.models.sam.model import Sam, SamConfig, SamModelTypediff --git a/kornia/contrib/models/sam/architecture/__init__.py b/kornia/models/sam/architecture/__init__.pysimilarity index 100%rename from kornia/contrib/models/sam/architecture/__init__.pyrename to kornia/models/sam/architecture/__init__.pydiff --git a/kornia/contrib/models/sam/architecture/common.py b/kornia/models/sam/architecture/common.pysimilarity index 90%rename from kornia/contrib/models/sam/architecture/common.pyrename to kornia/models/sam/architecture/common.pyindex 525961dbe..ebc3abb22 100644--- a/kornia/contrib/models/sam/architecture/common.py+++ b/kornia/models/sam/architecture/common.py@@ -25,19 +25,18 @@ from __future__ import annotationsfrom typing import Any+import torchfrom torch import nn-from kornia.core import Module, Tensor--class MLPBlock(Module):- def __init__(self, embedding_dim: int, mlp_dim: int, act: type[Module] = nn.GELU) -> None:+class MLPBlock(nn.Module):+ def __init__(self, embedding_dim: int, mlp_dim: int, act: type[nn.Module] = nn.GELU) -> None:super().__init__()self.lin1 = nn.Linear(embedding_dim, mlp_dim)self.lin2 = nn.Linear(mlp_dim, embedding_dim)self.act = act()- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:return self.lin2(self.act(self.lin1(x)))diff --git a/kornia/contrib/models/sam/architecture/image_encoder.py b/kornia/models/sam/architecture/image_encoder.pysimilarity index 90%rename from kornia/contrib/models/sam/architecture/image_encoder.pyrename to kornia/models/sam/architecture/image_encoder.pyindex e0990ce75..e92fd9a1b 100644--- a/kornia/contrib/models/sam/architecture/image_encoder.py+++ b/kornia/models/sam/architecture/image_encoder.py@@ -29,13 +29,12 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.contrib.models.common import LayerNorm2d, window_partition, window_unpartition-from kornia.contrib.models.sam.architecture.common import MLPBlock-from kornia.core import Module, Tensor, zeros+from kornia.models.common import LayerNorm2d, window_partition, window_unpartition+from kornia.models.sam.architecture.common import MLPBlock# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa-class ImageEncoderViT(Module):+class ImageEncoderViT(nn.Module):def __init__(self,img_size: int = 1024,@@ -48,8 +47,8 @@ class ImageEncoderViT(Module):mlp_ratio: float = 4.0,out_chans: int = 256,qkv_bias: bool = True,- norm_layer: type[Module] = nn.LayerNorm,- act_layer: type[Module] = nn.GELU,+ norm_layer: type[nn.Module] = nn.LayerNorm,+ act_layer: type[nn.Module] = nn.GELU,use_abs_pos: bool = True,use_rel_pos: bool = False,rel_pos_zero_init: bool = True,@@ -90,7 +89,7 @@ class ImageEncoderViT(Module):self.pos_embed: Optional[nn.Parameter] = Noneif use_abs_pos:# Initialize absolute positional embedding with pretrain image size.- self.pos_embed = nn.Parameter(zeros(1, img_size // patch_size, img_size // patch_size, embed_dim))+ self.pos_embed = nn.Parameter(torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim))self.blocks = nn.ModuleList()for i in range(depth):@@ -115,7 +114,7 @@ class ImageEncoderViT(Module):LayerNorm2d(out_chans),)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:x = self.patch_embed(x)if self.pos_embed is not None:x = x + self.pos_embed@@ -128,7 +127,7 @@ class ImageEncoderViT(Module):return x-class Block(Module):+class Block(nn.Module):"""Transformer blocks with support of window attention and residual propagation blocks."""def __init__(@@ -137,8 +136,8 @@ class Block(Module):num_heads: int,mlp_ratio: float = 4.0,qkv_bias: bool = True,- norm_layer: type[Module] = nn.LayerNorm,- act_layer: type[Module] = nn.GELU,+ norm_layer: type[nn.Module] = nn.LayerNorm,+ act_layer: type[nn.Module] = nn.GELU,use_rel_pos: bool = False,rel_pos_zero_init: bool = True,window_size: int = 0,@@ -175,7 +174,7 @@ class Block(Module):self.window_size = window_size- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:shortcut = xx = self.norm1(x)# Window partition@@ -194,7 +193,7 @@ class Block(Module):return x-class Attention(Module):+class Attention(nn.Module):"""Multi-head Attention block with relative position embeddings."""def __init__(@@ -228,10 +227,10 @@ class Attention(Module):self.use_rel_pos = use_rel_posif self.use_rel_pos and isinstance(input_size, tuple):# initialize relative positional embeddings- self.rel_pos_h = nn.Parameter(zeros(2 * input_size[0] - 1, head_dim))- self.rel_pos_w = nn.Parameter(zeros(2 * input_size[1] - 1, head_dim))+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:B, H, W, _ = x.shape# qkv with shape (3, B, nHead, H * W, C)qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)@@ -250,7 +249,7 @@ class Attention(Module):return x-def get_rel_pos(q_size: int, k_size: int, rel_pos: Tensor) -> Tensor:+def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:"""Get relative positional embeddings according to the relative positions of query and key sizes.Args:@@ -282,8 +281,13 @@ def get_rel_pos(q_size: int, k_size: int, rel_pos: Tensor) -> Tensor:def add_decomposed_rel_pos(- attn: Tensor, q: Tensor, rel_pos_h: Tensor, rel_pos_w: Tensor, q_size: tuple[int, int], k_size: tuple[int, int]-) -> Tensor:+ attn: torch.Tensor,+ q: torch.Tensor,+ rel_pos_h: torch.Tensor,+ rel_pos_w: torch.Tensor,+ q_size: tuple[int, int],+ k_size: tuple[int, int],+) -> torch.Tensor:"""Calculate decomposed Relative Positional Embeddings.from :paper:`mvitv2`.@@ -319,7 +323,7 @@ def add_decomposed_rel_pos(return attn-class PatchEmbed(Module):+class PatchEmbed(nn.Module):"""Image to Patch Embedding."""def __init__(@@ -344,7 +348,7 @@ class PatchEmbed(Module):self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:x = self.proj(x)# B C H W -> B H W Cx = x.permute(0, 2, 3, 1)diff --git a/kornia/contrib/models/sam/architecture/mask_decoder.py b/kornia/models/sam/architecture/mask_decoder.pysimilarity index 86%rename from kornia/contrib/models/sam/architecture/mask_decoder.pyrename to kornia/models/sam/architecture/mask_decoder.pyindex 2120dad41..a4e55e54e 100644--- a/kornia/contrib/models/sam/architecture/mask_decoder.py+++ b/kornia/models/sam/architecture/mask_decoder.py@@ -26,18 +26,17 @@ from __future__ import annotationsimport torchfrom torch import nn-from kornia.contrib.models.common import MLP, LayerNorm2d-from kornia.core import Module, Tensor, concatenate, stack+from kornia.models.common import MLP, LayerNorm2d-class MaskDecoder(Module):+class MaskDecoder(nn.Module):def __init__(self,*,transformer_dim: int,- transformer: Module,+ transformer: nn.Module,num_multimask_outputs: int = 3,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,iou_head_depth: int = 3,iou_head_hidden_dim: int = 256,) -> None:@@ -77,12 +76,12 @@ class MaskDecoder(Module):def forward(self,- image_embeddings: Tensor,- image_pe: Tensor,- sparse_prompt_embeddings: Tensor,- dense_prompt_embeddings: Tensor,+ image_embeddings: torch.Tensor,+ image_pe: torch.Tensor,+ sparse_prompt_embeddings: torch.Tensor,+ dense_prompt_embeddings: torch.Tensor,multimask_output: bool,- ) -> tuple[Tensor, Tensor]:+ ) -> tuple[torch.Tensor, torch.Tensor]:"""Predict masks given image and prompt embeddings.Args:@@ -117,19 +116,19 @@ class MaskDecoder(Module):def predict_masks(self,- image_embeddings: Tensor,- image_pe: Tensor,- sparse_prompt_embeddings: Tensor,- dense_prompt_embeddings: Tensor,- ) -> tuple[Tensor, Tensor]:+ image_embeddings: torch.Tensor,+ image_pe: torch.Tensor,+ sparse_prompt_embeddings: torch.Tensor,+ dense_prompt_embeddings: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:"""Predicts masks.See 'forward' for more details."""# Concatenate output tokens- output_tokens = concatenate([self.iou_token.weight, self.mask_tokens.weight], dim=0)+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)output_tokens = output_tokens[None, ...].expand(sparse_prompt_embeddings.size(0), -1, -1)- tokens = concatenate((output_tokens, sparse_prompt_embeddings), dim=1)+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)# Expand per-image data in batch direction to be per-masksrc = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)@@ -145,10 +144,10 @@ class MaskDecoder(Module):# Upscale mask embeddings and predict masks using the mask tokenssrc = src.transpose(1, 2).view(b, c, h, w)upscaled_embedding = self.output_upscaling(src)- hyper_in_list: list[Tensor] = []+ hyper_in_list: list[torch.Tensor] = []for i in range(self.num_mask_tokens):hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))- hyper_in = stack(hyper_in_list, dim=1)+ hyper_in = torch.stack(hyper_in_list, dim=1)b, c, h, w = upscaled_embedding.shapemasks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)diff --git a/kornia/contrib/models/sam/architecture/prompt_encoder.py b/kornia/models/sam/architecture/prompt_encoder.pysimilarity index 82%rename from kornia/contrib/models/sam/architecture/prompt_encoder.pyrename to kornia/models/sam/architecture/prompt_encoder.pyindex 6d3d743d5..55c00485a 100644--- a/kornia/contrib/models/sam/architecture/prompt_encoder.py+++ b/kornia/models/sam/architecture/prompt_encoder.py@@ -29,18 +29,17 @@ from typing import Optionalimport torchfrom torch import nn-from kornia.contrib.models.common import LayerNorm2d-from kornia.core import Device, Module, Tensor, concatenate, cos, sin, stack, zeros+from kornia.models.common import LayerNorm2d-class PromptEncoder(Module):+class PromptEncoder(nn.Module):def __init__(self,embed_dim: int,image_embedding_size: tuple[int, int],input_image_size: tuple[int, int],mask_in_chans: int,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,) -> None:"""Encode prompts for input to SAM's mask decoder.@@ -75,7 +74,7 @@ class PromptEncoder(Module):)self.no_mask_embed = nn.Embedding(1, embed_dim)- def get_dense_pe(self) -> Tensor:+ def get_dense_pe(self) -> torch.Tensor:"""Return the positional encoding used to encode point prompts, applied to a dense set of points the shapeof the image encoding.@@ -85,14 +84,14 @@ class PromptEncoder(Module):""" # noqa: D205return self.pe_layer(self.image_embedding_size)[None, ...]- def _embed_points(self, points: Tensor, labels: Tensor, pad: bool) -> Tensor:+ def _embed_points(self, points: torch.Tensor, labels: torch.Tensor, pad: bool) -> torch.Tensor:"""Embeds point prompts."""points = points + 0.5 # Shift to center of pixelif pad:- padding_point = zeros((points.shape[0], 1, 2), device=points.device)+ padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)- points = concatenate([points, padding_point], dim=1)- labels = concatenate([labels, padding_label], dim=1)+ points = torch.cat([points, padding_point], dim=1)+ labels = torch.cat([labels, padding_label], dim=1)point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)point_embedding[labels == -1] = 0.0point_embedding[labels == -1] += self.not_a_point_embed.weight@@ -100,7 +99,7 @@ class PromptEncoder(Module):point_embedding[labels == 1] += self.point_embeddings[1].weightreturn point_embedding- def _embed_boxes(self, boxes: Tensor) -> Tensor:+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:"""Embeds box prompts."""boxes = boxes + 0.5 # Shift to center of pixelcoords = boxes.reshape(-1, 2, 2)@@ -109,13 +108,16 @@ class PromptEncoder(Module):corner_embedding[:, 1, :] += self.point_embeddings[3].weightreturn corner_embedding- def _embed_masks(self, masks: Tensor) -> Tensor:+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:"""Embeds mask inputs."""mask_embedding = self.mask_downscaling(masks)return mask_embeddingdef _get_batch_size(- self, points: Optional[tuple[Tensor, Tensor]], boxes: Optional[Tensor], masks: Optional[Tensor]+ self,+ points: Optional[tuple[torch.Tensor, torch.Tensor]],+ boxes: Optional[torch.Tensor],+ masks: Optional[torch.Tensor],) -> int:"""Get the batch size of the output given the batch size of the input prompts."""if points is not None:@@ -127,12 +129,15 @@ class PromptEncoder(Module):else:return 1- def _get_device(self) -> Device:+ def _get_device(self) -> torch.device:return self.point_embeddings[0].weight.devicedef forward(- self, points: Optional[tuple[Tensor, Tensor]], boxes: Optional[Tensor], masks: Optional[Tensor]- ) -> tuple[Tensor, Tensor]:+ self,+ points: Optional[tuple[torch.Tensor, torch.Tensor]],+ boxes: Optional[torch.Tensor],+ masks: Optional[torch.Tensor],+ ) -> tuple[torch.Tensor, torch.Tensor]:"""Embeds different types of prompts, returning both sparse and dense embeddings.Args:@@ -151,10 +156,10 @@ class PromptEncoder(Module):if points is not None:coords, labels = pointspoint_embeddings = self._embed_points(coords, labels, pad=(boxes is None))- sparse_embeddings = concatenate([sparse_embeddings, point_embeddings], dim=1)+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)if boxes is not None:box_embeddings = self._embed_boxes(boxes)- sparse_embeddings = concatenate([sparse_embeddings, box_embeddings], dim=1)+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)if masks is not None:dense_embeddings = self._embed_masks(masks)@@ -166,7 +171,7 @@ class PromptEncoder(Module):return sparse_embeddings, dense_embeddings-class PositionEmbeddingRandom(Module):+class PositionEmbeddingRandom(nn.Module):"""Positional encoding using random spatial frequencies."""def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:@@ -175,16 +180,16 @@ class PositionEmbeddingRandom(Module):scale = 1.0self.register_buffer("positional_encoding_gaussian_matrix", scale * torch.randn((2, num_pos_feats)))- def _pe_encoding(self, coords: Tensor) -> Tensor:+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:"""Positionally encode points that are normalized to [0,1]."""# assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shapecoords = 2 * coords - 1coords = coords @ self.positional_encoding_gaussian_matrixcoords = 2 * pi * coords# outputs d_1 x ... x d_n x C shape- return concatenate([sin(coords), cos(coords)], dim=-1)+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)- def forward(self, size: tuple[int, int]) -> Tensor:+ def forward(self, size: tuple[int, int]) -> torch.Tensor:"""Generate positional encoding for a grid of the specified size."""h, w = size_dev = self.positional_encoding_gaussian_matrix.device@@ -195,10 +200,10 @@ class PositionEmbeddingRandom(Module):y_embed = y_embed / hx_embed = x_embed / w- pe = self._pe_encoding(stack([x_embed, y_embed], dim=-1))+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))return pe.permute(2, 0, 1) # C x H x W- def forward_with_coords(self, coords_input: Tensor, image_size: tuple[int, int]) -> Tensor:+ def forward_with_coords(self, coords_input: torch.Tensor, image_size: tuple[int, int]) -> torch.Tensor:"""Positionally encode points that are not normalized to [0,1]."""coords = coords_input.clone()coords[:, :, 0] = coords[:, :, 0] / image_size[1]diff --git a/kornia/contrib/models/sam/architecture/transformer.py b/kornia/models/sam/architecture/transformer.pysimilarity index 90%rename from kornia/contrib/models/sam/architecture/transformer.pyrename to kornia/models/sam/architecture/transformer.pyindex d95b17f45..8c2767158 100644--- a/kornia/contrib/models/sam/architecture/transformer.py+++ b/kornia/models/sam/architecture/transformer.py@@ -25,21 +25,21 @@ from __future__ import annotationsimport math+import torchfrom torch import nn-from kornia.contrib.models.sam.architecture.common import MLPBlock-from kornia.core import Module, Tensorfrom kornia.core.check import KORNIA_CHECK+from kornia.models.sam.architecture.common import MLPBlock-class TwoWayTransformer(Module):+class TwoWayTransformer(nn.Module):def __init__(self,depth: int,embedding_dim: int,num_heads: int,mlp_dim: int,- activation: type[Module] = nn.ReLU,+ activation: type[nn.Module] = nn.ReLU,attention_downsample_rate: int = 2,) -> None:"""Construct a transformer decoder that attends to an input image using queries whose positional embedding is@@ -76,7 +76,9 @@ class TwoWayTransformer(Module):self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)self.norm_final_attn = nn.LayerNorm(embedding_dim)- def forward(self, image_embedding: Tensor, image_pe: Tensor, point_embedding: Tensor) -> tuple[Tensor, Tensor]:+ def forward(+ self, image_embedding: torch.Tensor, image_pe: torch.Tensor, point_embedding: torch.Tensor+ ) -> tuple[torch.Tensor, torch.Tensor]:"""Run forward.Args:@@ -113,13 +115,13 @@ class TwoWayTransformer(Module):return queries, keys-class TwoWayAttentionBlock(Module):+class TwoWayAttentionBlock(nn.Module):def __init__(self,embedding_dim: int,num_heads: int,mlp_dim: int = 2048,- activation: type[Module] = nn.ReLU,+ activation: type[nn.Module] = nn.ReLU,attention_downsample_rate: int = 2,skip_first_layer_pe: bool = False,) -> None:@@ -153,7 +155,9 @@ class TwoWayAttentionBlock(Module):self.skip_first_layer_pe = skip_first_layer_pe- def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> tuple[Tensor, Tensor]:+ def forward(+ self, queries: torch.Tensor, keys: torch.Tensor, query_pe: torch.Tensor, key_pe: torch.Tensor+ ) -> tuple[torch.Tensor, torch.Tensor]:# Self attention blockif self.skip_first_layer_pe:queries = self.self_attn(q=queries, k=queries, v=queries)@@ -185,7 +189,7 @@ class TwoWayAttentionBlock(Module):return queries, keys-class Attention(Module):+class Attention(nn.Module):"""Attention layer that allows for downscaling the embedding after projection to queries, keys, and values."""def __init__(self, embedding_dim: int, num_heads: int, downsample_rate: int = 1) -> None:@@ -200,17 +204,17 @@ class Attention(Module):self.v_proj = nn.Linear(embedding_dim, self.internal_dim)self.out_proj = nn.Linear(self.internal_dim, embedding_dim)- def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:+ def _separate_heads(self, x: torch.Tensor, num_heads: int) -> torch.Tensor:b, n, c = x.shapex = x.reshape(b, n, num_heads, c // num_heads)return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head- def _recombine_heads(self, x: Tensor) -> Tensor:+ def _recombine_heads(self, x: torch.Tensor) -> torch.Tensor:b, n_heads, n_tokens, c_per_head = x.shapex = x.transpose(1, 2)return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C- def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:+ def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:# Input projectionsq = self.q_proj(q)k = self.k_proj(k)diff --git a/kornia/contrib/models/sam/model.py b/kornia/models/sam/model.pysimilarity index 86%rename from kornia/contrib/models/sam/model.pyrename to kornia/models/sam/model.pyindex 8da174e26..bc2033009 100644--- a/kornia/contrib/models/sam/model.py+++ b/kornia/models/sam/model.py@@ -33,16 +33,15 @@ from typing import Any, Optionalimport torch-from kornia.contrib.models import SegmentationResults-from kornia.contrib.models.base import ModelBase-from kornia.contrib.models.sam.architecture.common import LayerNorm-from kornia.contrib.models.sam.architecture.image_encoder import ImageEncoderViT-from kornia.contrib.models.sam.architecture.mask_decoder import MaskDecoder-from kornia.contrib.models.sam.architecture.prompt_encoder import PromptEncoder-from kornia.contrib.models.sam.architecture.transformer import TwoWayTransformer-from kornia.contrib.models.tiny_vit import TinyViT-from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE+from kornia.models.base import ModelBase+from kornia.models.sam.architecture.common import LayerNorm+from kornia.models.sam.architecture.image_encoder import ImageEncoderViT+from kornia.models.sam.architecture.mask_decoder import MaskDecoder+from kornia.models.sam.architecture.prompt_encoder import PromptEncoder+from kornia.models.sam.architecture.transformer import TwoWayTransformer+from kornia.models.structures import SegmentationResults+from kornia.models.tiny_vit import TinyViTclass SamModelType(Enum):@@ -136,7 +135,7 @@ class Sam(ModelBase[SamConfig]):The respective SAM modelExample:- >>> from kornia.contrib.models.sam import SamConfig+ >>> from kornia.models.sam import SamConfig>>> sam_model = Sam.from_config(SamConfig('vit_b'))"""@@ -235,7 +234,7 @@ class Sam(ModelBase[SamConfig]):@torch.no_grad()def forward(- self, images: Tensor, batched_prompts: list[dict[str, Any]], multimask_output: bool+ self, images: torch.Tensor, batched_prompts: list[dict[str, Any]], multimask_output: bool) -> list[SegmentationResults]:"""Predicts masks end-to-end from provided images and prompts.@@ -255,25 +254,26 @@ class Sam(ModelBase[SamConfig]):the following keys. If it does not have the respective prompt, it should not be includedin this dictionary. The options are:- - "points": tuple of (Tensor, Tensor) within the coordinate keypoints and their respective labels.- the tuple should look like (keypoints, labels), where:+ - "points": tuple of (torch.Tensor, torch.Tensor) within the coordinate keypoints+ and their respective labels. The tuple should look like (keypoints, labels), where the keypoints+ (a tensor) are a batched point prompts for this image, with shape :math:`(K, N, 2)`. Already+ transformed to the input frame of the model. The labels (a tensor) are a batched labels for point+ prompts, with shape :math:`(K, N)`. Where 1 indicates a foreground point and 0 indicates a background+ point.- - The keypoints (a tensor) are a batched point prompts for this image, with shape- :math:`(K, N, 2)`. Already transformed to the input frame of the model.- - The labels (a tensor) are a batched labels for point prompts, with shape :math:`(K, N)`.- Where 1 indicates a foreground point and 0 indicates a background point.+ - "boxes": (torch.Tensor) Batched box inputs, with shape :math:`(K, 4)`.+ Already transformed to the input frame of the model.- - "boxes": (Tensor) Batched box inputs, with shape :math:`(K, 4)`. Already transformed to the input- frame of the model.- - "mask_inputs": (Tensor) Batched mask inputs to the model, in the form :math:`(K, 1, H, W)`.+ - "mask_inputs": (torch.Tensor) Batched mask inputs to the model, in the form :math:`(K, 1, H, W)`.multimask_output: Whether the model should predict multiple disambiguating masks, or return a single mask.Returns:- A list over input images, where each element is as SegmentationResults the following.+ A list over input images, where each element is as SegmentationResults the following:+- logits: Low resolution logits with shape :math:`(K, C, H, W)`. Can be passed as mask input to- subsequent iterations of prediction. Where :math:`K` is the number of input prompts,- :math:`C` is determined by multimask_output, and :math:`H=W=256` are the model output size.+ subsequent iterations of prediction. Where :math:`K` is the number of input prompts,+ :math:`C` is determined by multimask_output, and :math:`H=W=256` are the model output size.- scores: The model's predictions of mask quality (iou prediction), in shape BxC."""diff --git a/kornia/models/segmentation/base.py b/kornia/models/segmentation/base.pyindex 31be4211a..988635f8c 100644--- a/kornia/models/segmentation/base.py+++ b/kornia/models/segmentation/base.py@@ -22,7 +22,6 @@ from typing import ClassVar, Optional, Unionimport torchimport kornia-from kornia.core import Tensorfrom kornia.core.external import PILImage as Imagefrom kornia.models.base import ModelBase@@ -39,18 +38,18 @@ class SemanticSegmentation(ModelBase):ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]@torch.inference_mode()- def forward(self, images: Union[Tensor, list[Tensor]]) -> Union[Tensor, list[Tensor]]:+ def forward(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]:"""Forward pass of the semantic segmentation model.Args:- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.+ images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.Returns:output tensor."""- outputs: Union[Tensor, list[Tensor]]+ outputs: Union[torch.Tensor, list[torch.Tensor]]if isinstance(images,@@ -72,7 +71,7 @@ class SemanticSegmentation(ModelBase):return outputs- def get_colormap(self, num_classes: int, colormap: str = "random", manual_seed: int = 2147) -> Tensor:+ def get_colormap(self, num_classes: int, colormap: str = "random", manual_seed: int = 2147) -> torch.Tensor:"""Get a color map of size num_classes.Args:@@ -94,7 +93,7 @@ class SemanticSegmentation(ModelBase):return colors- def visualize_output(self, semantic_mask: Tensor, colors: Tensor) -> Tensor:+ def visualize_output(self, semantic_mask: torch.Tensor, colors: torch.Tensor) -> torch.Tensor:"""Visualize the output of the segmentation model.Args:@@ -142,19 +141,19 @@ class SemanticSegmentation(ModelBase):def visualize(self,- images: Union[Tensor, list[Tensor]],- semantic_masks: Optional[Union[Tensor, list[Tensor]]] = None,+ images: Union[torch.Tensor, list[torch.Tensor]],+ semantic_masks: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,output_type: str = "torch",colormap: str = "random",manual_seed: int = 2147,- ) -> Union[Tensor, list[Tensor], list[Image.Image]]: # type: ignore+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore"""Visualize the segmentation masks.Args:- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.- semantic_masks: If list of segmentation masks. Each mask is a Tensor with shape :math:`(C, H, W)`.- If Tensor, a Tensor with shape :math:`(B, C, H, W)`.+ images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.+ semantic_masks: If list of segmentation masks. Each mask is a torch.Tensor with shape :math:`(C, H, W)`.+ If torch.Tensor, a torch.Tensor with shape :math:`(B, C, H, W)`.output_type: The type of output, can be "torch" or "PIL".colormap: The colormap to use, can be "random" or a custom color map.manual_seed: The manual seed to use for the colormap.@@ -163,7 +162,7 @@ class SemanticSegmentation(ModelBase):if semantic_masks is None:semantic_masks = self.forward(images)- outputs: Union[Tensor, list[Tensor]]+ outputs: Union[torch.Tensor, list[torch.Tensor]]if isinstance(semantic_masks,(@@ -184,12 +183,12 @@ class SemanticSegmentation(ModelBase):colors = self.get_colormap(semantic_masks.size(1), colormap, manual_seed=manual_seed)outputs = self.visualize_output(semantic_masks, colors)- return self._tensor_to_type(outputs, output_type, is_batch=True if isinstance(outputs, Tensor) else False)+ return self._tensor_to_type(outputs, output_type, is_batch=True if isinstance(outputs, torch.Tensor) else False)def save(self,- images: Union[Tensor, list[Tensor]],- semantic_masks: Optional[Union[Tensor, list[Tensor]]] = None,+ images: Union[torch.Tensor, list[torch.Tensor]],+ semantic_masks: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,directory: Optional[str] = None,output_type: str = "torch",colormap: str = "random",@@ -198,10 +197,10 @@ class SemanticSegmentation(ModelBase):"""Save the segmentation results.Args:- images: If list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.- If Tensor, a Tensor with shape :math:`(B, 3, H, W)`.- semantic_masks: If list of segmentation masks. Each mask is a Tensor with shape :math:`(C, H, W)`.- If Tensor, a Tensor with shape :math:`(B, C, H, W)`.+ images: If list of RGB images. Each image is a torch.Tensor with shape :math:`(3, H, W)`.+ If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.+ semantic_masks: If list of segmentation masks. Each mask is a torch.Tensor with shape :math:`(C, H, W)`.+ If torch.Tensor, a torch.Tensor with shape :math:`(B, C, H, W)`.directory: The directory to save the results.output_type: The type of output, can be "torch" or "PIL".colormap: The colormap to use, can be "random" or a custom color map.@@ -209,8 +208,8 @@ class SemanticSegmentation(ModelBase):"""colored_masks = self.visualize(images, semantic_masks, output_type, colormap=colormap, manual_seed=manual_seed)- overlaid: Union[Tensor, list[Tensor]]- if isinstance(images, Tensor) and isinstance(colored_masks, Tensor):+ overlaid: Union[torch.Tensor, list[torch.Tensor]]+ if isinstance(images, torch.Tensor) and isinstance(colored_masks, torch.Tensor):overlaid = kornia.enhance.add_weighted(images, 0.5, colored_masks, 0.5, 1.0)elif isinstance(images,@@ -229,7 +228,7 @@ class SemanticSegmentation(ModelBase):for i in range(len(images)):overlaid.append(kornia.enhance.add_weighted(images[i][None], 0.5, colored_masks[i][None], 0.5, 1.0)[0])else:- raise ValueError(f"`images` should be a Tensor or a list of Tensors. Got {type(images)}")+ raise ValueError(f"`images` should be a torch.Tensor or a list of Tensors. Got {type(images)}")self._save_outputs(images, directory, suffix="_src")self._save_outputs(colored_masks, directory, suffix="_mask")diff --git a/kornia/models/segmentation/segmentation_models.py b/kornia/models/segmentation/segmentation_models.pyindex c96c38a99..d90f15c75 100644--- a/kornia/models/segmentation/segmentation_models.py+++ b/kornia/models/segmentation/segmentation_models.py@@ -19,10 +19,10 @@ from __future__ import annotationsfrom typing import Any, Optional+import torchfrom torch import nnimport kornia-from kornia.core import Module, tensorfrom kornia.core.external import segmentation_models_pytorch as smpfrom .base import SemanticSegmentation@@ -84,7 +84,7 @@ class SegmentationModelsBuilder:@staticmethoddef get_preprocessing_pipeline(preproc_params: dict[str, Any]) -> kornia.augmentation.container.ImageSequential:# Ensure the color space transformation is ONNX-friendly- proc_sequence: list[Module] = []+ proc_sequence: list[nn.Module] = []input_space = preproc_params["input_space"]if input_space == "BGR":proc_sequence.append(kornia.color.BgrToRgb())@@ -104,14 +104,14 @@ class SegmentationModelsBuilder:# Handle mean and std normalizationif preproc_params["mean"] is not None:- mean = tensor([preproc_params["mean"]])+ mean = torch.tensor([preproc_params["mean"]])else:- mean = tensor(0.0)+ mean = torch.tensor(0.0)if preproc_params["std"] is not None:- std = tensor([preproc_params["std"]])+ std = torch.tensor([preproc_params["std"]])else:- std = tensor(1.0)+ std = torch.tensor(1.0)proc_sequence.append(kornia.enhance.Normalize(mean=mean, std=std))return kornia.augmentation.container.ImageSequential(*proc_sequence)diff --git a/kornia/models/super_resolution/small_sr.py b/kornia/models/small_sr.pysimilarity index 73%rename from kornia/models/super_resolution/small_sr.pyrename to kornia/models/small_sr.pyindex b6e5f5b81..a0c1c1efd 100644--- a/kornia/models/super_resolution/small_sr.py+++ b/kornia/models/small_sr.py@@ -15,23 +15,17 @@# limitations under the License.#-from typing import Optional-import torchfrom torch import nnfrom kornia.color.ycbcr import RgbToYcbcr, YcbcrToRgbfrom kornia.config import kornia_config-from kornia.core import Module, Tensor, concatenate-from kornia.models.utils import ResizePreProcessorfrom kornia.utils.download import CachedDownloader-from .base import SuperResolution-url = "https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch100-44c6958e.pth"-class SmallSRNet(Module):+class SmallSRNet(nn.Module):"""A small super-resolution model.This model uses the efficient sub-pixel convolution layer described in@@ -64,7 +58,7 @@ class SmallSRNet(Module):self.load_state_dict(pretrained_dict, strict=True)self.eval()- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:x = self.relu(self.conv1(x))x = self.relu(self.conv2(x))x = self.relu(self.conv3(x))@@ -72,7 +66,7 @@ class SmallSRNet(Module):return x-def weight_init(model: Module) -> None:+def weight_init(model: nn.Module) -> None:"""Initialize model weights."""torch.nn.init.orthogonal_(model.conv1.weight, torch.nn.init.calculate_gain("relu"))torch.nn.init.orthogonal_(model.conv2.weight, torch.nn.init.calculate_gain("relu"))@@ -80,7 +74,7 @@ def weight_init(model: Module) -> None:torch.nn.init.orthogonal_(model.conv4.weight)-class SmallSRNetWrapper(Module):+class SmallSRNetWrapper(nn.Module):def __init__(self, upscale_factor: int = 3, pretrained: bool = True) -> None:super().__init__()self.rgb_to_ycbcr = RgbToYcbcr()@@ -88,36 +82,11 @@ class SmallSRNetWrapper(Module):self.model = SmallSRNet(upscale_factor=upscale_factor, pretrained=pretrained)self.upscale_factor = upscale_factor- def forward(self, input: Tensor) -> Tensor:+ def forward(self, input: torch.Tensor) -> torch.Tensor:ycbcr = self.rgb_to_ycbcr(input)y, cb, cr = ycbcr.split(1, dim=1)out_y = self.model(y)out_cb = torch.nn.functional.interpolate(cb, scale_factor=self.upscale_factor, mode="bicubic")out_cr = torch.nn.functional.interpolate(cr, scale_factor=self.upscale_factor, mode="bicubic")- out = concatenate([out_y, out_cb, out_cr], dim=1)+ out = torch.cat([out_y, out_cb, out_cr], dim=1)return self.ycbcr_to_rgb(out)---class SmallSRBuilder:- @staticmethod- def build(- model_name: str = "small_sr", pretrained: bool = True, upscale_factor: int = 3, image_size: Optional[int] = None- ) -> SuperResolution:- if model_name.lower() == "small_sr":- model = SmallSRNetWrapper(upscale_factor, pretrained=pretrained)- else:- raise ValueError(f"Model {model_name} not found. Please choose from 'small_sr'.")-- sr = SuperResolution(- model,- pre_processor=ResizePreProcessor(224, 224),- post_processor=nn.Identity(),- name=model_name,- )- if image_size is None:- sr.pseudo_image_size = 224- else:- sr.input_image_size = image_size- sr.output_image_size = image_size * 3- sr.pseudo_image_size = image_size- return srdiff --git a/kornia/contrib/models/structures.py b/kornia/models/structures.pysimilarity index 89%rename from kornia/contrib/models/structures.pyrename to kornia/models/structures.pyindex 0bb2fce66..f2355d9a3 100644--- a/kornia/contrib/models/structures.py+++ b/kornia/models/structures.py@@ -20,7 +20,8 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Optional-from kornia.core import Tensor+import torch+from kornia.core.check import KORNIA_CHECKfrom kornia.geometry.transform import resize@@ -36,12 +37,12 @@ class SegmentationResults:"""- logits: Tensor- scores: Tensor+ logits: torch.Tensor+ scores: torch.Tensormask_threshold: float = 0.0@property- def binary_masks(self) -> Tensor:+ def binary_masks(self) -> torch.Tensor:"""Binary mask generated from logits considering the mask_threshold.Shape will be the same of logits :math:`(B, C, H, W)` where :math:`C` is the number masks predicted.@@ -59,7 +60,7 @@ class SegmentationResults:def original_res_logits(self, input_size: tuple[int, int], original_size: tuple[int, int], image_size_encoder: Optional[tuple[int, int]]- ) -> Tensor:+ ) -> torch.Tensor:"""Remove padding and upscale the logits to the original image size.Resize to image encoder input -> remove padding (bottom and right) -> Resize to original size@@ -91,7 +92,7 @@ class SegmentationResults:"""Realize a squeeze for the dim given for all properties."""self.logits = self.logits.squeeze(dim)self.scores = self.scores.squeeze(dim)- if isinstance(self._original_res_logits, Tensor):+ if isinstance(self._original_res_logits, torch.Tensor):self._original_res_logits = self._original_res_logits.squeeze(dim)return self@@ -109,20 +110,20 @@ class Prompts:"""- points: Optional[tuple[Tensor, Tensor]] = None- boxes: Optional[Tensor] = None- masks: Optional[Tensor] = None+ points: Optional[tuple[torch.Tensor, torch.Tensor]] = None+ boxes: Optional[torch.Tensor] = None+ masks: Optional[torch.Tensor] = Nonedef __post_init__(self) -> None:- if isinstance(self.keypoints, Tensor) and isinstance(self.boxes, Tensor):+ if isinstance(self.keypoints, torch.Tensor) and isinstance(self.boxes, torch.Tensor):KORNIA_CHECK(self.keypoints.shape[0] == self.boxes.shape[0], "The prompts should have the same batch size!")@property- def keypoints(self) -> Optional[Tensor]:+ def keypoints(self) -> Optional[torch.Tensor]:"""The keypoints from the `points`."""return self.points[0] if isinstance(self.points, tuple) else None@property- def keypoints_labels(self) -> Optional[Tensor]:+ def keypoints_labels(self) -> Optional[torch.Tensor]:"""The keypoints labels from the `points`."""return self.points[1] if isinstance(self.points, tuple) else Nonediff --git a/kornia/models/super_resolution/__init__.py b/kornia/models/super_resolution/__init__.pydeleted file mode 100644index 5c01e6e94..000000000--- a/kornia/models/super_resolution/__init__.py+++ /dev/null@@ -1,25 +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.-#--"""Super-resolution models submodule for Kornia.--This package provides model architectures and utilities for image super-resolution tasks.-"""--from .base import *-from .rrdbnet import *-from .small_sr import *diff --git a/kornia/models/super_resolution/rrdbnet.py b/kornia/models/super_resolution/rrdbnet.pydeleted file mode 100644index 1ed509e75..000000000--- a/kornia/models/super_resolution/rrdbnet.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.-#--import torch-from torch import nn--from kornia.config import kornia_config-from kornia.core.external import basicsr-from kornia.models.utils import OutputRangePostProcessor-from kornia.utils.download import CachedDownloader--from .base import SuperResolution--__all__ = ["RRDBNetBuilder"]--URLs = {- "RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",- "RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",- "RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",- "RealESRGAN_x2plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",-}---class RRDBNetBuilder:- @staticmethod- def build(model_name: str = "RealESRNet_x4plus", pretrained: bool = True) -> SuperResolution:- if model_name == "RealESRGAN_x4plus":- model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore- num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4- )- elif model_name == "RealESRNet_x4plus":- model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore- num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4- )- elif model_name == "RealESRGAN_x4plus_anime_6B":- model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore- num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4- )- elif model_name == "RealESRGAN_x2plus":- model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore- num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2- )- else:- raise ValueError(- f"Model {model_name} not found. Please choose from "- "'RealESRGAN_x4plus', 'RealESRNet_x4plus', 'RealESRGAN_x4plus_anime_6B', 'RealESRGAN_x2plus'."- )-- model_path = None- if pretrained:- url = URLs[model_name]- model_path = CachedDownloader.download_to_cache(- url, model_name, download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir- )- model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu"))["params_ema"], strict=True)- model.eval()-- return SuperResolution(- model,- pre_processor=nn.Identity(),- post_processor=OutputRangePostProcessor(min_val=0.0, max_val=1.0),- name=model_name,- )diff --git a/kornia/contrib/models/tiny_vit.py b/kornia/models/tiny_vit.pysimilarity index 93%rename from kornia/contrib/models/tiny_vit.pyrename to kornia/models/tiny_vit.pyindex 69a07b344..4624fccfb 100644--- a/kornia/contrib/models/tiny_vit.py+++ b/kornia/models/tiny_vit.py@@ -28,9 +28,8 @@ import torch.nn.functional as Ffrom torch import nnfrom torch.utils import checkpoint-from kornia.contrib.models.common import DropPath, LayerNorm2d, window_partition, window_unpartition-from kornia.core import Module, Tensorfrom kornia.core.check import KORNIA_CHECK+from kornia.models.common import DropPath, LayerNorm2d, window_partition, window_unpartitiondef _make_pair(x: int | tuple[int, int]) -> tuple[int, int]:@@ -46,7 +45,7 @@ class ConvBN(nn.Sequential):stride: int = 1,padding: int = 0,groups: int = 1,- activation: type[Module] = nn.Identity,+ activation: type[nn.Module] = nn.Identity,) -> None:super().__init__()self.c = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, groups=groups, bias=False)@@ -55,20 +54,20 @@ class ConvBN(nn.Sequential):class PatchEmbed(nn.Sequential):- def __init__(self, in_channels: int, embed_dim: int, activation: type[Module] = nn.GELU) -> None:+ def __init__(self, in_channels: int, embed_dim: int, activation: type[nn.Module] = nn.GELU) -> None:super().__init__()self.seq = nn.Sequential(ConvBN(in_channels, embed_dim // 2, 3, 2, 1), activation(), ConvBN(embed_dim // 2, embed_dim, 3, 2, 1))-class MBConv(Module):+class MBConv(nn.Module):def __init__(self,in_channels: int,out_channels: int,expansion_ratio: float,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,drop_path: float = 0.0,) -> None:super().__init__()@@ -79,18 +78,18 @@ class MBConv(Module):self.drop_path = DropPath(drop_path)self.act = activation()- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:return self.act(x + self.drop_path(self.conv3(self.conv2(self.conv1(x)))))-class PatchMerging(Module):+class PatchMerging(nn.Module):def __init__(self,input_resolution: int | tuple[int, int],dim: int,out_dim: int,stride: int,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,) -> None:KORNIA_CHECK(stride in (1, 2), "stride must be either 1 or 2")super().__init__()@@ -99,7 +98,7 @@ class PatchMerging(Module):self.conv2 = ConvBN(out_dim, out_dim, 3, stride, 1, groups=out_dim, activation=activation)self.conv3 = ConvBN(out_dim, out_dim, 1)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:if x.ndim == 3:x = x.transpose(1, 2).unflatten(2, self.input_resolution) # (B, H * W, C) -> (B, C, H, W)x = self.conv3(self.conv2(self.conv1(x)))@@ -107,14 +106,14 @@ class PatchMerging(Module):return x-class ConvLayer(Module):+class ConvLayer(nn.Module):def __init__(self,dim: int,depth: int,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,drop_path: float | list[float] = 0.0,- downsample: Optional[Module] = None,+ downsample: Optional[nn.Module] = None,use_checkpoint: bool = False,conv_expand_ratio: float = 4.0,) -> None:@@ -131,7 +130,7 @@ class ConvLayer(Module):# patch merging layerself.downsample = downsample- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:for blk in self.blocks:x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x)if self.downsample is not None:@@ -145,7 +144,7 @@ class MLP(nn.Sequential):in_features: int,hidden_features: int,out_features: int,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,drop: float = 0.0,) -> None:super().__init__()@@ -160,7 +159,7 @@ class MLP(nn.Sequential):# NOTE: differences from image_encoder.Attention:# - different relative position encoding mechanism (separable/decomposed vs joint)# - this impl supports attn_ratio (increase output size for value), though it is not used-class Attention(Module):+class Attention(nn.Module):def __init__(self,dim: int,@@ -186,11 +185,11 @@ class Attention(Module):indices, attn_offset_size = self.build_attention_bias(resolution)self.attention_biases = nn.Parameter(torch.zeros(num_heads, attn_offset_size))self.register_buffer("attention_bias_idxs", indices, persistent=False)- self.attention_bias_idxs: Tensor- self.ab: Optional[Tensor] = None+ self.attention_bias_idxs: torch.Tensor+ self.ab: Optional[torch.Tensor] = None@staticmethod- def build_attention_bias(resolution: tuple[int, int]) -> tuple[Tensor, int]:+ def build_attention_bias(resolution: tuple[int, int]) -> tuple[torch.Tensor, int]:H, W = resolutionrows = torch.arange(H)cols = torch.arange(W)@@ -211,7 +210,7 @@ class Attention(Module):self.ab = None if (mode and self.ab is not None) else self.attention_biases[:, self.attention_bias_idxs]return self- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:B, N, _ = x.shapex = self.norm(x)qkv = self.qkv(x)@@ -227,7 +226,7 @@ class Attention(Module):return x-class TinyViTBlock(Module):+class TinyViTBlock(nn.Module):def __init__(self,dim: int,@@ -238,7 +237,7 @@ class TinyViTBlock(Module):drop: float = 0.0,drop_path: float = 0.0,local_conv_size: int = 3,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,) -> None:KORNIA_CHECK(dim % num_heads == 0, "dim must be divislbe by num_heads")super().__init__()@@ -252,7 +251,7 @@ class TinyViTBlock(Module):self.mlp = MLP(dim, int(dim * mlp_ratio), dim, activation, drop)self.drop_path2 = DropPath(drop_path)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:H, W = self.input_resolutionB, L, C = x.shaperes_x = x@@ -273,7 +272,7 @@ class TinyViTBlock(Module):return x-class BasicLayer(Module):+class BasicLayer(nn.Module):def __init__(self,dim: int,@@ -284,10 +283,10 @@ class BasicLayer(Module):mlp_ratio: float = 4.0,drop: float = 0.0,drop_path: float | list[float] = 0.0,- downsample: Optional[Module] = None,+ downsample: Optional[nn.Module] = None,use_checkpoint: bool = False,local_conv_size: int = 3,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,) -> None:super().__init__()self.use_checkpoint = use_checkpoint@@ -312,7 +311,7 @@ class BasicLayer(Module):# patch merging layerself.downsample = downsample- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:for blk in self.blocks:x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x)if self.downsample is not None:@@ -320,7 +319,7 @@ class BasicLayer(Module):return x-class TinyViT(Module):+class TinyViT(nn.Module):"""TinyViT model, as described in https://arxiv.org/abs/2207.10666.Args:@@ -358,13 +357,13 @@ class TinyViT(Module):mbconv_expand_ratio: float = 4.0,local_conv_size: int = 3,# layer_lr_decay: float = 1.0,- activation: type[Module] = nn.GELU,+ activation: type[nn.Module] = nn.GELU,mobile_sam: bool = False,) -> None:super().__init__()self.img_size = img_sizeself.mobile_sam = mobile_sam- self.neck: Optional[Module]+ self.neck: Optional[nn.Module]if mobile_sam:# MobileSAM adjusts the stride to match the total stride of other ViT backbones# used in the original SAM (stride 16)@@ -431,7 +430,7 @@ class TinyViT(Module):self.norm_head = nn.LayerNorm(embed_dims[-1])self.head = nn.Linear(embed_dims[-1], num_classes)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:"""Classify images if ``mobile_sam=False``, produce feature maps if ``mobile_sam=True``."""x = self.patch_embed(x)x = self.layers(x)diff --git a/kornia/contrib/vit.py b/kornia/models/vit.pysimilarity index 91%rename from kornia/contrib/vit.pyrename to kornia/models/vit.pyindex b4c31ea7a..952fee13b 100644--- a/kornia/contrib/vit.py+++ b/kornia/models/vit.py@@ -31,18 +31,17 @@ from typing import Any, Callableimport torchfrom torch import nn-from kornia.core import Module, Tensor, concatenatefrom kornia.core.check import KORNIA_CHECK__all__ = ["VisionTransformer"]-class ResidualAdd(Module):- def __init__(self, fn: Callable[..., Tensor]) -> None:+class ResidualAdd(nn.Module):+ def __init__(self, fn: Callable[..., torch.Tensor]) -> None:super().__init__()self.fn = fn- def forward(self, x: Tensor, **kwargs: Any) -> Tensor:+ def forward(self, x: torch.Tensor, **kwargs: Any) -> torch.Tensor:res = xx = self.fn(x, **kwargs)x += res@@ -60,7 +59,7 @@ class FeedForward(nn.Sequential):)-class MultiHeadAttention(Module):+class MultiHeadAttention(nn.Module):def __init__(self, emb_size: int, num_heads: int, att_drop: float, proj_drop: float) -> None:super().__init__()self.emb_size = emb_size@@ -81,7 +80,7 @@ class MultiHeadAttention(Module):self.projection = nn.Linear(emb_size, emb_size)self.projection_drop = nn.Dropout(proj_drop) # added timm trick- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:B, N, C = x.shape# split keys, queries and values in num_heads# NOTE: the line below differs from timm@@ -122,7 +121,7 @@ class TransformerEncoderBlock(nn.Sequential):)-class TransformerEncoder(Module):+class TransformerEncoder(nn.Module):def __init__(self,embed_dim: int = 768,@@ -135,9 +134,9 @@ class TransformerEncoder(Module):self.blocks = nn.Sequential(*(TransformerEncoderBlock(embed_dim, num_heads, dropout_rate, dropout_attn) for _ in range(depth)))- self.results: list[Tensor] = []+ self.results: list[torch.Tensor] = []- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:self.results = []out = xfor m in self.blocks.children():@@ -146,7 +145,7 @@ class TransformerEncoder(Module):return out-class PatchEmbedding(Module):+class PatchEmbedding(nn.Module):"""Compute the 2d image patch embedding ready to pass to transformer encoder."""def __init__(@@ -155,7 +154,7 @@ class PatchEmbedding(Module):out_channels: int = 768,patch_size: int = 16,image_size: int = 224,- backbone: Module | None = None,+ backbone: nn.Module | None = None,) -> None:super().__init__()self.in_channels = in_channels@@ -177,19 +176,19 @@ class PatchEmbedding(Module):out = self.backbone(torch.zeros(1, *image_size)).detach()return out.shape[-3], out.shape[-2] * out.shape[-1]- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:x = self.backbone(x)B, N, _, _ = x.shapex = x.view(B, N, -1).permute(0, 2, 1) # BxNxEcls_tokens = self.cls_token.repeat(B, 1, 1) # Bx1xE# prepend the cls token to the input- x = concatenate([cls_tokens, x], dim=1) # Bx(N+1)xE+ x = torch.cat([cls_tokens, x], dim=1) # Bx(N+1)xE# add position embeddingx += self.positionsreturn x-class VisionTransformer(Module):+class VisionTransformer(nn.Module):"""Vision transformer (ViT) module.The module is expected to be used as operator for different vision tasks.@@ -228,7 +227,7 @@ class VisionTransformer(Module):num_heads: int = 12,dropout_rate: float = 0.0,dropout_attn: float = 0.0,- backbone: Module | None = None,+ backbone: nn.Module | None = None,) -> None:super().__init__()self.image_size = image_size@@ -242,12 +241,12 @@ class VisionTransformer(Module):self.norm = nn.LayerNorm(hidden_dim, 1e-6)@property- def encoder_results(self) -> list[Tensor]:+ def encoder_results(self) -> list[torch.Tensor]:return self.encoder.results- def forward(self, x: Tensor) -> Tensor:- if not isinstance(x, Tensor):- raise TypeError(f"Input x type is not a Tensor. Got: {type(x)}")+ def forward(self, x: torch.Tensor) -> torch.Tensor:+ if not isinstance(x, torch.Tensor):+ raise TypeError(f"Input x type is not a torch.Tensor. Got: {type(x)}")if self.image_size not in (*x.shape[-2:],) and x.shape[-3] != self.in_channels:raise ValueError(@@ -274,13 +273,13 @@ class VisionTransformer(Module):Args:variant: ViT model variant e.g. ``vit_b/16``.pretrained: whether to load pre-trained AugReg weights.- kwargs: other keyword arguments that will be passed to :func:`kornia.contrib.vit.VisionTransformer`.+ kwargs: other keyword arguments that will be passed to :func:`kornia.models.vit.VisionTransformer`.Returns:The respective ViT modelExample:- >>> from kornia.contrib import VisionTransformer+ >>> from kornia.models.vit import VisionTransformer>>> vit_model = VisionTransformer.from_config("vit_b/16", pretrained=True)"""diff --git a/kornia/contrib/vit_mobile.py b/kornia/models/vit_mobile.pysimilarity index 92%rename from kornia/contrib/vit_mobile.pyrename to kornia/models/vit_mobile.pyindex fa8ee3a17..97b316853 100644--- a/kornia/contrib/vit_mobile.py+++ b/kornia/models/vit_mobile.py@@ -20,41 +20,39 @@ from typing import Any, Dict, Tupleimport torchfrom torch import nn-from kornia.core import Module, Tensor--def conv_1x1_bn(inp: int, oup: int) -> Module:+def conv_1x1_bn(inp: int, oup: int) -> nn.Module:"""Apply 1x1 Convolution with Batch Norm."""return nn.Sequential(nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), nn.SiLU())-def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> Module:+def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> nn.Module:"""Apply NxN Convolution with Batch Norm."""return nn.Sequential(nn.Conv2d(inp, oup, kernal_size, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.SiLU())-class PreNorm(Module):- def __init__(self, dim: int, fn: Module) -> None:+class PreNorm(nn.Module):+ def __init__(self, dim: int, fn: nn.Module) -> None:super().__init__()self.norm = nn.LayerNorm(dim)self.fn = fn- def forward(self, x: Tensor, **kwargs: Dict[str, Any]) -> Tensor:+ def forward(self, x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:return self.fn(self.norm(x), **kwargs)-class FeedForward(Module):+class FeedForward(nn.Module):def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0) -> None:super().__init__()self.net = nn.Sequential(nn.Linear(dim, hidden_dim), nn.SiLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout))- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:return self.net(x)-class Attention(Module):+class Attention(nn.Module):def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0) -> None:super().__init__()inner_dim = dim_head * heads@@ -68,7 +66,7 @@ class Attention(Module):self.to_out = nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout)) if project_out else nn.Identity()- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:qkv = self.to_qkv(x).chunk(3, dim=-1)b, p, n, hd = qkv[0].shape@@ -81,7 +79,7 @@ class Attention(Module):return self.to_out(out)-class Transformer(Module):+class Transformer(nn.Module):"""Transformer block described in ViT.Paper: https://arxiv.org/abs/2010.11929@@ -110,14 +108,14 @@ class Transformer(Module):))- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:for attn, ff in self.layers:x = attn(x) + xx = ff(x) + xreturn x-class MV2Block(Module):+class MV2Block(nn.Module):"""MV2 block described in MobileNetV2.Paper: https://arxiv.org/pdf/1801.04381@@ -163,14 +161,14 @@ class MV2Block(Module):nn.BatchNorm2d(oup),)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:if self.use_res_connect:return x + self.conv(x)else:return self.conv(x)-class MobileViTBlock(Module):+class MobileViTBlock(nn.Module):"""MobileViT block mentioned in MobileViT.Args:@@ -205,7 +203,7 @@ class MobileViTBlock(Module):self.conv3 = conv_1x1_bn(dim, channel)self.conv4 = conv_nxn_bn(2 * channel, channel, kernel_size)- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:y = x.clone()# Local representations@@ -235,7 +233,7 @@ class MobileViTBlock(Module):return x-class MobileViT(Module):+class MobileViT(nn.Module):"""Module MobileViT. Default arguments is for MobileViT XXS.Paper: https://arxiv.org/abs/2110.02178@@ -299,7 +297,7 @@ class MobileViT(Module):self.conv2 = conv_1x1_bn(channels[-2], channels[-1])- def forward(self, x: Tensor) -> Tensor:+ def forward(self, x: torch.Tensor) -> torch.Tensor:x = self.conv1(x)x = self.mv2[0](x)diff --git a/kornia/models/tracking/__init__.py b/kornia/models/yunet/__init__.pysimilarity index 79%rename from kornia/models/tracking/__init__.pyrename to kornia/models/yunet/__init__.pyindex 413a0339c..12e937437 100644--- a/kornia/models/tracking/__init__.py+++ b/kornia/models/yunet/__init__.py@@ -15,9 +15,6 @@# limitations under the License.#-"""Tracking models submodule for Kornia.+from .model import YuNet-This package provides model architectures and utilities for object tracking tasks.-"""--from .boxmot_tracker import *+__all__ = ["YuNet"]diff --git a/kornia/models/yunet/model.py b/kornia/models/yunet/model.pynew file mode 100644index 000000000..a05935668--- /dev/null+++ b/kornia/models/yunet/model.py@@ -0,0 +1,150 @@+# 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.+#++# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa+from typing import Dict++import torch+import torch.nn.functional as F+from torch import nn++__all__ = ["YuNet"]++url: str = "https://github.com/kornia/data/raw/main/yunet_final.pth"+++class ConvDPUnit(nn.Sequential):+ def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None:+ super().__init__()+ self.add_module("conv1", nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=True, groups=1))+ self.add_module("conv2", nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=True, groups=out_channels))+ if withBNRelu:+ self.add_module("bn", nn.BatchNorm2d(out_channels))+ self.add_module("relu", nn.ReLU(inplace=True))+++class Conv_head(nn.Sequential):+ def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:+ super().__init__()+ self.add_module("conv1", nn.Conv2d(in_channels, mid_channels, 3, 2, 1, bias=True, groups=1))+ self.add_module("bn1", nn.BatchNorm2d(mid_channels))+ self.add_module("relu", nn.ReLU(inplace=True))+ self.add_module("conv2", ConvDPUnit(mid_channels, out_channels))+++class Conv4layerBlock(nn.Sequential):+ def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None:+ super().__init__()+ self.add_module("conv1", ConvDPUnit(in_channels, in_channels, True))+ self.add_module("conv2", ConvDPUnit(in_channels, out_channels, withBNRelu))+++class YuNet(nn.Module):+ r"""YuNet face detection model.++ This is the underlying CNN model used by :py:class:`kornia.contrib.FaceDetector` for face detection.+ The model architecture is based on the method described in :cite:`facedetect-yu`.++ Args:+ phase: the phase of the model, either "train" or "test".+ pretrained: if True, loads pretrained weights from the official repository.++ Example:+ >>> model = YuNet("test", pretrained=True)+ >>> img = torch.rand(1, 3, 320, 320)+ >>> out = model(img)++ """++ def __init__(self, phase: str, pretrained: bool) -> None:+ super().__init__()+ self.phase = phase+ self.num_classes = 2++ self.model0 = Conv_head(3, 16, 16)+ self.model1 = Conv4layerBlock(16, 64)+ self.model2 = Conv4layerBlock(64, 64)+ self.model3 = Conv4layerBlock(64, 64)+ self.model4 = Conv4layerBlock(64, 64)+ self.model5 = Conv4layerBlock(64, 64)+ self.model6 = Conv4layerBlock(64, 64)++ self.head = nn.Sequential(+ Conv4layerBlock(64, 3 * (14 + 2 + 1), False),+ Conv4layerBlock(64, 2 * (14 + 2 + 1), False),+ Conv4layerBlock(64, 2 * (14 + 2 + 1), False),+ Conv4layerBlock(64, 3 * (14 + 2 + 1), False),+ )++ if self.phase == "train":+ for m in self.modules():+ if isinstance(m, nn.Conv2d):+ if m.bias is not None:+ nn.init.xavier_normal_(m.weight.data)+ m.bias.data.fill_(0.02)+ else:+ m.weight.data.normal_(0, 0.01)+ elif isinstance(m, nn.BatchNorm2d):+ m.weight.data.fill_(1)+ m.bias.data.zero_()++ # use torch.hub to load pretrained model+ if pretrained:+ pretrained_dict = torch.hub.load_state_dict_from_url(url, map_location=torch.device("cpu"))+ self.load_state_dict(pretrained_dict, strict=True)+ self.eval()++ def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:+ detection_sources, head_list = [], []++ x = self.model0(x)+ x = F.max_pool2d(x, 2)+ x = self.model1(x)+ x = self.model2(x)+ x = F.max_pool2d(x, 2)+ x = self.model3(x)+ detection_sources.append(x)++ x = F.max_pool2d(x, 2)+ x = self.model4(x)+ detection_sources.append(x)++ x = F.max_pool2d(x, 2)+ x = self.model5(x)+ detection_sources.append(x)++ x = F.max_pool2d(x, 2)+ x = self.model6(x)+ detection_sources.append(x)++ for i, h in enumerate(self.head):+ x_tmp = h(detection_sources[i])+ head_list.append(x_tmp.permute(0, 2, 3, 1).contiguous())++ head_data = torch.cat([o.view(o.size(0), -1) for o in head_list], 1)+ head_data = head_data.view(head_data.size(0), -1, 17)++ loc_data, conf_data, iou_data = head_data.split((14, 2, 1), dim=-1)++ if self.phase == "test":+ conf_data = torch.softmax(conf_data, dim=-1)+ else:+ loc_data = loc_data.view(loc_data.size(0), -1, 14)+ conf_data = conf_data.view(conf_data.size(0), -1, self.num_classes)+ iou_data = iou_data.view(iou_data.size(0), -1, 1)++ return {"loc": loc_data, "conf": conf_data, "iou": iou_data}diff --git a/kornia/models/yunet/processors.py b/kornia/models/yunet/processors.pynew file mode 100644index 000000000..f5ad1157f--- /dev/null+++ b/kornia/models/yunet/processors.py@@ -0,0 +1,103 @@+# 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.+#++# Adapted from https://github.com/Hakuyume/chainer-ssd+import math+from typing import List, Tuple++import torch++__all__ = ["PriorBox", "decode"]+++def decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor:+ """Decode locations from predictions using priors to undo the encoding for offset regression at train time.++ Args:+ loc: location predictions for loc layers. Shape: [num_priors,4].+ priors: Prior boxes in center-offset form. Shape: [num_priors,4].+ variances: (list[float]) Variances of priorboxes.++ Return:+ torch.Tensor containing decoded bounding box predictions.++ """+ boxes = torch.cat(+ (+ priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4],+ priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]),+ priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4],+ priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4],+ priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4],+ priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4],+ priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4],+ ),+ 1,+ )+ # prepare final output+ tmp = boxes[:, 0:2] - boxes[:, 2:4] / 2+ return torch.cat((tmp, boxes[:, 2:4] + tmp, boxes[:, 4:]), dim=-1)+++class PriorBox:+ """Generate prior boxes for YuNet face detection model."""++ def __init__(self, min_sizes: List[List[int]], steps: List[int], clip: bool, image_size: Tuple[int, int]) -> None:+ self.min_sizes = min_sizes+ self.steps = steps+ self.clip = clip+ self.image_size = image_size++ self.device: torch.device = torch.device("cpu")+ self.dtype: torch.dtype = torch.float32++ for i in range(4):+ if self.steps[i] != math.pow(2, (i + 3)):+ raise ValueError("steps must be [8,16,32,64]")++ self.feature_map_2th = [int(int((self.image_size[0] + 1) / 2) / 2), int(int((self.image_size[1] + 1) / 2) / 2)]+ self.feature_map_3th = [int(self.feature_map_2th[0] / 2), int(self.feature_map_2th[1] / 2)]+ self.feature_map_4th = [int(self.feature_map_3th[0] / 2), int(self.feature_map_3th[1] / 2)]+ self.feature_map_5th = [int(self.feature_map_4th[0] / 2), int(self.feature_map_4th[1] / 2)]+ self.feature_map_6th = [int(self.feature_map_5th[0] / 2), int(self.feature_map_5th[1] / 2)]++ self.feature_maps = [self.feature_map_3th, self.feature_map_4th, self.feature_map_5th, self.feature_map_6th]++ def to(self, device: torch.device, dtype: torch.dtype) -> "PriorBox":+ self.device = device+ self.dtype = dtype+ return self++ def __call__(self) -> torch.Tensor:+ anchors: List[float] = []+ for k, f in enumerate(self.feature_maps):+ min_sizes: List[int] = self.min_sizes[k]+ # NOTE: the nested loop it's to make torchscript happy+ for i in range(f[0]):+ for j in range(f[1]):+ for min_size in min_sizes:+ s_kx = min_size / self.image_size[1]+ s_ky = min_size / self.image_size[0]++ cx = (j + 0.5) * self.steps[k] / self.image_size[1]+ cy = (i + 0.5) * self.steps[k] / self.image_size[0]+ anchors += [cx, cy, s_kx, s_ky]+ # back to torch land+ output = torch.tensor(anchors, device=self.device, dtype=self.dtype).view(-1, 4)+ if self.clip:+ output = output.clamp(max=1, min=0)+ return outputdiff --git a/pixi.toml b/pixi.tomlindex 5ba6cf3ea..b410780c4 100644--- a/pixi.toml+++ b/pixi.toml@@ -42,6 +42,7 @@ test-f32 = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DTYPE = "floattest-f64 = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DTYPE = "float64" } }test-slow = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_RUNSLOW = "true" } }test-quick = { cmd = "uv run pytest -v -m 'not (jit or grad or nn)' tests/" }+test-module = { cmd = "uv run pytest -v", description = "Run tests for a specific module (usage: pixi run test-module tests/<module_path>, e.g., pixi run test-module tests/contrib/)" }# Qualitylint = { cmd = "uv run pre-commit run ruff --all-files" }typecheck = { cmd = "uvx ty check" }diff --git a/tests/contrib/test_classification_head.py b/tests/contrib/test_classification_head.pydeleted file mode 100644index 5be07a653..000000000--- a/tests/contrib/test_classification_head.py+++ /dev/null@@ -1,32 +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 pytest-import torch--import kornia--from testing.base import BaseTester---class TestClassificationHead(BaseTester):- @pytest.mark.parametrize("B, D, N", [(1, 8, 10), (2, 2, 5)])- def test_smoke(self, device, dtype, B, D, N):- feat = torch.rand(B, D, D, device=device, dtype=dtype)- head = kornia.contrib.ClassificationHead(embed_size=D, num_classes=N).to(device, dtype)- logits = head(feat)- assert logits.shape == (B, N)diff --git a/tests/contrib/test_edge_detector.py b/tests/contrib/test_edge_detector.pyindex b8721a49c..539d1dec7 100644--- a/tests/contrib/test_edge_detector.py+++ b/tests/contrib/test_edge_detector.py@@ -27,13 +27,18 @@ class TestEdgeDetector(BaseTester):@pytest.mark.slowdef test_smoke(self, device, dtype):img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)- net = kornia.contrib.EdgeDetector().to(device, dtype)+ net = kornia.contrib.EdgeDetectorBuilder.build(pretrained=False).to(device, dtype)out = net(img)- assert out.shape == (2, 1, 64, 64)+ # ResizePostProcessor returns a list, so we need to handle that+ if isinstance(out, list):+ assert len(out) == 2+ assert all(item.shape == (1, 1, 64, 64) for item in out)+ else:+ assert out.shape == (2, 1, 64, 64)@pytest.mark.slow@pytest.mark.skip(reason="issue with `ClassVar[list[int]]`")def test_jit(self, device, dtype):- op = kornia.contrib.EdgeDetector().to(device, dtype)+ op = kornia.contrib.EdgeDetectorBuilder.build(pretrained=False).to(device, dtype)op_jit = torch.jit.script(op)assert op_jit is not Nonediff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex 65a838f33..f22e603ef 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -18,7 +18,7 @@import pytestimport torch-from kornia.filters import DexiNed, filter2d, filter2d_separable, filter3d+from kornia.filters import filter2d, filter2d_separable, filter3dfrom kornia.utils._compat import torch_version_lefrom testing.base import BaseTester@@ -740,45 +740,3 @@ class TestFilter3D(BaseTester):actual = op_optimized(data, kernel, normalized=normalized)self.assert_close(actual, expected)---class TestDexiNed(BaseTester):- def test_smoke(self, device, dtype):- img = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)- net = DexiNed(pretrained=False).to(device, dtype)- feat = net.get_features(img)- assert len(feat) == 6- out = net(img)- assert out.shape == (2, 1, 32, 32)-- @pytest.mark.slow- @pytest.mark.parametrize("data", ["dexined"], indirect=True)- def test_inference(self, device, dtype, data):- model = DexiNed(pretrained=False)- model.load_state_dict(data, strict=True)- model = model.to(device, dtype)- model.eval()-- img = torch.tensor([[[[0.0, 255.0, 0.0], [0.0, 255.0, 0.0], [0.0, 255.0, 0.0]]]], device=device, dtype=dtype)- img = img.repeat(1, 3, 1, 1)-- expect = torch.tensor(- [[[[-0.3709, 0.0519, -0.2839], [0.0627, 0.6587, -0.1276], [-0.1840, -0.3917, -0.8240]]]],- device=device,- dtype=dtype,- )-- out = model(img)- self.assert_close(out, expect, atol=3e-4, rtol=3e-4)-- @pytest.mark.skip(reason="DexiNed do not compile with dynamo.")- def test_dynamo(self, device, dtype, torch_optimizer):- # TODO: update the dexined to be possible to use with dynamo- data = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)- op = DexiNed(pretrained=True).to(device, dtype)- op_optimized = torch_optimizer(op)-- expected = op(data)- actual = op_optimized(data)-- self.assert_close(actual, expected)diff --git a/tests/contrib/models/__init__.py b/tests/models/__init__.pysimilarity index 100%rename from tests/contrib/models/__init__.pyrename to tests/models/__init__.pydiff --git a/tests/models/box_filtering.py b/tests/models/test_box_filtering.pysimilarity index 98%rename from tests/models/box_filtering.pyrename to tests/models/test_box_filtering.pyindex 84e034022..55018f6e0 100644--- a/tests/models/box_filtering.py+++ b/tests/models/test_box_filtering.py@@ -19,8 +19,8 @@ import pytestimport torchfrom numpy.testing import assert_almost_equal+from kornia.contrib.object_detection import BoxFilteringfrom kornia.core import tensor-from kornia.models.detection.utils import BoxFiltering # Replace with the actual module pathclass TestBoxFiltering:diff --git a/tests/models/test_dexined.py b/tests/models/test_dexined.pynew file mode 100644index 000000000..6d363c588--- /dev/null+++ b/tests/models/test_dexined.py@@ -0,0 +1,65 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++from kornia.models.dexined import DexiNed++from testing.base import BaseTester+++class TestDexiNed(BaseTester):+ def test_smoke(self, device, dtype):+ img = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)+ net = DexiNed(pretrained=False).to(device, dtype)+ feat = net.get_features(img)+ assert len(feat) == 6+ out = net(img)+ assert out.shape == (2, 1, 32, 32)++ @pytest.mark.slow+ @pytest.mark.parametrize("data", ["dexined"], indirect=True)+ def test_inference(self, device, dtype, data):+ model = DexiNed(pretrained=False)+ model.load_state_dict(data, strict=True)+ model = model.to(device, dtype)+ model.eval()++ img = torch.tensor([[[[0.0, 255.0, 0.0], [0.0, 255.0, 0.0], [0.0, 255.0, 0.0]]]], device=device, dtype=dtype)+ img = img.repeat(1, 3, 1, 1)++ expect = torch.tensor(+ [[[[-0.3709, 0.0519, -0.2839], [0.0627, 0.6587, -0.1276], [-0.1840, -0.3917, -0.8240]]]],+ device=device,+ dtype=dtype,+ )++ out = model(img)+ self.assert_close(out, expect, atol=1e-3, rtol=1e-2)++ @pytest.mark.skip(reason="DexiNed do not compile with dynamo.")+ def test_dynamo(self, device, dtype, torch_optimizer):+ # TODO: update the dexined to be possible to use with dynamo+ data = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)+ op = DexiNed(pretrained=True).to(device, dtype)+ op_optimized = torch_optimizer(op)++ expected = op(data)+ actual = op_optimized(data)++ self.assert_close(actual, expected)diff --git a/tests/contrib/models/test_efficient_vit.py b/tests/models/test_efficient_vit.pysimilarity index 95%rename from tests/contrib/models/test_efficient_vit.pyrename to tests/models/test_efficient_vit.pyindex 96e859ff3..d156b9edc 100644--- a/tests/contrib/models/test_efficient_vit.py+++ b/tests/models/test_efficient_vit.py@@ -19,8 +19,8 @@import pytestimport torch-from kornia.contrib.models.efficient_vit import EfficientViT, EfficientViTConfig-from kornia.contrib.models.efficient_vit import backbone as vit+from kornia.models.efficient_vit import EfficientViT, EfficientViTConfig+from kornia.models.efficient_vit import backbone as vitfrom kornia.utils._compat import torch_version_ltdiff --git a/tests/contrib/test_mobile_vit.py b/tests/models/test_mobile_vit.pysimilarity index 91%rename from tests/contrib/test_mobile_vit.pyrename to tests/models/test_mobile_vit.pyindex ad34d0d68..16f91c8f8 100644--- a/tests/contrib/test_mobile_vit.py+++ b/tests/models/test_mobile_vit.py@@ -18,7 +18,7 @@import pytestimport torch-import kornia+from kornia.models.vit_mobile import MobileViTfrom testing.base import BaseTester@@ -33,7 +33,7 @@ class TestMobileViT(BaseTester):channel = {"xxs": 320, "xs": 384, "s": 640}img = torch.rand(B, 3, ih, iw, device=device, dtype=dtype)- mvit = kornia.contrib.MobileViT(mode=mode, patch_size=patch_size).to(device, dtype)+ mvit = MobileViT(mode=mode, patch_size=patch_size).to(device, dtype)out = mvit(img)assert isinstance(out, torch.Tensor)diff --git a/tests/contrib/test_object_detector.py b/tests/models/test_object_detector.pysimilarity index 88%rename from tests/contrib/test_object_detector.pyrename to tests/models/test_object_detector.pyindex f4de34b88..5ea57281b 100644--- a/tests/contrib/test_object_detector.py+++ b/tests/models/test_object_detector.py@@ -21,7 +21,7 @@ import pytestimport torchimport kornia-from kornia.contrib.models.rt_detr import RTDETR, DETRPostProcessor, RTDETRConfig+from kornia.models.rt_detr import RTDETR, DETRPostProcessor, RTDETRConfigfrom kornia.utils._compat import torch_version_ltfrom testing.base import BaseTester@@ -33,9 +33,9 @@ class TestObjectDetector(BaseTester):confidence = 0.3config = RTDETRConfig("resnet50d", 10, head_num_queries=10)model = RTDETR.from_config(config).to(device, dtype).eval()- pre_processor = kornia.models.utils.ResizePreProcessor(32, 32)+ pre_processor = kornia.models.processors.ResizePreProcessor(32, 32)post_processor = DETRPostProcessor(confidence, num_top_queries=3).to(device, dtype).eval()- detector = kornia.models.detection.ObjectDetector(model, pre_processor, post_processor)+ detector = kornia.contrib.object_detection.ObjectDetector(model, pre_processor, post_processor)sizes = torch.randint(5, 10, (batch_size, 2)) * 32imgs = [torch.randn(3, h, w, device=device, dtype=dtype) for h, w in sizes]@@ -56,9 +56,9 @@ class TestObjectDetector(BaseTester):def test_onnx(self, device, dtype, tmp_path: Path, variant: str):config = RTDETRConfig(variant, 1)model = RTDETR.from_config(config).to(device=device, dtype=dtype).eval()- pre_processor = kornia.models.utils.ResizePreProcessor(640, 640)+ pre_processor = kornia.models.processors.ResizePreProcessor(640, 640)post_processor = DETRPostProcessor(0.3, num_top_queries=3)- detector = kornia.models.detection.ObjectDetector(model, pre_processor, post_processor)+ detector = kornia.contrib.object_detection.ObjectDetector(model, pre_processor, post_processor)data = torch.rand(1, 3, 400, 640, device=device, dtype=dtype)diff --git a/tests/contrib/test_prompter.py b/tests/models/test_prompter.pysimilarity index 99%rename from tests/contrib/test_prompter.pyrename to tests/models/test_prompter.pyindex 8a982911c..1a0082923 100644--- a/tests/contrib/test_prompter.py+++ b/tests/models/test_prompter.py@@ -18,8 +18,8 @@import pytestimport torch-from kornia.contrib.models.sam import SamConfigfrom kornia.contrib.visual_prompter import VisualPrompter+from kornia.models.sam import SamConfigfrom kornia.utils._compat import torch_versionfrom testing.base import BaseTesterdiff --git a/tests/contrib/models/test_rt_detr.py b/tests/models/test_rt_detr.pysimilarity index 91%rename from tests/contrib/models/test_rt_detr.pyrename to tests/models/test_rt_detr.pyindex 8dcb6d076..3c5191935 100644--- a/tests/contrib/models/test_rt_detr.py+++ b/tests/models/test_rt_detr.py@@ -20,11 +20,11 @@ from functools import partialimport pytestimport torch-from kornia.contrib.models.rt_detr.architecture.hgnetv2 import PPHGNetV2-from kornia.contrib.models.rt_detr.architecture.hybrid_encoder import HybridEncoder, RepVggBlock-from kornia.contrib.models.rt_detr.architecture.resnet_d import ResNetD-from kornia.contrib.models.rt_detr.architecture.rtdetr_head import RTDETRHead-from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig+from kornia.models.rt_detr.architecture.hgnetv2 import PPHGNetV2+from kornia.models.rt_detr.architecture.hybrid_encoder import HybridEncoder, RepVggBlock+from kornia.models.rt_detr.architecture.resnet_d import ResNetD+from kornia.models.rt_detr.architecture.rtdetr_head import RTDETRHead+from kornia.models.rt_detr.model import RTDETR, RTDETRConfigfrom testing.base import BaseTester, assert_close@@ -85,7 +85,7 @@ def test_regvgg_optimize_for_deployment(device, dtype):expected = module(x)module.optimize_for_deployment()actual = module(x)- assert_close(actual, expected)+ assert_close(actual, expected, atol=1e-3, rtol=1e-2)class TestRTDETR(BaseTester):diff --git a/tests/contrib/models/test_sam.py b/tests/models/test_sam.pysimilarity index 98%rename from tests/contrib/models/test_sam.pyrename to tests/models/test_sam.pyindex f6f57ead1..a40e9693d 100644--- a/tests/contrib/models/test_sam.py+++ b/tests/models/test_sam.py@@ -18,8 +18,8 @@import pytestimport torch-from kornia.contrib.models.sam import Sam, SamConfigfrom kornia.core import pad+from kornia.models.sam import Sam, SamConfigfrom testing.base import BaseTesterdiff --git a/tests/contrib/models/test_tiny_vit.py b/tests/models/test_tiny_vit.pysimilarity index 98%rename from tests/contrib/models/test_tiny_vit.pyrename to tests/models/test_tiny_vit.pyindex 41347311a..5b251621c 100644--- a/tests/contrib/models/test_tiny_vit.py+++ b/tests/models/test_tiny_vit.py@@ -20,8 +20,8 @@ import sysimport pytestimport torch-from kornia.contrib.models.tiny_vit import TinyViTfrom kornia.core import Tensor+from kornia.models.tiny_vit import TinyViTfrom testing.base import BaseTesterdiff --git a/tests/contrib/test_vision_transformer.py b/tests/models/test_vision_transformer.pysimilarity index 85%rename from tests/contrib/test_vision_transformer.pyrename to tests/models/test_vision_transformer.pyindex 65e9739d3..6e87c8b5c 100644--- a/tests/contrib/test_vision_transformer.py+++ b/tests/models/test_vision_transformer.py@@ -18,7 +18,7 @@import pytestimport torch-import kornia+from kornia.models.vit import VisionTransformerfrom testing.base import BaseTester@@ -33,7 +33,7 @@ class TestVisionTransformer(BaseTester):T = image_size**2 // patch_size**2 + 1 # tokens sizeimg = torch.rand(B, 3, image_size, image_size, device=device, dtype=dtype)- vit = kornia.contrib.VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)+ vit = VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)out = vit(img)assert isinstance(out, torch.Tensor)@@ -50,13 +50,13 @@ class TestVisionTransformer(BaseTester):@pytest.mark.parametrize("image_size", [32, 224])def test_exception(self, device, dtype, H, D, image_size):with pytest.raises(ValueError):- kornia.contrib.VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)+ VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)def test_backbone(self, device, dtype):def backbone_mock(x):return torch.ones(1, 128, 14, 14, device=device, dtype=dtype)img = torch.rand(1, 3, 32, 32, device=device, dtype=dtype)- vit = kornia.contrib.VisionTransformer(backbone=backbone_mock, num_heads=8).to(device, dtype)+ vit = VisionTransformer(backbone=backbone_mock, num_heads=8).to(device, dtype)out = vit(img)assert out.shape == (1, 197, 128)