Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] add segment anything base (#2315)

João Gustavo A. Amorim81dfd5346461
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 7e5dcad27..3ac959fd9 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -3,6 +3,32 @@ kornia.contrib
.. currentmodule:: kornia.contrib
+Models
+------
+
+Base
+^^^^
+.. autoclass:: kornia.contrib.models.base.ModelBase
+ :members:
+ :undoc-members:
+
+Structures
+^^^^^^^^^^
+.. _anchor SegmentationResults:
+.. autoclass:: kornia.contrib.models.SegmentationResults
+ :members:
+ :undoc-members:
+
+.. autoclass:: kornia.contrib.models.Prompts
+ :members:
+ :undoc-members:
+
+ImagePrompter
+-------------
+
+.. autoclass:: kornia.contrib.image_prompter.ImagePrompter
+ :members: set_image, reset_image, compile, predict, preprocess_image, preprocess_prompts
+
Edge Detection
--------------
@@ -22,7 +48,7 @@ Face Detection
:undoc-members:
Interactive Demo
-~~~~~~~~~~~~~~~~
+^^^^^^^^^^^^^^^^
.. raw:: html
<gradio-app space="kornia/Face-Detection"></gradio-app>
@@ -32,9 +58,25 @@ Visit the `Kornia face detection demo on the Hugging Face Spaces
Image Segmentation
------------------
-
.. autofunction:: connected_components
+
+Segment Anything (SAM)
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. autoclass:: kornia.contrib.models.sam.SamModelType
+ :members:
+ :undoc-members:
+
+.. autoclass:: kornia.contrib.models.sam.SamConfig
+ :members:
+ :undoc-members:
+
+.. autoclass:: kornia.contrib.models.sam.Sam
+ :members: from_config, forward, load_checkpoint
+ :undoc-members:
+ :special-members: __init__,
+
Image Patches
-------------
diff --git a/docs/source/index.rst b/docs/source/index.rst
index d4982f1eb..6fa52a4e1 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -60,8 +60,8 @@ Join the community
applications/image_matching
applications/image_stitching
applications/image_registration
- applications/semantic_segmentation
applications/image_denoising
+ applications/semantic_segmentation
.. toctree::
:caption: KORNIA MODELS
@@ -76,6 +76,7 @@ Join the community
models/affnet
models/sold2
models/dexined
+ models/segment_anything
.. toctree::
diff --git a/docs/source/models/segment_anything.rst b/docs/source/models/segment_anything.rst
new file mode 100644
index 000000000..bcfb631f4
--- /dev/null
+++ b/docs/source/models/segment_anything.rst
@@ -0,0 +1,309 @@
+Segment Anything (SAM)
+======================
+
+The Segment Anything Model (SAM) produces high quality object masks from input prompts such as points or boxes, and it
+can be used to generate masks for all objects in an image.
+
+.. card::
+ :link: https://segment-anything.com/
+
+ **Segment Anything**
+ ^^^
+ **Abstract:** We introduce the Segment Anything (SA) project: a new task, model, and dataset for image
+ segmentation. Using our efficient model in a data collection loop, we built the largest segmentation
+ dataset to date (by far), with over 1 billion masks on 11M licensed and privacy respecting images. The
+ model is designed and trained to be promptable, so it can transfer zero-shot to new image distributions
+ and tasks. We evaluate its capabilities on numerous tasks and find that its zero-shot performance is impressive
+ -- often competitive with or even superior to prior fully supervised results. We are releasing the Segment Anything
+ Model (SAM) and corresponding dataset (SA-1B) of 1B masks and 11M images at https://segment-anything.com to foster
+ research into foundation models for computer vision.
+
+ **Tasks:** Segmentation
+
+ **Datasets:** SA-1B
+
+ **Licence:** Apache
+
+ +++
+ **Authors:** Alexander Kirillov and Eric Mintun and Nikhila Ravi and Hanzi Mao and Chloe Rolland and Laura
+ Gustafson and Alex Berg and Wan-Yen Lo and Piotr Dollar and Ross Girshick
+
+
+
+How to use SAM from Kornia
+--------------------------
+The Kornia API for SAM try to provide a simple API to access initialize the model and load/download the weights. Also,
+providing it to a high-level API called :code:`ImagePrompter`, which allow the users to set an image and run multiple
+queries multiple times.
+
+The :code:`ImagePrompter` works querying on a single image, if you want to explore and query into a batch of images,
+you can use the :code:`Sam` directly. But, for it you will need to write the boilerplate to preprocess and postprocess to
+use it. This boilerplate, is already handle on the high-level API :code:`ImagePrompter`.
+
+Image Prompter
+^^^^^^^^^^^^^^
+.. _anchor Prompter:
+
+The High level API :code:`ImagePrompter` handle with the image and prompt transformation, preprocessing and prediction for
+a given SAM model.
+
+About the :code:`ImagePrompter`:
+
+#. From a `ModelConfig` loads the desired model with the desired checkpoint to be used as the model to receive the query
+ prompts. For know we just support Segment Anything model, where the *SAM-h* is the default option.
+
+#. Based on the model, the :code:`ImagePrompter` will handle with the necessary transformations to be done into the image
+ and prompts before apply it to the model. These transformations are done using PyTorch backed, by our API of
+ augmentations. Where we use the :class:`kornia.geometry.augmentation.AugmentationSequential` to handle with the different
+ data formats (keypoints, boxes, masks, image).
+
+#. When you use :code:`prompter.set_image(...)`, the prompter will preprocess this image, and then pass it to the encoder,
+ and cache the embeddings to query it after.
+
+ * The preprocess steps are: 1) Resize the image to have its longer side the same size as :code:`image_encoder` image size
+ input. 2) Cache the information of this transformation to apply into the prompts. 3) normalize the image based on the
+ passed mean and standard deviation, or with the values of the SAM dataset. 4) pad on the bottom and right for the image
+ have the encoder expected resolution: :math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`.
+
+ * The best image to be used will always have the shape equals to
+ :math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`.
+
+#. When you use :code:`prompter.predict(...)`, the prompter will apply the cached transformations on the coordinates of the
+ prompts, and then query this prompts into the cached embeddings.
+
+ * If :code:`output_original_size=True`, the results structure will upsample the logits from it's resolution into the
+ image input original resolution. The output logits has the height and width equals to 256.
+
+#. You can benefit from using the :code:`torch.compile(...)` API (dynamo) for torch >= 2.0.0 version. To compile with dynamo
+ we provide the method :code:`prompter.compile(...)` which will optimize the right parts of the backend model and the
+ prompter itself.
+
+--------------
+
+Example of using the :code:`ImagePrompter`:
+
+Exploring how to simple initialize the :code:`ImagePrompter`, automatically load the weights from a URL,
+read the image and set it to be query, how to write the prompts, and the multiple ways we can use these prompts
+to query the image masks from the SAM model.
+
+
+.. code-block:: python
+
+ import torch
+
+ from kornia.contrib.models.sam import SamConfig
+ from kornia.contrib.image_prompter import ImagePrompter
+ from kornia.io import load_image, ImageLoadType
+ from kornia.geometry.keypoints import Keypoints
+ from kornia.geometry.boxes import Boxes
+ from kornia.utils import get_cuda_device_if_available
+
+ model_type = 'vit_h'
+ checkpoint = './https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth'
+ device = get_cuda_device_if_available()
+
+ # Load image
+ image = load_image('./example.jpg', ImageLoadType.RGB32, device)
+
+ # Define the model config
+ config = SamConfig(model_type, checkpoint)
+
+ # Load the prompter
+ prompter = ImagePrompter(config, device=device)
+
+ # You can use torch dynamo/compile API with:
+ # prompter.compile()
+
+ # set the image: This will preprocess the image and already generate the embeddings of it
+ prompter.set_image(image)
+
+ # Generate the prompts
+ keypoints = Keypoints(torch.tensor([[[500, 375]]], device=device, dtype=torch.float32)) # BxNx2
+ # For the keypoints label: 1 indicates a foreground point; 0 indicates a background point
+ keypoints_labels = torch.tensor([[1]], device=device) # BxN
+ boxes = Boxes(
+ torch.tensor([[[[425, 600], [425, 875], [700, 600], [700, 875]]]], device=device, dtype=torch.float32), mode='xyxy'
+ )
+
+ # Runs the prediction with all prompts
+ prediction = prompter.predict(
+ point_coords=keypoints,
+ point_labels=keypoints_labels,
+ boxes=boxes,
+ multimask_output=True,
+ )
+
+ #----------------------------------------------
+ # or run the prediction with just the keypoints
+ prediction = prompter.predict(
+ point_coords=keypoints,
+ point_labels=keypoints_labels,
+ multimask_output=True,
+ )
+
+ #----------------------------------------------
+ # or run the prediction with just the box
+ prediction = prompter.predict(
+ boxes=boxes,
+ multimask_output=True,
+ )
+
+ #----------------------------------------------
+ # or run the prediction without prompts
+ prediction = prompter.predict(
+ multimask_output=True,
+ )
+
+ #------------------------------------------------
+ # or run the prediction using the previous logits
+ prediction = prompter.predict(
+ masks=prediction.logits
+ multimask_output=True,
+ )
+
+ # The `prediction` is a SegmentationResults dataclass with the masks, scores and logits
+ print(prediction.masks.shape)
+ print(prediction.scores)
+ print(prediction.logits.shape)
+
+
+Read more about the :code:`SegmentationResults` on :ref:`the official docs<anchor SegmentationResults>`
+
+
+
+Load from config
+^^^^^^^^^^^^^^^^
+You can build a SAM model by specifying the encoder parameters on the the :code:`SamConfig`, or from the model type. The
+:code:`from_config` method will first try to build the model based on the model type, otherwise will try from the specified
+parameters. If a checkpoint URL or path for a file is seted, the method will automatically load it.
+
+.. code-block:: python
+
+ from kornia.contrib.models.sam import Sam, SamConfig
+ from kornia.utils import get_cuda_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`
+ model_type = 'vit_b'
+
+ # The checkpoint can be a filepath or a url
+ checkpoint = './path_for_the_model_checkpoint.pth'
+ device = get_cuda_device_if_available()
+
+ # Load config
+ config = SamConfig(model_type, checkpoint)
+
+ # Load the model with checkpoint
+ sam_model = Sam.from_config(config)
+
+ # Move to desired device
+ sam_model = sam_model.to(device)
+
+
+Load checkpoint
+^^^^^^^^^^^^^^^
+With the load checkpoint method you can load from a file or directly from a URL. The official (by meta) model weights are:
+
+#. `vit_h`: `ViT-H SAM model - https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth <https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth>`_.
+#. `vit_l`: `ViT-L SAM model - https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth <https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth>`_.
+#. `vit_b`: `ViT-B SAM model - https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth <https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth>`_.
+
+If a URL is passed the model will automatically download and cache the weights using
+:code:`torch.hub.load_state_dict_from_url`
+
+.. code-block:: python
+
+ from kornia.contrib.models.sam import Sam, SamConfig
+ from kornia.utils import get_cuda_device_if_available
+
+ model_type = 'vit_b'
+
+ # The checkpoint can be a filepath or a url
+ checkpoint = './path_for_the_model_checkpoint.pth'
+ device = get_cuda_device_if_available()
+
+ # Load/build the model
+ sam_model = Sam.from_config(SamConfig(model_type))
+
+ # Load the checkpoint
+ sam_model.load_checkpoint(checkpoint, device)
+
+
+.. Mask Generator
+.. ^^^^^^^^^^^^^^
+
+
+Example of how to use the SAM model without API
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+This is a simple example, of how to directly use the SAM model loaded. We recommend the use of
+:ref:`Prompter API<anchor Prompter>` to handle/prepare the inputs.
+
+.. code-block:: python
+
+ from kornia.contrib.models.sam import Sam
+ from kornia.contrib.models import SegmentationResults
+ from kornia.io import load_image, ImageLoadType
+ from kornia.utils import get_cuda_device_if_available
+ from kornia.geometry import resize
+ from kornia.enhance import normalize
+
+ model_type = 'vit_b' # or can be a number `2` or the enum sam.SamModelType.vit_b
+ checkpoint_path = './path_for_the_model_checkpoint.pth'
+ device = get_cuda_device_if_available()
+
+ # Load the model
+ sam_model = Sam.from_pretrained(model_type, checkpoint_path, device)
+
+ # Load image
+ image = load_image('./example.jpg', ImageLoadType.RGB32, device)
+
+ # Transform the image (CxHxW) into a batched input (BxCxHxW)
+ image = image[None, ...]
+
+ # Resize the image to have the maximum size 1024 on its largest side
+ inpt = resize(image, 1024, side='long')
+
+ # Embed prompts -- ATTENTION: should match the coordinates after the resize of the image
+ sparse_embeddings, dense_embeddings = sam_model.prompt_encoder(points=None, boxes=None, masks=None)
+
+ # define the info for normalize the input
+ pixel_mean = torch.tensor(...)
+ pixel_std = torch.tensor(...)
+
+ # Preprocess input
+ inpt = normalize(inpt, pixel_mean, pixel_std)
+ padh = model_sam.image_encoder.img_size - h
+ padw = model_sam.image_encoder.img_size - w
+ inpt = pad(inpt, (0, padw, 0, padh))
+
+ #--------------------------------------------------------------------
+ # Option A: Manually calling each API
+ #--------------------------------------------------------------------
+ low_res_logits, iou_predictions = sam_model.mask_decoder(
+ image_embeddings=sam_model.image_encoder(inpt),
+ image_pe=sam_model.prompt_encoder.get_dense_pe(),
+ sparse_prompt_embeddings=sparse_embeddings,
+ dense_prompt_embeddings=dense_embeddings,
+ multimask_output=True,
+ )
+
+ prediction = SegmentationResults(low_res_logits, iou_predictions)
+
+ #--------------------------------------------------------------------
+ # Option B: Calling the model itself
+ #--------------------------------------------------------------------
+ prediction = sam_model(inpt[None, ...], [{}], multimask_output=True)
+
+ #--------------------------------------------------------------------
+ # Post processing
+ #--------------------------------------------------------------------
+ # Upscale the masks to the original image resolution
+ input_size = (inpt.shape[-2], inpt.shape[-1])
+ original_size = (image.shape[-2], image.shape[-1])
+ image_size_encoder = (model_sam.image_encoder.img_size, model_sam.image_encoder.img_size)
+ prediction.original_res_logits(input_size, original_size, image_size_encoder)
+
+ # If wants to check the binary masks
+ masks = prediction.binary_masks
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 3557015d2..8f6cab987 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -153,7 +153,7 @@ class AugmentationSequential(ImageSequential):
def __init__(
self,
*args: Union[_AugmentationBase, ImageSequential],
- data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ data_keys: Union[List[str], List[int], List[DataKey]] = [DataKey.INPUT],
same_on_batch: Optional[bool] = None,
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
@@ -246,7 +246,7 @@ class AugmentationSequential(ImageSequential):
self,
*args: DataType,
params: Optional[List[ParamItem]] = None,
- data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
) -> Union[DataType, List[DataType]]:
"""Reverse the transformation applied.
@@ -341,7 +341,7 @@ class AugmentationSequential(ImageSequential):
self,
*args: DataType,
params: Optional[List[ParamItem]] = None,
- data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
) -> Union[DataType, List[DataType]]:
"""Compute multiple tensors simultaneously according to ``self.data_keys``."""
self.clear_state()
@@ -431,6 +431,8 @@ class AugmentationSequential(ImageSequential):
return VideoKeypoints.from_tensor(arg)
elif self.contains_3d_augmentation:
raise NotImplementedError("3D keypoint handlers are not yet supported.")
+ elif isinstance(arg, (Keypoints,)):
+ return arg
else:
arg = cast(Tensor, arg)
# TODO: Add List[Tensor] in the future.
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index d11062692..912f48750 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -73,7 +73,7 @@ class AugmentationSequentialOps:
def data_keys(self, data_keys: List[DataKey]) -> None:
self._data_keys = [DataKey.get(inp) for inp in data_keys]
- def preproc_datakeys(self, data_keys: Optional[List[Union[str, int, DataKey]]] = None) -> List[DataKey]:
+ def preproc_datakeys(self, data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None) -> List[DataKey]:
if data_keys is None:
return self.data_keys
else:
@@ -97,7 +97,7 @@ class AugmentationSequentialOps:
module: Module,
param: ParamItem,
extra_args: Dict[DataKey, Dict[str, Any]],
- data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
) -> Union[DataType, List[DataType]]:
_data_keys = self.preproc_datakeys(data_keys)
outputs = []
@@ -115,7 +115,7 @@ class AugmentationSequentialOps:
module: Module,
param: ParamItem,
extra_args: Dict[DataKey, Dict[str, Any]],
- data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
) -> Union[DataType, List[DataType]]:
_data_keys = self.preproc_datakeys(data_keys)
outputs = []
diff --git a/kornia/contrib/image_prompter.py b/kornia/contrib/image_prompter.py
new file mode 100644
index 000000000..487287367
--- /dev/null
+++ b/kornia/contrib/image_prompter.py
@@ -0,0 +1,376 @@
+from __future__ import annotations
+
+from typing import Any
+
+import torch
+
+from kornia.augmentation import LongestMaxSize
+from kornia.augmentation.container.augment import AugmentationSequential
+from kornia.contrib.models import Prompts, SegmentationResults
+from kornia.contrib.models.sam import Sam, SamConfig
+from kornia.core import Tensor, pad, tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.enhance import normalize
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
+
+
+class ImagePrompter:
+ """This class allow the user to run multiple query with multiple prompts for a model.
+
+ At the moment, we just support the SAM model. The model is loaded based on the given config.
+
+ For default the images are transformed to have their long side with size of the `image_encoder.img_size`. This
+ Prompter class ensure to transform the images and the prompts before prediction. Also, the image is passed
+ automatically for the method `preprocess_image`, which is responsible for normalize the image and pad it to have
+ the right size for the SAM model :math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`. For
+ default the image is normalized by the mean and standard deviation of the SAM dataset values.
+
+ Args:
+ config: A model config to generate the model. Now just the SAM model is supported.
+ device: The desired device to use the model.
+ dtype: The desired dtype to use the model.
+
+ Example:
+ >>> # prompter = ImagePrompter() # Will load the vit h for default
+ >>> # You can load a custom SAM type for modifying the config
+ >>> prompter = ImagePrompter(SamConfig('vit_b'))
+ >>> image = torch.rand(3, 25, 30)
+ >>> prompter.set_image(image)
+ >>> boxes = Boxes(
+ ... torch.tensor(
+ ... [[[[0, 0], [0, 10], [10, 0], [10, 10]]]],
+ ... device=prompter.device,
+ ... dtype=torch.float32
+ ... ),
+ ... mode='xyxy'
+ ... )
+ >>> prediction = prompter.predict(boxes=boxes)
+ >>> prediction.logits.shape
+ torch.Size([1, 3, 256, 256])
+ """
+
+ def __init__(
+ self,
+ config: SamConfig = SamConfig(
+ model_type='vit_h', checkpoint='https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth'
+ ),
+ device: torch.device | None = None,
+ dtype: torch.dtype | None = None,
+ ) -> None:
+ super().__init__()
+ if isinstance(config, SamConfig):
+ self.model = Sam.from_config(config)
+ transforms = (LongestMaxSize(self.model.image_encoder.img_size, p=1.0),)
+ self.pixel_mean: Tensor | None = tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
+ self.pixel_std: Tensor | None = tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255
+ else:
+ raise NotImplementedError
+
+ self.model = self.model.to(device=device, dtype=dtype)
+ self.transforms = AugmentationSequential(*transforms, same_on_batch=True)
+
+ self.device = device
+ self.dtype = dtype
+ self._original_image_size: None | tuple[int, int] = None
+ self._input_image_size: None | tuple[int, int] = None
+ self._input_encoder_size: None | tuple[int, int] = None
+ self.reset_image()
+
+ def preprocess_image(self, x: Tensor, mean: Tensor | None = None, std: Tensor | None = None) -> Tensor:
+ """Normalize and pad a tensor.
+
+ For normalize the tensor: will priorize the `mean` and `std` passed as argument, if None will use the default
+ Sam Dataset values.
+
+ For pad the tensor: Will pad the tensor into the right and bottom to match with the size of
+ `self.model.image_encoder.img_size`
+
+ Args:
+ x: The image to be preprocessed
+ mean: Mean for each channel.
+ std: Standard deviations for each channel.
+
+ Returns:
+ The image preprocessed (normalized if has mean and str available and padded to encoder size)
+ """
+
+ if isinstance(mean, Tensor) and isinstance(std, Tensor):
+ x = normalize(x, mean, std)
+ elif isinstance(self.pixel_mean, Tensor) and isinstance(self.pixel_std, Tensor):
+ x = normalize(x, self.pixel_mean, self.pixel_std)
+
+ encoder_im_size = self.model.image_encoder.img_size
+ pad_h = encoder_im_size - x.shape[-2]
+ pad_w = encoder_im_size - x.shape[-1]
+ x = pad(x, (0, pad_w, 0, pad_h))
+
+ return x
+
+ @torch.no_grad()
+ def set_image(self, image: Tensor, mean: Tensor | None = None, std: Tensor | None = None) -> None:
+ """Set the embeddings from the given image with `image_decoder` of the model.
+
+ Prepare the given image with the selected transforms and the preprocess method.
+
+ Args:
+ image: RGB image. Normally images with range of [0-1], the model preprocess normalize the
+ pixel values with the mean and std defined in its initialization. Expected to be into a float32
+ dtype. Shape :math:`(3, H, W)`.
+ """
+ KORNIA_CHECK_SHAPE(image, ['3', 'H', 'W'])
+
+ self.reset_image()
+
+ self._original_image_size = (image.shape[-2], image.shape[-1])
+
+ image = self.transforms(image, data_keys=['input'])
+ self._tfs_params = self.transforms._params
+ self._input_image_size = (image.shape[-2], image.shape[-1])
+
+ image = self.preprocess_image(image, mean, std)
+
+ self._input_encoder_size = (image.shape[-2], image.shape[-1])
+
+ self.image_embeddings = self.model.image_encoder(image)
+ self.is_image_set = True
+
+ def _valid_keypoints(self, keypoints: Keypoints | Tensor, labels: Tensor) -> Keypoints:
+ """Validate the keypoints shape and ensure to be a Keypoints."""
+ KORNIA_CHECK_SHAPE(keypoints.data, ['K', 'N', '2'])
+ KORNIA_CHECK_SHAPE(labels.data, ['K', 'N'])
+ KORNIA_CHECK(keypoints.shape[0] == labels.shape[0], 'The keypoints and labels should have the same batch size')
+
+ if isinstance(keypoints, Tensor):
+ keypoints = Keypoints.from_tensor(keypoints)
+
+ return keypoints
+
+ def _valid_boxes(self, boxes: Boxes | Tensor) -> Boxes:
+ """Validate the boxes shape and ensure to be a Boxes into xyxy mode."""
+ if isinstance(boxes, Tensor):
+ KORNIA_CHECK_SHAPE(boxes.data, ['K', '4'])
+ boxes = Boxes(boxes, mode='xyxy')
+
+ if boxes.mode == 'xyxy':
+ boxes_xyxy = boxes
+ else:
+ boxes_xyxy = Boxes(boxes.to_tensor(mode='xyxy'), mode='xyxy')
+
+ return boxes_xyxy
+
+ def _valid_masks(self, masks: Tensor) -> Tensor:
+ """Validate the input masks shape."""
+ KORNIA_CHECK_SHAPE(masks, ['K', '1', '256', '256'])
+ return masks
+
+ def _transform_prompts(
+ self, *prompts: Tensor | Boxes | Keypoints, data_keys: list[str] = []
+ ) -> dict[str, Tensor | Boxes | Keypoints]:
+ transformed_prompts = self.transforms(*prompts, data_keys=data_keys, params=self._tfs_params)
+ return {key: transformed_prompts[idx] for idx, key in enumerate(data_keys)}
+
+ def preprocess_prompts(
+ self,
+ keypoints: Keypoints | Tensor | None = None,
+ keypoints_labels: Tensor | None = None,
+ boxes: Boxes | Tensor | None = None,
+ masks: Tensor | None = None,
+ ) -> Prompts:
+ """Validate and preprocess the given prompts to be aligned with the input image."""
+ data_keys = []
+ to_transform: list[Keypoints | Boxes | Tensor] = []
+
+ if isinstance(keypoints, (Keypoints, Tensor)) and isinstance(keypoints_labels, Tensor):
+ keypoints = self._valid_keypoints(keypoints, keypoints_labels)
+ data_keys.append('keypoints')
+ to_transform.append(keypoints)
+
+ if isinstance(boxes, (Boxes, Tensor)):
+ self._valid_boxes(boxes)
+ data_keys.append('bbox_xyxy')
+ to_transform.append(boxes)
+
+ if isinstance(masks, Tensor):
+ self._valid_masks(masks)
+
+ data = self._transform_prompts(*to_transform, data_keys=data_keys)
+
+ if 'keypoints' in data and isinstance(data['keypoints'], Keypoints):
+ kpts_tensor = data['keypoints'].to_tensor()
+ if KORNIA_CHECK_IS_TENSOR(kpts_tensor) and KORNIA_CHECK_IS_TENSOR(keypoints_labels):
+ points = (kpts_tensor[None, ...], keypoints_labels)
+ else:
+ points = None
+
+ if 'bbox_xyxy' in data and isinstance(data['bbox_xyxy'], Boxes):
+ _bbox = data['bbox_xyxy'].to_tensor(mode='xyxy')
+ if KORNIA_CHECK_IS_TENSOR(_bbox):
+ bbox = _bbox
+ else:
+ bbox = None
+
+ return Prompts(points=points, boxes=bbox, masks=masks)
+
+ @torch.no_grad()
+ def predict(
+ self,
+ keypoints: Keypoints | Tensor | None = None,
+ keypoints_labels: Tensor | None = None,
+ boxes: Boxes | Tensor | None = None,
+ masks: Tensor | None = None,
+ multimask_output: bool = True,
+ output_original_size: bool = True,
+ ) -> SegmentationResults:
+ """Predict masks for the given image based on the input prompts.
+
+ Args:
+ keypoints: Point prompts to the model. Each point is in (X,Y) in pixels. Shape :math:`(K, N, 2)`. Where
+ `N` is the number of points and `K` the number of prompts.
+ keypoint_labels: Labels for the point prompts. 1 indicates a foreground point and 0 indicates a background
+ point. Shape :math:`(K, N)`. Where `N` is the number of points, and `K` the number of
+ prompts.
+ boxes: A box prompt to the model. If a tensor, should be in a xyxy mode. Shape :math:`(K, 4)`
+ masks: A low resolution mask input to the model, typically coming from a previous prediction
+ iteration. Has shape :math:`(K, 1, H, W)`, where for SAM, H=W=256.
+ multimask_output: If true, the model will return three masks. For ambiguous input prompts (such as a
+ single click), this will often produce better masks than a single prediction. If only
+ a single mask is needed, the model's predicted quality score can be used to select the
+ best mask. For non-ambiguous prompts, such as multiple input prompts,
+ multimask_output=False can give better results.
+ output_original_size: If true, the logits of `SegmentationResults` will be post-process to match the
+ original input image size.
+ Returns:
+ A prediction with the logits and scores (IoU of each predicted mask)
+ """
+
+ KORNIA_CHECK(self.is_image_set, 'An image must be set with `self.set_image(...)` before `predict` be called!')
+
+ prompts = self.preprocess_prompts(keypoints, keypoints_labels, boxes, masks)
+
+ # Embed prompts
+ sparse_embeddings, dense_embeddings = self.model.prompt_encoder(
+ points=prompts.points, boxes=prompts.boxes, masks=prompts.masks
+ )
+ del prompts
+
+ # Predict masks
+ logits, scores = self.model.mask_decoder(
+ image_embeddings=self.image_embeddings,
+ image_pe=self.model.prompt_encoder.get_dense_pe(),
+ sparse_prompt_embeddings=sparse_embeddings,
+ dense_prompt_embeddings=dense_embeddings,
+ multimask_output=multimask_output,
+ )
+ results = SegmentationResults(logits, scores)
+ if (
+ output_original_size
+ and isinstance(self._input_image_size, tuple)
+ and isinstance(self._original_image_size, tuple)
+ ):
+ results.original_res_logits(self._input_image_size, self._original_image_size, self._input_encoder_size)
+
+ # results = results.squeeze(0)
+
+ return results
+
+ def reset_image(self) -> None:
+ self._tfs_params = None
+ self._original_image_size = None
+ self._input_image_size = None
+ self._input_encoder_size = None
+
+ if hasattr(self, 'image_embeddings'):
+ del self.image_embeddings
+
+ self.image_embeddings = None
+ self.is_image_set = False
+
+ def compile(
+ self,
+ *,
+ fullgraph: bool = False,
+ dynamic: bool = False,
+ backend: str = 'inductor',
+ mode: str | None = None,
+ options: dict[Any, Any] = {},
+ disable: bool = False,
+ ) -> None:
+ """Applies `torch.compile(...)`/dynamo API into the ImagePrompter API.
+
+ .. note:: For more information about the dynamo API check the official docs
+ https://pytorch.org/docs/stable/generated/torch.compile.html
+
+ Args:
+ fullgraph: Whether it is ok to break model into several subgraphs
+ dynamic: Use dynamic shape tracing
+ backend: backend to be used
+ mode: Can be either “default”, “reduce-overhead” or “max-autotune”
+ options: A dictionary of options to pass to the backend.
+ disable: Turn torch.compile() into a no-op for testing
+
+ Example:
+ >>> # prompter = ImagePrompter()
+ >>> # prompter.compile() # You should have torch >= 2.0.0 installed
+ >>> # Use the prompter methods ...
+ """
+
+ # self.set_image = torch.compile( # type: ignore[method-assign]
+ # self.set_image,
+ # fullgraph=fullgraph,
+ # dynamic=dynamic,
+ # backend=backend,
+ # mode=mode,
+ # options=options,
+ # disable=disable,
+ # )
+ # FIXME: compile set image will try to compile AugmentationSequential which fails
+ self.model.image_encoder = torch.compile( # type: ignore
+ self.model.image_encoder,
+ fullgraph=fullgraph,
+ dynamic=dynamic,
+ backend=backend,
+ mode=mode,
+ options=options,
+ disable=disable,
+ )
+
+ # self.preprocess_image = torch.compile( # type: ignore[method-assign]
+ # self.preprocess_image,
+ # fullgraph=fullgraph,
+ # dynamic=dynamic,
+ # backend=backend,
+ # mode=mode,
+ # options=options,
+ # disable=disable,
+ # )
+
+ # FIXME: compile predict will try to compile Preproc prompts, which need to compileAugmentationSequential
+ # which fails
+ # self.predict = torch.compile( # type: ignore[method-assign]
+ # self.predict,
+ # fullgraph=fullgraph,
+ # dynamic=dynamic,
+ # backend=backend,
+ # mode=mode,
+ # options=options,
+ # disable=disable,
+ # )
+ self.model.mask_decoder = torch.compile( # type: ignore
+ self.model.mask_decoder,
+ fullgraph=fullgraph,
+ dynamic=dynamic,
+ backend=backend,
+ mode=mode,
+ options=options,
+ disable=disable,
+ )
+ self.model.prompt_encoder = torch.compile( # type: ignore
+ self.model.prompt_encoder,
+ fullgraph=fullgraph,
+ dynamic=dynamic,
+ backend=backend,
+ mode=mode,
+ options=options,
+ disable=disable,
+ )
diff --git a/kornia/contrib/models/__init__.py b/kornia/contrib/models/__init__.py
new file mode 100644
index 000000000..35e5e5b82
--- /dev/null
+++ b/kornia/contrib/models/__init__.py
@@ -0,0 +1 @@
+from kornia.contrib.models.structures import Prompts, SegmentationResults
diff --git a/kornia/contrib/models/base.py b/kornia/contrib/models/base.py
new file mode 100644
index 000000000..60f28a770
--- /dev/null
+++ b/kornia/contrib/models/base.py
@@ -0,0 +1,57 @@
+from __future__ import annotations
+
+import os
+from abc import ABC, abstractmethod
+from typing import Any, Generic, 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: torch.device | None = 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]:
+ """This function should 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: str | None = None,
+ options: dict[Any, Any] = {},
+ 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 compiled
diff --git a/kornia/contrib/models/sam/__init__.py b/kornia/contrib/models/sam/__init__.py
new file mode 100644
index 000000000..9c13b90cb
--- /dev/null
+++ b/kornia/contrib/models/sam/__init__.py
@@ -0,0 +1 @@
+from kornia.contrib.models.sam.model import Sam, SamConfig, SamModelType
diff --git a/kornia/contrib/models/sam/architecture/__init__.py b/kornia/contrib/models/sam/architecture/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/kornia/contrib/models/sam/architecture/common.py b/kornia/contrib/models/sam/architecture/common.py
new file mode 100644
index 000000000..2a2039f68
--- /dev/null
+++ b/kornia/contrib/models/sam/architecture/common.py
@@ -0,0 +1,46 @@
+"""Based from the original code from Meta Platforms, Inc. and affiliates.
+
+https://github.com/facebookresearch/segment-
+anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/common.py
+"""
+from __future__ import annotations
+
+from typing import Any
+
+from torch import nn, ones
+
+from kornia.core import Module, Tensor, zeros
+
+
+class MLPBlock(Module):
+ def __init__(self, embedding_dim: int, mlp_dim: int, act: type[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:
+ return self.lin2(self.act(self.lin1(x)))
+
+
+# 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):
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
+ super().__init__()
+ self.weight = nn.Parameter(ones(num_channels))
+ self.bias = nn.Parameter(zeros(num_channels))
+ self.eps = eps
+
+ def forward(self, x: Tensor) -> Tensor:
+ u = x.mean(1, keepdim=True)
+ s = (x - u).pow(2).mean(1, keepdim=True)
+ x = (x - u) / (s + self.eps).sqrt()
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
+ return x
+
+
+class LayerNorm(nn.LayerNorm):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self.eps = 1e-6
diff --git a/kornia/contrib/models/sam/architecture/image_encoder.py b/kornia/contrib/models/sam/architecture/image_encoder.py
new file mode 100644
index 000000000..14b300143
--- /dev/null
+++ b/kornia/contrib/models/sam/architecture/image_encoder.py
@@ -0,0 +1,365 @@
+"""Based from the original code from Meta Platforms, Inc. and affiliates.
+
+https://github.com/facebookresearch/segment-
+anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/image_encoder.py
+"""
+from __future__ import annotations
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from kornia.contrib.models.sam.architecture.common import LayerNorm2d, MLPBlock
+from kornia.core import Module, Tensor, pad, zeros
+
+
+# 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):
+ def __init__(
+ self,
+ img_size: int = 1024,
+ patch_size: int = 16,
+ in_chans: int = 3,
+ embed_dim: int = 768,
+ depth: int = 12,
+ num_heads: int = 12,
+ 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,
+ use_abs_pos: bool = True,
+ use_rel_pos: bool = False,
+ rel_pos_zero_init: bool = True,
+ window_size: int = 0,
+ global_attn_indexes: tuple[int, ...] = (),
+ ) -> None:
+ """
+ Args:
+ img_size: Input image size.
+ patch_size: Patch size.
+ in_chans: Number of input image channels.
+ embed_dim: Patch embedding dimension.
+ depth: Depth of ViT.
+ num_heads: Number of attention heads in each ViT block.
+ mlp_ratio: Ratio of mlp hidden dim to embedding dim.
+ qkv_bias: If True, add a learnable bias to query, key, value.
+ norm_layer: Normalization layer.
+ act_layer: Activation layer.
+ use_abs_pos: If True, use absolute positional embeddings.
+ use_rel_pos: If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init: If True, zero initialize relative positional parameters.
+ window_size: Window size for window attention blocks.
+ global_attn_indexes: Indexes for blocks using global attention.
+ """
+ super().__init__()
+ self.img_size = img_size
+
+ self.patch_embed = PatchEmbed(
+ kernel_size=(patch_size, patch_size),
+ stride=(patch_size, patch_size),
+ in_chans=in_chans,
+ embed_dim=embed_dim,
+ )
+
+ self.pos_embed: nn.Parameter | None = None
+ if 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.blocks = nn.ModuleList()
+ for i in range(depth):
+ block = Block(
+ dim=embed_dim,
+ num_heads=num_heads,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ norm_layer=norm_layer,
+ act_layer=act_layer,
+ use_rel_pos=use_rel_pos,
+ rel_pos_zero_init=rel_pos_zero_init,
+ window_size=window_size if i not in global_attn_indexes else 0,
+ input_size=(img_size // patch_size, img_size // patch_size),
+ )
+ self.blocks.append(block)
+
+ self.neck = nn.Sequential(
+ nn.Conv2d(embed_dim, out_chans, kernel_size=1, bias=False),
+ LayerNorm2d(out_chans),
+ nn.Conv2d(out_chans, out_chans, kernel_size=3, padding=1, bias=False),
+ LayerNorm2d(out_chans),
+ )
+
+ def forward(self, x: Tensor) -> Tensor:
+ x = self.patch_embed(x)
+ if self.pos_embed is not None:
+ x = x + self.pos_embed
+
+ for blk in self.blocks:
+ x = blk(x)
+
+ x = self.neck(x.permute(0, 3, 1, 2))
+
+ return x
+
+
+class Block(Module):
+ """Transformer blocks with support of window attention and residual propagation blocks."""
+
+ def __init__(
+ self,
+ dim: int,
+ num_heads: int,
+ mlp_ratio: float = 4.0,
+ qkv_bias: bool = True,
+ norm_layer: type[Module] = nn.LayerNorm,
+ act_layer: type[Module] = nn.GELU,
+ use_rel_pos: bool = False,
+ rel_pos_zero_init: bool = True,
+ window_size: int = 0,
+ input_size: tuple[int, int] | None = None,
+ ) -> None:
+ """
+ Args:
+ dim: Number of input channels.
+ num_heads: Number of attention heads in each ViT block.
+ mlp_ratio: Ratio of mlp hidden dim to embedding dim.
+ qkv_bias: If True, add a learnable bias to query, key, value.
+ norm_layer: Normalization layer.
+ act_layer: Activation layer.
+ use_rel_pos: If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init: If True, zero initialize relative positional parameters.
+ window_size: Window size for window attention blocks. If it equals 0, then use global attention.
+ input_size: Input resolution for calculating the relative positional parameter size.
+ """
+ super().__init__()
+ self.norm1 = norm_layer(dim)
+ self.attn = Attention(
+ dim,
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ use_rel_pos=use_rel_pos,
+ rel_pos_zero_init=rel_pos_zero_init,
+ input_size=input_size if window_size == 0 else (window_size, window_size),
+ )
+
+ self.norm2 = norm_layer(dim)
+ self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
+
+ self.window_size = window_size
+
+ def forward(self, x: Tensor) -> Tensor:
+ shortcut = x
+ x = self.norm1(x)
+ # Window partition
+ if self.window_size > 0:
+ H, W = x.shape[1], x.shape[2]
+ x, pad_hw = window_partition(x, self.window_size)
+
+ x = self.attn(x)
+ # Reverse window partition
+ if self.window_size > 0:
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
+
+ x = shortcut + x
+ x = x + self.mlp(self.norm2(x))
+
+ return x
+
+
+class Attention(Module):
+ """Multi-head Attention block with relative position embeddings."""
+
+ def __init__(
+ self,
+ dim: int,
+ num_heads: int = 8,
+ qkv_bias: bool = True,
+ use_rel_pos: bool = False,
+ rel_pos_zero_init: bool = True,
+ input_size: tuple[int, int] | None = None,
+ ) -> None:
+ """
+ Args:
+ dim: Number of input channels.
+ num_heads: Number of attention heads.
+ qkv_bias: If True, add a learnable bias to query, key, value.
+ rel_pos: If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init: If True, zero initialize relative positional parameters.
+ input_size: Input resolution for calculating the relative positional parameter size.
+ """
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = head_dim**-0.5
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.proj = nn.Linear(dim, dim)
+
+ self.use_rel_pos = use_rel_pos
+ if 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))
+
+ def forward(self, x: Tensor) -> 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)
+ # q, k, v with shape (B * nHead, H * W, C)
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
+
+ attn = (q * self.scale) @ k.transpose(-2, -1)
+
+ if self.use_rel_pos:
+ attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
+
+ attn = attn.softmax(dim=-1)
+ x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
+ x = self.proj(x)
+
+ return x
+
+
+def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, int]]:
+ """Partition into non-overlapping windows with padding if needed.
+
+ Args:
+ x: input tokens with [B, H, W, C].
+ window_size: window size.
+
+ Returns:
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
+ (Hp, Wp): padded height and width before partition
+ """
+ B, H, W, C = x.shape
+
+ pad_h = (window_size - H % window_size) % window_size
+ pad_w = (window_size - W % window_size) % window_size
+ if pad_h > 0 or pad_w > 0:
+ x = pad(x, (0, 0, 0, pad_w, 0, pad_h))
+ Hp, Wp = H + pad_h, W + pad_w
+
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
+ return windows, (Hp, Wp)
+
+
+def window_unpartition(windows: Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int]) -> Tensor:
+ """Window unpartition into original sequences and removing padding.
+
+ Args:
+ x: input tokens with [B * num_windows, window_size, window_size, C].
+ window_size: window size.
+ pad_hw: padded height and width (Hp, Wp).
+ hw: original height and width (H, W) before padding.
+
+ Returns:
+ x: unpartitioned sequences with [B, H, W, C].
+ """
+ Hp, Wp = pad_hw
+ H, W = hw
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
+
+ if Hp > H or Wp > W:
+ x = x[:, :H, :W, :].contiguous()
+ return x
+
+
+def get_rel_pos(q_size: int, k_size: int, rel_pos: Tensor) -> Tensor:
+ """Get relative positional embeddings according to the relative positions of query and key sizes.
+
+ Args:
+ q_size: size of query q.
+ k_size: size of key k.
+ rel_pos: relative position embeddings (L, C).
+
+ Returns:
+ Extracted positional embeddings according to relative positions.
+ """
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
+ # Interpolate rel pos if needed.
+ if rel_pos.shape[0] != max_rel_dist:
+ # Interpolate rel pos.
+ rel_pos_resized = F.interpolate(
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode="linear"
+ )
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
+ else:
+ rel_pos_resized = rel_pos
+
+ # Scale the coords with short length if shapes for q and k are different.
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
+
+ return rel_pos_resized[relative_coords.long()]
+
+
+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:
+ """Calculate decomposed Relative Positional Embeddings.
+
+ from :paper:`mvitv2`.
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
+
+
+ Args:
+ attn: attention map.
+ q: query q in the attention layer with shape (B, q_h * q_w, C).
+ rel_pos_h: relative position embeddings (Lh, C) for height axis.
+ rel_pos_w: relative position embeddings (Lw, C) for width axis.
+ q_size: spatial sequence size of query q with (q_h, q_w).
+ k_size: spatial sequence size of key k with (k_h, k_w).
+
+ Returns:
+ att: attention map with added relative positional embeddings.
+ """
+ q_h, q_w = q_size
+ k_h, k_w = k_size
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
+
+ B, _, dim = q.shape
+ r_q = q.reshape(B, q_h, q_w, dim)
+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
+
+ attn = (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view(
+ B, q_h * q_w, k_h * k_w
+ )
+
+ return attn
+
+
+class PatchEmbed(Module):
+ """Image to Patch Embedding."""
+
+ def __init__(
+ self,
+ kernel_size: tuple[int, int] = (16, 16),
+ stride: tuple[int, int] = (16, 16),
+ padding: tuple[int, int] = (0, 0),
+ in_chans: int = 3,
+ embed_dim: int = 768,
+ ) -> None:
+ """
+ Args:
+ kernel_size: kernel size of the projection layer.
+ stride: stride of the projection layer.
+ padding: padding size of the projection layer.
+ in_chans: Number of input image channels.
+ embed_dim: Patch embedding dimension.
+ """
+ super().__init__()
+
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding)
+
+ def forward(self, x: Tensor) -> Tensor:
+ x = self.proj(x)
+ # B C H W -> B H W C
+ x = x.permute(0, 2, 3, 1)
+ return x
diff --git a/kornia/contrib/models/sam/architecture/mask_decoder.py b/kornia/contrib/models/sam/architecture/mask_decoder.py
new file mode 100644
index 000000000..1f731d5cd
--- /dev/null
+++ b/kornia/contrib/models/sam/architecture/mask_decoder.py
@@ -0,0 +1,159 @@
+"""Based from the original code from Meta Platforms, Inc. and affiliates.
+
+https://github.com/facebookresearch/segment-
+anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/mask_decoder.py
+"""
+from __future__ import annotations
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from kornia.contrib.models.sam.architecture.common import LayerNorm2d
+from kornia.core import Module, Tensor, concatenate, stack
+
+
+class MaskDecoder(Module):
+ def __init__(
+ self,
+ *,
+ transformer_dim: int,
+ transformer: Module,
+ num_multimask_outputs: int = 3,
+ activation: type[Module] = nn.GELU,
+ iou_head_depth: int = 3,
+ iou_head_hidden_dim: int = 256,
+ ) -> None:
+ """Predicts masks given an image and prompt embeddings, using a tranformer architecture.
+
+ Args:
+ transformer_dim: the channel dimension of the transformer
+ transformer: the transformer used to predict masks
+ num_multimask_outputs: the number of masks to predict when disambiguating masks
+ activation: the type of activation to use when upscaling masks
+ iou_head_depth: the depth of the MLP used to predict mask quality
+ iou_head_hidden_dim: the hidden dimension of the MLP used to predict mask quality
+ """
+ super().__init__()
+ self.transformer_dim = transformer_dim
+ self.transformer = transformer
+
+ self.num_multimask_outputs = num_multimask_outputs
+
+ self.iou_token = nn.Embedding(1, transformer_dim)
+ self.num_mask_tokens = num_multimask_outputs + 1
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
+
+ self.output_upscaling = nn.Sequential(
+ nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
+ LayerNorm2d(transformer_dim // 4),
+ activation(),
+ nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
+ activation(),
+ )
+ self.output_hypernetworks_mlps = nn.ModuleList(
+ [MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for i in range(self.num_mask_tokens)]
+ )
+
+ self.iou_prediction_head = MLP(transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth)
+
+ def forward(
+ self,
+ image_embeddings: Tensor,
+ image_pe: Tensor,
+ sparse_prompt_embeddings: Tensor,
+ dense_prompt_embeddings: Tensor,
+ multimask_output: bool,
+ ) -> tuple[Tensor, Tensor]:
+ """Predict masks given image and prompt embeddings.
+
+ Args:
+ image_embeddings: the embeddings from the image encoder
+ image_pe: positional encoding with the shape of image_embeddings
+ sparse_prompt_embeddings: the embeddings of the points and boxes
+ dense_prompt_embeddings: the embeddings of the mask inputs
+ multimask_output: Whether to return multiple masks or a single mask.
+
+ Returns:
+ batched predicted masks
+ batched predictions of mask quality
+ """
+ masks, iou_pred = self.predict_masks(
+ image_embeddings=image_embeddings,
+ image_pe=image_pe,
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
+ dense_prompt_embeddings=dense_prompt_embeddings,
+ )
+
+ # Select the correct mask or masks for outptu
+ if multimask_output:
+ mask_slice = slice(1, None)
+ else:
+ mask_slice = slice(0, 1)
+ masks = masks[:, mask_slice, :, :]
+ iou_pred = iou_pred[:, mask_slice]
+
+ # Prepare output
+ return masks, iou_pred
+
+ def predict_masks(
+ self,
+ image_embeddings: Tensor,
+ image_pe: Tensor,
+ sparse_prompt_embeddings: Tensor,
+ dense_prompt_embeddings: Tensor,
+ ) -> tuple[Tensor, 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 = output_tokens[None, ...].expand(sparse_prompt_embeddings.size(0), -1, -1)
+ tokens = concatenate((output_tokens, sparse_prompt_embeddings), dim=1)
+
+ # Expand per-image data in batch direction to be per-mask
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
+ src = src + dense_prompt_embeddings
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
+ b, c, h, w = src.shape
+
+ # Run the transformer
+ hs, src = self.transformer(src, pos_src, tokens)
+ iou_token_out = hs[:, 0, :]
+ mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :]
+
+ # Upscale mask embeddings and predict masks using the mask tokens
+ src = src.transpose(1, 2).view(b, c, h, w)
+ upscaled_embedding = self.output_upscaling(src)
+ hyper_in_list: list[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)
+ b, c, h, w = upscaled_embedding.shape
+ masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
+
+ # Generate mask quality predictions
+ iou_pred = self.iou_prediction_head(iou_token_out)
+
+ return masks, iou_pred
+
+
+# Lightly adapted from
+# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py
+class MLP(Module):
+ def __init__(
+ self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
+ ) -> None:
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ 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):
+ 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:
+ x = F.sigmoid(x)
+ return x
diff --git a/kornia/contrib/models/sam/architecture/prompt_encoder.py b/kornia/contrib/models/sam/architecture/prompt_encoder.py
new file mode 100644
index 000000000..1e45a5cbb
--- /dev/null
+++ b/kornia/contrib/models/sam/architecture/prompt_encoder.py
@@ -0,0 +1,182 @@
+"""Based from the original code from Meta Platforms, Inc. and affiliates.
+
+https://github.com/facebookresearch/segment-
+anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/prompt_encoder.py
+"""
+from __future__ import annotations
+
+from math import pi
+
+import torch
+from torch import nn
+
+from kornia.contrib.models.sam.architecture.common import LayerNorm2d
+from kornia.core import Device, Module, Tensor, concatenate, stack, zeros
+
+
+class PromptEncoder(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,
+ ) -> None:
+ """Encodes prompts for input to SAM's mask decoder.
+
+ Args:
+ embed_dim: The prompts' embedding dimension
+ image_embedding_size: The spatial size of the image embedding, as (H, W).
+ input_image_size: The padded size of the image as input to the image encoder, as (H, W).
+ mask_in_chans: The number of hidden channels used for encoding input masks.
+ activation: The activation to use when encoding input masks.
+ """
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.input_image_size = input_image_size
+ self.image_embedding_size = image_embedding_size
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
+
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
+ point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)]
+ self.point_embeddings = nn.ModuleList(point_embeddings)
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
+
+ self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])
+ self.mask_downscaling = nn.Sequential(
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
+ LayerNorm2d(mask_in_chans // 4),
+ activation(),
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
+ LayerNorm2d(mask_in_chans),
+ activation(),
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
+ )
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
+
+ def get_dense_pe(self) -> Tensor:
+ """Returns the positional encoding used to encode point prompts, applied to a dense set of points the shape
+ of the image encoding.
+
+ Returns:
+ Positional encoding with shape 1x(embed_dim)x(embedding_h)x(embedding_w)
+ """
+ return self.pe_layer(self.image_embedding_size)[None, ...]
+
+ def _embed_points(self, points: Tensor, labels: Tensor, pad: bool) -> Tensor:
+ """Embeds point prompts."""
+ points = points + 0.5 # Shift to center of pixel
+ if pad:
+ padding_point = 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)
+ point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)
+ point_embedding[labels == -1] = 0.0
+ point_embedding[labels == -1] += self.not_a_point_embed.weight
+ point_embedding[labels == 0] += self.point_embeddings[0].weight
+ point_embedding[labels == 1] += self.point_embeddings[1].weight
+ return point_embedding
+
+ def _embed_boxes(self, boxes: Tensor) -> Tensor:
+ """Embeds box prompts."""
+ boxes = boxes + 0.5 # Shift to center of pixel
+ coords = boxes.reshape(-1, 2, 2)
+ corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
+ return corner_embedding
+
+ def _embed_masks(self, masks: Tensor) -> Tensor:
+ """Embeds mask inputs."""
+ mask_embedding = self.mask_downscaling(masks)
+ return mask_embedding
+
+ def _get_batch_size(self, points: tuple[Tensor, Tensor] | None, boxes: Tensor | None, masks: Tensor | None) -> int:
+ """Gets the batch size of the output given the batch size of the input prompts."""
+ if points is not None:
+ return points[0].shape[0]
+ elif boxes is not None:
+ return boxes.shape[0]
+ elif masks is not None:
+ return masks.shape[0]
+ else:
+ return 1
+
+ def _get_device(self) -> Device:
+ return self.point_embeddings[0].weight.device
+
+ def forward(
+ self, points: tuple[Tensor, Tensor] | None, boxes: Tensor | None, masks: Tensor | None
+ ) -> tuple[Tensor, Tensor]:
+ """Embeds different types of prompts, returning both sparse and dense embeddings.
+
+ Args:
+ points: point coordinates and labels to embed.
+ boxes: boxes to embed
+ masks: masks to embed
+
+ Returns:
+ - sparse embeddings for the points and boxes, with shape BxNx(embed_dim), where N is determined by the
+ number of input points and boxes.
+ - dense embeddings for the masks, in the shape Bx(embed_dim)x(embed_H)x(embed_W)
+ """
+ bs = self._get_batch_size(points, boxes, masks)
+ sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
+ if points is not None:
+ coords, labels = points
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
+ sparse_embeddings = concatenate([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)
+
+ if masks is not None:
+ dense_embeddings = self._embed_masks(masks)
+ else:
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
+ )
+
+ return sparse_embeddings, dense_embeddings
+
+
+class PositionEmbeddingRandom(Module):
+ """Positional encoding using random spatial frequencies."""
+
+ def __init__(self, num_pos_feats: int = 64, scale: float | None = None) -> None:
+ super().__init__()
+ if scale is None or scale <= 0.0:
+ scale = 1.0
+ self.register_buffer("positional_encoding_gaussian_matrix", scale * torch.randn((2, num_pos_feats)))
+
+ def _pe_encoding(self, coords: Tensor) -> 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 shape
+ coords = 2 * coords - 1
+ coords = coords @ self.positional_encoding_gaussian_matrix
+ coords = 2 * pi * coords
+ # outputs d_1 x ... x d_n x C shape
+ return concatenate([torch.sin(coords), torch.cos(coords)], dim=-1)
+
+ def forward(self, size: tuple[int, int]) -> Tensor:
+ """Generate positional encoding for a grid of the specified size."""
+ h, w = size
+ _dev = self.positional_encoding_gaussian_matrix.device
+ device = _dev if isinstance(_dev, torch.device) else None
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
+ y_embed = grid.cumsum(dim=0) - 0.5
+ x_embed = grid.cumsum(dim=1) - 0.5
+ y_embed = y_embed / h
+ x_embed = x_embed / w
+
+ pe = self._pe_encoding(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:
+ """Positionally encode points that are not normalized to [0,1]."""
+ coords = coords_input.clone()
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
+ return self._pe_encoding(coords.to(torch.float32)) # B x N x C
diff --git a/kornia/contrib/models/sam/architecture/transformer.py b/kornia/contrib/models/sam/architecture/transformer.py
new file mode 100644
index 000000000..af96dd233
--- /dev/null
+++ b/kornia/contrib/models/sam/architecture/transformer.py
@@ -0,0 +1,210 @@
+"""Based from the original code from Meta Platforms, Inc. and affiliates.
+
+https://github.com/facebookresearch/segment-
+anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/transformer.py
+"""
+from __future__ import annotations
+
+import math
+
+from torch import nn
+
+from kornia.contrib.models.sam.architecture.common import MLPBlock
+from kornia.core import Module, Tensor
+from kornia.core.check import KORNIA_CHECK
+
+
+class TwoWayTransformer(Module):
+ def __init__(
+ self,
+ depth: int,
+ embedding_dim: int,
+ num_heads: int,
+ mlp_dim: int,
+ activation: type[Module] = nn.ReLU,
+ attention_downsample_rate: int = 2,
+ ) -> None:
+ """A transformer decoder that attends to an input image using queries whose positional embedding is
+ supplied.
+
+ Args:
+ depth: number of layers in the transformer
+ embedding_dim: the channel dimension for the input embeddings
+ num_heads: the number of heads for multihead attention. Must divide embedding_dim
+ mlp_dim: the channel dimension internal to the MLP block
+ activation: the activation to use in the MLP block
+ """
+ super().__init__()
+ self.depth = depth
+ self.embedding_dim = embedding_dim
+ self.num_heads = num_heads
+ self.mlp_dim = mlp_dim
+ self.layers = nn.ModuleList()
+
+ for i in range(depth):
+ self.layers.append(
+ TwoWayAttentionBlock(
+ embedding_dim=embedding_dim,
+ num_heads=num_heads,
+ mlp_dim=mlp_dim,
+ activation=activation,
+ attention_downsample_rate=attention_downsample_rate,
+ skip_first_layer_pe=(i == 0),
+ )
+ )
+
+ 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]:
+ """
+ Args:
+ image_embedding: image to attend to. Should be shape B x embedding_dim x h x w for any h and w.
+ image_pe: the positional encoding to add to the image. Must have the same shape as image_embedding.
+ point_embedding: the embedding to add to the query points. Must have shape B x N_points x embedding_dim
+ for any N_points.
+
+ Returns:
+ - the processed point_embedding
+ - the processed image_embedding
+ """
+ # BxCxHxW -> BxHWxC == B x N_image_tokens x C
+ bs, c, h, w = image_embedding.shape
+ image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
+ image_pe = image_pe.flatten(2).permute(0, 2, 1)
+
+ # Prepare queries
+ queries = point_embedding
+ keys = image_embedding
+
+ # Apply transformer blocks and final layernorm
+ for layer in self.layers:
+ queries, keys = layer(queries=queries, keys=keys, query_pe=point_embedding, key_pe=image_pe)
+
+ # Apply the final attenion layer from the points to the image
+ q = queries + point_embedding
+ k = keys + image_pe
+ attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
+ queries = queries + attn_out
+ queries = self.norm_final_attn(queries)
+
+ return queries, keys
+
+
+class TwoWayAttentionBlock(Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ num_heads: int,
+ mlp_dim: int = 2048,
+ activation: type[Module] = nn.ReLU,
+ attention_downsample_rate: int = 2,
+ skip_first_layer_pe: bool = False,
+ ) -> None:
+ """A transformer block with four layers: (1) self-attention of sparse inputs, (2) cross attention of sparse
+ inputs to dense inputs, (3) mlp block on sparse inputs, and (4) cross attention of dense inputs to sparse
+ inputs.
+
+ Args:
+ embedding_dim: the channel dimension of the embeddings
+ num_heads: the number of heads in the attention layers
+ mlp_dim: the hidden dimension of the mlp block
+ activation: the activation of the mlp block
+ skip_first_layer_pe: skip the PE on the first layer
+ """
+ super().__init__()
+ self.self_attn = Attention(embedding_dim, num_heads)
+ self.norm1 = nn.LayerNorm(embedding_dim)
+
+ self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
+ self.norm2 = nn.LayerNorm(embedding_dim)
+
+ self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
+ self.norm3 = nn.LayerNorm(embedding_dim)
+
+ self.norm4 = nn.LayerNorm(embedding_dim)
+ self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)
+
+ 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]:
+ # Self attention block
+ if self.skip_first_layer_pe:
+ queries = self.self_attn(q=queries, k=queries, v=queries)
+ else:
+ q = queries + query_pe
+ attn_out = self.self_attn(q=q, k=q, v=queries)
+ queries = queries + attn_out
+ queries = self.norm1(queries)
+
+ # Cross attention block, tokens attending to image embedding
+ q = queries + query_pe
+ k = keys + key_pe
+ attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
+ queries = queries + attn_out
+ queries = self.norm2(queries)
+
+ # MLP block
+ mlp_out = self.mlp(queries)
+ queries = queries + mlp_out
+ queries = self.norm3(queries)
+
+ # Cross attention block, image embedding attending to tokens
+ q = queries + query_pe
+ k = keys + key_pe
+ attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
+ keys = keys + attn_out
+ keys = self.norm4(keys)
+
+ return queries, keys
+
+
+class Attention(Module):
+ """An attention layer that allows for downscaling the size of the embedding after projection to queries, keys,
+ and values."""
+
+ def __init__(self, embedding_dim: int, num_heads: int, downsample_rate: int = 1) -> None:
+ super().__init__()
+ self.embedding_dim = embedding_dim
+ self.internal_dim = embedding_dim // downsample_rate
+ self.num_heads = num_heads
+ KORNIA_CHECK(self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim.")
+
+ self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
+ self.k_proj = nn.Linear(embedding_dim, self.internal_dim)
+ 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:
+ b, n, c = x.shape
+ x = 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:
+ b, n_heads, n_tokens, c_per_head = x.shape
+ x = 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:
+ # Input projections
+ q = self.q_proj(q)
+ k = self.k_proj(k)
+ v = self.v_proj(v)
+
+ # Separate into heads
+ q = self._separate_heads(q, self.num_heads)
+ k = self._separate_heads(k, self.num_heads)
+ v = self._separate_heads(v, self.num_heads)
+
+ # Attention
+ _, _, _, c_per_head = q.shape
+ attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens
+ attn = attn / math.sqrt(c_per_head)
+ attn = attn.softmax(dim=-1)
+
+ # Get output
+ out = attn @ v
+ out = self._recombine_heads(out)
+ out = self.out_proj(out)
+
+ return out
diff --git a/kornia/contrib/models/sam/model.py b/kornia/contrib/models/sam/model.py
new file mode 100644
index 000000000..7c5cde292
--- /dev/null
+++ b/kornia/contrib/models/sam/model.py
@@ -0,0 +1,259 @@
+"""Based from the original code from Meta Platforms, Inc. and affiliates.
+
+https://github.com/facebookresearch/segment-
+anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/build_sam.py
+
+https://github.com/facebookresearch/segment-
+anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling/sam.py
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any
+
+import 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.core import Tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+
+
+class SamModelType(Enum):
+ """Map the SAM model types."""
+
+ vit_h = 0
+ vit_l = 1
+ vit_b = 2
+
+
+@dataclass
+class SamConfig:
+ """Encapsulate the Config to build a SAM model.
+
+ Args:
+ model_type: the available models are:
+
+ - 0, 'vit_h' or :func:`kornia.contrib.sam.SamModelType.vit_h`
+ - 1, 'vit_l' or :func:`kornia.contrib.sam.SamModelType.vit_l`
+ - 2, 'vit_b' or :func:`kornia.contrib.sam.SamModelType.vit_b`
+
+ checkpoint: URL or a path for a file with the weights of the model
+ encoder_embed_dim: Patch embedding dimension.
+ encoder_depth: Depth of ViT.
+ encoder_num_heads: Number of attention heads in each ViT block.
+ encoder_global_attn_indexes: Encoder indexes for blocks using global attention.
+ """
+
+ model_type: str | int | SamModelType | None = None
+ checkpoint: str | None = None
+
+ encoder_embed_dim: int | None = None
+ encoder_depth: int | None = None
+ encoder_num_heads: int | None = None
+ encoder_global_attn_indexes: tuple[int, ...] | None = None
+
+
+class Sam(ModelBase[SamConfig]):
+ mask_threshold: float = 0.0
+
+ def __init__(
+ self, image_encoder: ImageEncoderViT, prompt_encoder: PromptEncoder, mask_decoder: MaskDecoder
+ ) -> None:
+ """SAM predicts object masks from an image and input prompts.
+
+ Args:
+ image_encoder: The backbone used to encode the image into image embeddings that allow for efficient mask
+ prediction.
+ prompt_encoder: Encodes various types of input prompts.
+ mask_decoder: Predicts masks from the image embeddings and encoded prompts.
+ """
+
+ super().__init__()
+ self.image_encoder = image_encoder
+ self.prompt_encoder = prompt_encoder
+ self.mask_decoder = mask_decoder
+
+ @staticmethod
+ def from_config(config: SamConfig) -> Sam:
+ """Build/load the SAM model based on it's config.
+
+ Args:
+ config: The SamConfig data structure. If the model_type is available, build from it, otherwise will use
+ the parameters set.
+ Returns:
+ The respective SAM model
+
+ Example:
+ >>> from kornia.contrib.models.sam import SamConfig
+ >>> sam_model = Sam.from_config(SamConfig('vit_b'))
+ """
+ model_type = config.model_type
+
+ if isinstance(model_type, int):
+ model_type = SamModelType(model_type)
+ elif isinstance(model_type, str):
+ _map_sam_type = {'vit_h': SamModelType.vit_h, 'vit_l': SamModelType.vit_l, 'vit_b': SamModelType.vit_b}
+ model_type = _map_sam_type[model_type]
+
+ if model_type == SamModelType.vit_b:
+ model = _build_sam(
+ encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=(2, 5, 8, 11)
+ )
+
+ elif model_type == SamModelType.vit_l:
+ model = _build_sam(
+ encoder_embed_dim=1024,
+ encoder_depth=24,
+ encoder_num_heads=16,
+ encoder_global_attn_indexes=(5, 11, 17, 23),
+ )
+
+ elif model_type == SamModelType.vit_h:
+ model = _build_sam(
+ encoder_embed_dim=1280,
+ encoder_depth=32,
+ encoder_num_heads=16,
+ encoder_global_attn_indexes=(7, 15, 23, 31),
+ )
+ elif (
+ isinstance(config.encoder_embed_dim, int)
+ and isinstance(config.encoder_depth, int)
+ and isinstance(config.encoder_num_heads, int)
+ and isinstance(config.encoder_global_attn_indexes, int)
+ ):
+ model = _build_sam(
+ encoder_embed_dim=config.encoder_embed_dim,
+ encoder_depth=config.encoder_depth,
+ encoder_num_heads=config.num_heads,
+ encoder_global_attn_indexes=config.encoder_global_attn_indexes,
+ )
+ else:
+ raise NotImplementedError('Unexpected config. The model_type should be provide or the encoder configs.')
+
+ if config.checkpoint:
+ model.load_checkpoint(config.checkpoint)
+
+ return model
+
+ @torch.no_grad()
+ def forward(
+ self, images: Tensor, batched_prompts: list[dict[str, Any]], multimask_output: bool
+ ) -> list[SegmentationResults]:
+ """Predicts masks end-to-end from provided images and prompts.
+
+ This method expects that the images have already been pre-processed, at least been normalized, resized and
+ padded to be compatible with the `self.image_encoder`.
+
+ .. note: For each image :math:`(3, H, W)`, it is possible to input a batch (:math:`K`) of :math:`N` prompts,
+ the results are batched by the number of prompts batch. So given a prompt with :math:`K=5`, and
+ :math:`N=10`, the results will look like :math:`5xCxHxW` where :math:`C` is determined by
+ multimask_output. And within each of these masks :math:`(5xC)`, it should be possible to find
+ :math:`N` instances if the model succeed.
+
+ Args:
+ images: The image as a torch tensor in :math:`(B, 3, H, W)` format, already transformed for input to the
+ model.
+ batched_prompts: A list over the batch of images (list length should be :math:`B`), each a dictionary with
+ the following keys. If it does not have the respective prompt, it should not be included
+ in 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:
+
+ - 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": (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)`.
+
+ 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.
+ - 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.
+ - scores: The model's predictions of mask quality (iou prediction), in shape BxC.
+ """
+
+ KORNIA_CHECK_SHAPE(images, ['B', '3', 'H', 'W'])
+ KORNIA_CHECK(
+ images.shape[0] == len(batched_prompts),
+ 'The number of images (`B`) should match with the length of prompts!',
+ )
+
+ image_embeddings = self.image_encoder(images)
+
+ outputs = []
+ for prompt_record, curr_embedding in zip(batched_prompts, image_embeddings):
+ # Embed prompts
+ sparse_embeddings, dense_embeddings = self.prompt_encoder(
+ points=prompt_record.get("points", None),
+ boxes=prompt_record.get("boxes", None),
+ masks=prompt_record.get("mask_inputs", None),
+ )
+
+ # Predict masks
+ low_res_logits, iou_predictions = self.mask_decoder(
+ image_embeddings=curr_embedding[None, ...],
+ image_pe=self.prompt_encoder.get_dense_pe(),
+ sparse_prompt_embeddings=sparse_embeddings,
+ dense_prompt_embeddings=dense_embeddings,
+ multimask_output=multimask_output,
+ )
+
+ # Save results
+ outputs.append(SegmentationResults(low_res_logits, iou_predictions, self.mask_threshold))
+
+ return outputs
+
+
+def _build_sam(
+ encoder_embed_dim: int, encoder_depth: int, encoder_num_heads: int, encoder_global_attn_indexes: tuple[int, ...]
+) -> Sam:
+ prompt_embed_dim = 256
+ image_size = 1024
+ vit_patch_size = 16
+ image_embedding_size = image_size // vit_patch_size
+
+ return Sam(
+ image_encoder=ImageEncoderViT(
+ depth=encoder_depth,
+ embed_dim=encoder_embed_dim,
+ img_size=image_size,
+ mlp_ratio=4,
+ norm_layer=LayerNorm,
+ num_heads=encoder_num_heads,
+ patch_size=vit_patch_size,
+ qkv_bias=True,
+ use_rel_pos=True,
+ global_attn_indexes=encoder_global_attn_indexes,
+ window_size=14,
+ out_chans=prompt_embed_dim,
+ ),
+ prompt_encoder=PromptEncoder(
+ embed_dim=prompt_embed_dim,
+ image_embedding_size=(image_embedding_size, image_embedding_size),
+ input_image_size=(image_size, image_size),
+ mask_in_chans=16,
+ ),
+ mask_decoder=MaskDecoder(
+ num_multimask_outputs=3,
+ transformer=TwoWayTransformer(depth=2, embedding_dim=prompt_embed_dim, mlp_dim=2048, num_heads=8),
+ transformer_dim=prompt_embed_dim,
+ iou_head_depth=3,
+ iou_head_hidden_dim=256,
+ ),
+ # pixel_mean=[123.675, 116.28, 103.53],
+ # pixel_std=[58.395, 57.12, 57.375],
+ )
diff --git a/kornia/contrib/models/structures.py b/kornia/contrib/models/structures.py
new file mode 100644
index 000000000..3384c55ca
--- /dev/null
+++ b/kornia/contrib/models/structures.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK
+from kornia.geometry.transform import resize
+
+
+@dataclass
+class SegmentationResults:
+ """Encapsulate the results obtained by a Segmentation model.
+
+ Args:
+ logits: Results logits with shape :math:`(B, C, H, W)`, where :math:`C` refers to the number of predicted masks
+ scores: The scores from the logits. Shape :math:`(B,)`
+ mask_threshold: The threshold value to generate the `binary_masks` from the `logits`
+ """
+
+ logits: Tensor
+ scores: Tensor
+ mask_threshold: float = 0.0
+
+ @property
+ def binary_masks(self) -> 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.
+
+ .. note: If you run `original_res_logits`, this will generate the masks based on the original resolution logits.
+ Otherwise, this will use the low resolution logits (self.logits).
+ """
+ if self._original_res_logits is not None:
+ x = self._original_res_logits
+ else:
+ x = self.logits
+
+ return x > self.mask_threshold
+
+ def original_res_logits(
+ self, input_size: tuple[int, int], original_size: tuple[int, int], image_size_encoder: tuple[int, int] | None
+ ) -> 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
+
+ .. note: This method set a internal `original_res_logits` which will be used if available for the binary masks.
+
+ Args:
+ input_size: The size of the image input to the model, in (H, W) format. Used to remove padding.
+ original_size: The original size of the image before resizing for input to the model, in (H, W) format.
+ image_size_encoder: The size of the input image for image encoder, in (H, W) format. Used to resize the
+ logits back to encoder resolution before remove the padding.
+
+ Returns:
+ Batched logits in :math:`(K, C, H, W)` format, where (H, W) is given by original_size.
+ """
+ x = self.logits
+
+ if isinstance(image_size_encoder, tuple):
+ x = resize(x, size=image_size_encoder, interpolation='bilinear', align_corners=False, antialias=False)
+ x = x[..., : input_size[0], : input_size[1]]
+
+ x = resize(x, size=original_size, interpolation='bilinear', align_corners=False, antialias=False)
+
+ self._original_res_logits = x
+ return self._original_res_logits
+
+ def squeeze(self, dim: int = 0) -> 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):
+ self._original_res_logits = self._original_res_logits.squeeze(dim)
+
+ return self
+
+
+@dataclass
+class Prompts:
+ """Encapsulate the prompts inputs for a Model.
+
+ Args:
+ points: A tuple with the keypoints (coordinates x, y) and their respective labels. Shape :math:`(K, N, 2)` for
+ the keypoints, and :math:`(K, N)`
+ boxes: Batched box inputs, with shape :math:`(K, 4)`. Expected to be into xyxy format.
+ masks: Batched mask prompts to the model with shape :math:`(K, 1, H, W)`
+ """
+
+ points: tuple[Tensor, Tensor] | None = None
+ boxes: Tensor | None = None
+ masks: Tensor | None = None
+
+ def __post_init__(self) -> None:
+ if isinstance(self.keypoints, Tensor) and isinstance(self.boxes, Tensor):
+ KORNIA_CHECK(self.keypoints.shape[0] == self.boxes.shape[0], 'The prompts should have the same batch size!')
+
+ @property
+ def keypoints(self) -> Tensor | None:
+ """The keypoints from the `points`"""
+ return self.points[0] if isinstance(self.points, tuple) else None
+
+ @property
+ def keypoints_labels(self) -> Tensor | None:
+ """The keypoints labels from the `points`"""
+ return self.points[1] if isinstance(self.points, tuple) else None
diff --git a/kornia/io/io.py b/kornia/io/io.py
index e5beac4a9..7c0534813 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -12,7 +12,7 @@ from torch.utils import dlpack # TODO: remove this if kornia relies on torch>=
from kornia.color import rgb_to_grayscale, rgba_to_rgb
from kornia.color.gray import grayscale_to_rgb
from kornia.color.rgb import rgb_to_rgba
-from kornia.core import Tensor
+from kornia.core import Device, Tensor
from kornia.core.check import KORNIA_CHECK
@@ -26,7 +26,7 @@ class ImageLoadType(Enum):
RGB32 = 5
-def load_image_to_tensor(path_file: str, device: str) -> Tensor:
+def load_image_to_tensor(path_file: str, device: Device) -> Tensor:
# load the file and decodes using kornia_rs. Internally it uses a package that
# combines image-rs a self maintained version of the dlpack-rs. After the decoding,
# the obtained stream bits are encapusalted to a cv::Tensor data structure without
@@ -38,7 +38,8 @@ def load_image_to_tensor(path_file: str, device: str) -> Tensor:
th_tensor = dlpack.from_dlpack(cv_tensor) # HxWx3
# move the tensor to the desired device, move the data layout to CHW and clone
# to return an owned data tensor.
- return th_tensor.to(torch.device(device)).permute(2, 0, 1).clone() # CxHxW
+ dev = device if isinstance(device, torch.device) or device is None else torch.device(device)
+ return th_tensor.to(device=dev).permute(2, 0, 1).clone() # CxHxW
def to_float32(image: Tensor) -> Tensor:
@@ -51,7 +52,7 @@ def to_uint8(image: Tensor) -> Tensor:
return image.mul(255.0).byte()
-def load_image(path_file: str, desired_type: ImageLoadType, device: str = "cpu") -> Tensor:
+def load_image(path_file: str, desired_type: ImageLoadType, device: Device = "cpu") -> Tensor:
"""Read an image file and decode using the Kornia Rust backend.
Args:
diff --git a/test/contrib/__init__.py b/test/contrib/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/test/contrib/models/__init__.py b/test/contrib/models/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/test/contrib/models/test_sam.py b/test/contrib/models/test_sam.py
new file mode 100644
index 000000000..2359999ba
--- /dev/null
+++ b/test/contrib/models/test_sam.py
@@ -0,0 +1,84 @@
+import pytest
+import torch
+
+from kornia.contrib.models.sam import Sam, SamConfig
+from kornia.core import pad
+from kornia.testing import BaseTester
+
+
+def _pad_rb(x, size):
+ """Pads right bottom."""
+ pad_h = size - x.shape[-2]
+ pad_w = size - x.shape[-1]
+ return pad(x, (0, pad_w, 0, pad_h))
+
+
+class TestSam(BaseTester):
+ def test_smoke(self):
+ ...
+
+ @pytest.mark.parametrize('batch_size', [1, 3])
+ @pytest.mark.parametrize('N', [2, 5])
+ @pytest.mark.parametrize('multimask_output', [True, False])
+ def test_cardinality(self, device, batch_size, N, multimask_output):
+ # SAM: don't supports float64
+ dtype = torch.float32
+ inpt = torch.rand(1, 3, 77, 128, device=device, dtype=dtype)
+ model = Sam.from_config(SamConfig('vit_b'))
+ model = model.to(device=device, dtype=dtype)
+ inpt = _pad_rb(inpt, model.image_encoder.img_size)
+ keypoints = torch.randint(0, min(inpt.shape[-2:]), (batch_size, N, 2), device=device).to(dtype=dtype)
+ labels = torch.randint(0, 1, (batch_size, N), device=device).to(dtype=dtype)
+
+ out = model(inpt, [{'points': (keypoints, labels)}], multimask_output)
+
+ C = 3 if multimask_output else 1
+ assert len(out) == inpt.size(0)
+ assert out[0].logits.shape == (batch_size, C, 256, 256)
+
+ def test_exception(self):
+ model = Sam.from_config(SamConfig('vit_b'))
+
+ with pytest.raises(TypeError) as errinfo:
+ inpt = torch.rand(3, 1, 2)
+ model(inpt, [], False)
+ assert 'shape must be [[\'B\', \'3\', \'H\', \'W\']]. Got torch.Size([3, 1, 2])' in str(errinfo)
+
+ with pytest.raises(Exception) as errinfo:
+ inpt = torch.rand(2, 3, 1, 2)
+ model(inpt, [{}], False)
+ assert 'The number of images (`B`) should match with the length of prompts!' in str(errinfo)
+
+ @pytest.mark.parametrize('model_type', ['vit_b', 'vit_l', 'vit_h'])
+ def test_config(self, device, model_type):
+ model = Sam.from_config(SamConfig(model_type))
+ model = model.to(device=device)
+
+ assert isinstance(model, Sam)
+ assert next(model.parameters()).device == device
+
+ @pytest.mark.skip(reason='Unsupport at moment -- the code is not tested for trainning and had `torch.no_grad`')
+ def test_gradcheck(self, device):
+ ...
+
+ @pytest.mark.skip(reason='Unecessary test')
+ def test_module(self):
+ ...
+
+ @pytest.mark.skip(reason='Needs to be reviewed.')
+ def test_dynamo(self, device, torch_optimizer):
+ dtype = torch.float32
+ img = torch.rand(1, 3, 128, 75, device=device, dtype=dtype)
+
+ op = Sam.from_config(SamConfig('vit_b'))
+ op = op.to(device=device, dtype=dtype)
+
+ op_optimized = torch_optimizer(op)
+
+ img = _pad_rb(img, op.image_encoder.img_size)
+
+ expected = op(img, [{}], False)
+ actual = op_optimized(img, [{}], False)
+
+ self.assert_close(expected[0].logits, actual[0].logits)
+ self.assert_close(expected[0].scores, actual[0].scores)
diff --git a/test/test_contrib.py b/test/contrib/test_contrib.py
similarity index 100%
rename from test/test_contrib.py
rename to test/contrib/test_contrib.py
diff --git a/test/contrib/test_prompter.py b/test/contrib/test_prompter.py
new file mode 100644
index 000000000..02206f304
--- /dev/null
+++ b/test/contrib/test_prompter.py
@@ -0,0 +1,106 @@
+import sys
+
+import pytest
+import torch
+
+from kornia.contrib.image_prompter import ImagePrompter
+from kornia.contrib.models.sam import SamConfig
+from kornia.testing import BaseTester
+
+
+class TestImagePrompter(BaseTester):
+ def test_smoke(self, device, dtype):
+ inpt = torch.rand(3, 77, 128, device=device, dtype=dtype)
+ prompter = ImagePrompter(SamConfig('vit_b'), device, dtype)
+
+ prompter.set_image(inpt)
+ assert prompter.is_image_set
+
+ prompter.reset_image()
+ assert not prompter.is_image_set
+
+ @pytest.mark.parametrize('batch_size', [1, 4])
+ @pytest.mark.parametrize('N', [2, 5])
+ @pytest.mark.parametrize('multimask_output', [True, False])
+ def test_cardinality(self, device, batch_size, N, multimask_output):
+ # SAM: don't supports float64
+ dtype = torch.float32
+ inpt = torch.rand(3, 77, 128, device=device, dtype=dtype)
+ prompter = ImagePrompter(SamConfig('vit_b'), device, dtype)
+
+ keypoints = torch.randint(0, min(inpt.shape[-2:]), (batch_size, N, 2), device=device).to(dtype=dtype)
+ labels = torch.randint(0, 1, (batch_size, N), device=device).to(dtype=dtype)
+
+ prompter.set_image(inpt)
+
+ out = prompter.predict((keypoints, labels), multimask_output=multimask_output)
+
+ C = 3 if multimask_output else 1
+ assert out.logits.shape == (1, C, 256, 256)
+ assert out.scores.shape == (1, C)
+
+ def test_exception(self):
+ prompter = ImagePrompter(SamConfig('vit_b'))
+
+ inpt = torch.rand(1, 3, 1, 2)
+
+ # Wrong shape for the image
+ with pytest.raises(TypeError) as errinfo:
+ prompter.set_image(inpt, [], False)
+ assert 'shape must be [[\'3\', \'H\', \'W\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+
+ # predict without set an image
+ with pytest.raises(Exception) as errinfo:
+ prompter.predict()
+ assert 'An image must be set with `self.set_image(...)`' in str(errinfo)
+
+ # Valid masks
+ with pytest.raises(TypeError) as errinfo:
+ prompter._valid_masks(inpt)
+ assert 'shape must be [[\'K\', \'1\', \'256\', \'256\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+
+ # Valid boxes
+ with pytest.raises(TypeError) as errinfo:
+ prompter._valid_boxes(inpt)
+ assert 'shape must be [[\'K\', \'4\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+
+ # Valid keypoints
+ with pytest.raises(TypeError) as errinfo:
+ prompter._valid_keypoints(inpt, None)
+ assert 'shape must be [[\'K\', \'N\', \'2\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ prompter._valid_keypoints(torch.rand(1, 1, 2), inpt)
+ assert 'shape must be [[\'K\', \'N\']]. Got torch.Size([1, 3, 1, 2])' in str(errinfo)
+
+ with pytest.raises(Exception) as errinfo:
+ prompter._valid_keypoints(torch.rand(1, 1, 2), torch.rand(2, 1))
+ assert 'The keypoints and labels should have the same batch size' in str(errinfo)
+
+ @pytest.mark.skip(reason='Unecessary test')
+ def test_gradcheck(self, device):
+ ...
+
+ @pytest.mark.skip(reason='Unecessary test')
+ def test_module(self):
+ ...
+
+ def test_dynamo(self, device):
+ if not (hasattr(torch, 'compile') and sys.platform == "linux"):
+ pytest.skip(f"skipped because {torch.__version__} not have `compile` available! Failed to setup dynamo.")
+
+ dtype = torch.float32
+ img = torch.rand(3, 128, 75, device=device, dtype=dtype)
+
+ prompter = ImagePrompter(SamConfig('vit_b'), device, dtype)
+ prompter.set_image(img)
+
+ expected = prompter.predict(img)
+ prompter.reset_image()
+
+ prompter.compile()
+ prompter.set_image(img)
+ actual = prompter.predict(img)
+
+ self.assert_close(expected.logits, actual.logits)
+ self.assert_close(expected.scores, actual.scores)