Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib)!: VisualPrompter prompts, SAM's resize filter, every dtype, single image (#6040)

Dmytro Mishkin328c34da12e9
diff --git a/changelog.d/6040.breaking.md b/changelog.d/6040.breaking.md
new file mode 100644
index 000000000..5b12bd34e
--- /dev/null
+++ b/changelog.d/6040.breaking.md
@@ -0,0 +1 @@
+`VisualPrompter.predict(keypoints=...)` without `keypoints_labels` raises; the keypoints were ignored and the prediction was the one without prompts. `VisualPrompter.set_image` takes one image, `(3, H, W)` or `(1, 3, H, W)`, and raises for a batch: it accepted `(B, 3, H, W)` with B > 1, after which `predict()` without prompts returned one prediction per image and `predict` with keypoint or `Boxes` prompts raised. Use `Sam.forward` to segment a batch of images with per-image prompts.
diff --git a/changelog.d/6040.fixed.md b/changelog.d/6040.fixed.md
new file mode 100644
index 000000000..0a9b5ff4a
--- /dev/null
+++ b/changelog.d/6040.fixed.md
@@ -0,0 +1 @@
+`VisualPrompter.predict(boxes=...)` uses a box prompt given as a tensor; it was dropped, and the prediction was the one without prompts. A `(1, K, 4)` box prompt is read as the K boxes of the image; for K > 1 it raised a tensor size mismatch, and box prompts for more than one image now raise a clear error instead of a batch size mismatch. `VisualPrompter` resizes the image as SAM's reference does, with `torch.nn.functional.interpolate(image, size, mode="bilinear", align_corners=False, antialias=True)`, and keypoint prompts follow the same half-pixel map: it resized with `align_corners=True` while the masks are resized back with `align_corners=False`, which shifted the masks by up to 0.48 original pixels, and it did not antialias when it downscaled. On a 1380 x 2076 image, the mask IoU against SAM's own pipeline goes from 0.957, 0.966 and 0.943 to 0.969, 0.969 and 0.968. Box prompts are mapped as SAM's `apply_boxes` maps them: kornia's `xyxy` corners are pixel edges and scale as `x * s`, so the box `(0, 0, W, H)` covers the whole resized image; they went through the `Boxes` vertex at `x2 - 1` and the corner-aligned map, which put the box `(10, 20, 60, 50)` of a 77 x 128 image at `(80.55, 161.84, 476.25, 397.51)` instead of `(80, 160, 480, 400)`. `VisualPrompter.predict` and `Sam.forward` run in float16, bfloat16 and float64, with or without prompts: the SAM prompt encoder built its positional encoding in float32, and they raised `RuntimeError: expected m1 and m2 to have the same dtype`; it now computes the encoding in float32 (float64 for a float64 model), with autocast disabled, and casts it to the dtype of the model. Keypoint and box prompts are mapped to the resized image in float32 (float64 for a float64 model) and handed to the prompt encoder in that dtype, which also shifts them to pixel centres in that dtype. `kornia.models.common.LayerNorm2d` overflowed in float16 once a value was more than 255.9 from its channel mean, so pretrained MobileSAM gave empty masks in float16; float16 and bfloat16 inputs are now normalised in float32. `Sam.from_config` builds a custom ViT image encoder from `SamConfig(encoder_embed_dim=..., encoder_depth=..., encoder_num_heads=..., encoder_global_attn_indexes=...)` with `encoder_global_attn_indexes` a tuple, a list or an int; it raised `NotImplementedError` for a tuple or a list and `TypeError` for an int. A custom encoder config with `pretrained=True` and no `model_type` raises a `BaseError` saying that the released weights need a `model_type`; it raised `KeyError: None`.
diff --git a/docs/source/models/segment_anything.rst b/docs/source/models/segment_anything.rst
index c9295bb98..7b906745a 100644
--- a/docs/source/models/segment_anything.rst
+++ b/docs/source/models/segment_anything.rst
@@ -72,22 +72,22 @@ About the :code:`VisualPrompter`:
#. From a :class:`~kornia.models.sam.SamConfig` it loads the desired model with the desired checkpoint, which then receives
the query prompts. For now only the Segment Anything family is supported, with *SAM ViT-H* as the default option.
-#. Based on the model, the :code:`VisualPrompter` applies the necessary transformations to the image and prompts before
- passing them to the model. These transformations are implemented with our augmentation API, using
- :class:`kornia.augmentation.AugmentationSequential` to handle the different data formats (keypoints, boxes, masks, image).
+#. Based on the model, the :code:`VisualPrompter` resizes the image the way SAM's reference does, and maps the keypoint
+ and box prompts to the resized image with the same per-axis scales before passing them to the model. The formulas are
+ in the :class:`~kornia.contrib.visual_prompter.VisualPrompter` docstring.
#. When you call :code:`prompter.set_image(...)`, the prompter preprocesses the image, passes it to the encoder,
and caches the embeddings for later queries. Note that the image should be scaled to the range [0, 1].
* The preprocessing steps are: 1) resize the image so that its longer side matches the :code:`image_encoder` input size;
- 2) cache this transformation so it can be applied to the prompts; 3) normalize the image with the given mean and
+ 2) record the scales of this resize so they can be applied to the prompts; 3) normalize the image with the given mean and
standard deviation, or with the SAM dataset statistics; 4) pad the bottom and right so the image has the resolution the
encoder expects: :math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`.
* The best input image will always have shape
:math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`.
-#. When you call :code:`prompter.predict(...)`, the prompter applies the cached transformation to the prompt coordinates
+#. When you call :code:`prompter.predict(...)`, the prompter applies the recorded scales to the prompt coordinates
and then queries the cached embeddings with them.
* If :code:`output_original_size=True`, the result structure upsamples the logits from their native resolution to the
@@ -265,13 +265,12 @@ This is a simple example of how to use the loaded SAM model directly. We recomme
.. code-block:: python
import torch
- from torch.nn.functional import pad
+ import torch.nn.functional as F
from kornia.models.sam import Sam, SamConfig
from kornia.models.structures import SegmentationResults
from kornia.io import load_image, ImageLoadType
from kornia.core.utils import get_cuda_or_mps_device_if_available
- from kornia.geometry import resize
from kornia.enhance import normalize
model_type = 'vit_b' # or the number `2`, or the enum `SamModelType.vit_b`
@@ -287,12 +286,22 @@ This is a simple example of how to use the loaded SAM model directly. We recomme
# Transform the image (CxHxW) into a batched input (BxCxHxW)
image = image[None, ...]
- # Resize the image to have a maximum size of 1024 on its largest side
- data = resize(image, 1024, side='long')
- h, w = data.shape[-2:]
+ # Resize the image so that its longest side is 1024, as SAM's reference does (bilinear, half-pixel, antialiased).
+ # On MPS with torch older than 2.7, which has no antialiased bilinear kernel, resize on the CPU and move back.
+ H, W = image.shape[-2:]
+ h, w = int(H * 1024 / max(H, W)), int(W * 1024 / max(H, W))
+ data = F.interpolate(image, size=(h, w), mode='bilinear', align_corners=False, antialias=True)
- # Embed prompts -- ATTENTION: prompt coordinates must match the image after the resize
- sparse_embeddings, dense_embeddings = sam_model.prompt_encoder(points=None, boxes=None, masks=None)
+ # Map the prompts to the resized image with the same per-axis scales (see the VisualPrompter docstring):
+ # a keypoint marks a pixel centre, (x + 0.5) * s - 0.5; a box marks pixel edges (xyxy), x * s.
+ scale = torch.tensor([w / W, h / H], device=device)
+ keypoints = torch.tensor([[[500.0, 375.0]]], device=device) # (K, N, 2), in the original image
+ labels = torch.tensor([[1.0]], device=device) # (K, N): 1 foreground, 0 background
+ points = ((keypoints + 0.5) * scale - 0.5, labels)
+ boxes = (torch.tensor([[100.0, 100.0, 700.0, 600.0]], device=device).reshape(-1, 2, 2) * scale).reshape(-1, 4)
+
+ # Embed prompts
+ sparse_embeddings, dense_embeddings = sam_model.prompt_encoder(points=points, boxes=boxes, masks=None)
# SAM dataset statistics used to normalize the input, in the [0, 1] range
pixel_mean = torch.tensor([123.675, 116.28, 103.53], device=device) / 255.0
@@ -302,7 +311,7 @@ This is a simple example of how to use the loaded SAM model directly. We recomme
data = normalize(data, pixel_mean, pixel_std)
padh = sam_model.image_encoder.img_size - h
padw = sam_model.image_encoder.img_size - w
- data = pad(data, (0, padw, 0, padh))
+ data = F.pad(data, (0, padw, 0, padh))
#--------------------------------------------------------------------
# Option A: Manually calling each API
@@ -320,13 +329,13 @@ This is a simple example of how to use the loaded SAM model directly. We recomme
#--------------------------------------------------------------------
# Option B: Calling the model itself
#--------------------------------------------------------------------
- prediction = sam_model(data, [{}], multimask_output=True)[0] # one SegmentationResults per image
+ prediction = sam_model(data, [{"points": points, "boxes": boxes}], multimask_output=True)[0] # one per image
#--------------------------------------------------------------------
# Post processing
#--------------------------------------------------------------------
# Upscale the masks to the original image resolution
- input_size = (data.shape[-2], data.shape[-1])
+ input_size = (h, w) # the resized image, before the padding
original_size = (image.shape[-2], image.shape[-1])
image_size_encoder = (sam_model.image_encoder.img_size, sam_model.image_encoder.img_size)
prediction.original_res_logits(input_size, original_size, image_size_encoder)
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 1dd36f11d..0188c84a5 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -22,9 +22,10 @@ from typing import Any, Optional
import torch
import torch.nn.functional as F
-from kornia.augmentation import LongestMaxSize
+from kornia.augmentation import Resize
from kornia.augmentation.container.augment import AugmentationSequential
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.exceptions import BaseError
from kornia.enhance import normalize as kornia_normalize
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -32,16 +33,68 @@ from kornia.models.sam import Sam, SamConfig
from kornia.models.structures import Prompts, SegmentationResults
+def _resize_like_sam(image: torch.Tensor, size: tuple[int, int]) -> torch.Tensor:
+ """Resize as SAM's reference does: bilinear on the half-pixel grid, with torch's antialiasing.
+
+ This is ``ResizeLongestSide.apply_image_torch`` of ``segment-anything@3518c86``. It runs in at least float32, as
+ torch has no half-precision antialiased kernel on the CPU, and the result is cast back to the dtype of ``image``.
+ """
+ x = image.to(torch.promote_types(image.dtype, torch.float32))
+ try:
+ out = F.interpolate(x, size=size, mode="bilinear", align_corners=False, antialias=True)
+ except NotImplementedError:
+ if x.device.type != "mps":
+ raise
+ # torch 2.5.1 has no MPS kernel for the antialiased bilinear resize (``_upsample_bilinear2d_aa``).
+ out = F.interpolate(x.cpu(), size=size, mode="bilinear", align_corners=False, antialias=True).to(x.device)
+ return out.to(image.dtype)
+
+
class VisualPrompter:
- r"""Allow the user to run multiple query with multiple prompts for a model.
+ r"""Allow the user to run multiple queries with multiple prompts on one image.
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 F.normalize the image and F.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.
+ The prompter holds one image at a time: :meth:`set_image` takes a :math:`(3, H, W)` or :math:`(1, 3, H, W)` image,
+ and :meth:`predict` then answers prompts on it. To segment a batch of images, each with its own prompts, use
+ :meth:`kornia.models.sam.Sam.forward`.
+
+ The image is resized so that its long side equals ``image_encoder.img_size``. The output size :math:`(h, w)` comes
+ from ``transforms``, an :class:`~kornia.augmentation.AugmentationSequential` that must hold exactly one stage,
+ ``kornia.augmentation.Resize(img_size, side="long", align_corners=False, antialias=True)``. The image itself is
+ resized as SAM's reference resizes it (``ResizeLongestSide.apply_image_torch``), with
+ ``torch.nn.functional.interpolate(image, size, mode="bilinear", align_corners=False, antialias=True)``, computed in
+ float32 (float64 for a float64 image) and cast back. The image is then passed to the method `preprocess_image`,
+ which normalizes it and pads it to the size the SAM model takes,
+ :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.
+
+ The prompts follow the per-axis scales :math:`s_x = w / W` and :math:`s_y = h / H` of an :math:`H \times W` image,
+ computed in float32 (float64 for a float64 model), and come out in that dtype. A keypoint marks a pixel centre and
+ follows the half-pixel map :math:`x \mapsto (x + 0.5)\,s_x - 0.5` (likewise for :math:`y`), the map this resize
+ samples on. A box marks pixel edges, kornia's ``xyxy`` convention (``width = x2 - x1``), and both its corners follow
+ :math:`x \mapsto x\,s_x`, as in the reference's ``apply_boxes``: at :math:`s = 8` the box (10, 20, 60, 50) goes to
+ (80, 160, 480, 400), and :math:`(0, 0, W, H)` to the whole resized image :math:`(0, 0, w, h)`.
+
+ The image does not go through kornia's own antialiased :func:`~kornia.geometry.transform.resize`, which blurs with a
+ Gaussian of standard deviation :math:`(f - 1) / 2` before downscaling by :math:`f`, a weaker low-pass than the
+ antialiased bilinear filter of SAM's preprocessing. On a 1380 x 2076 image, against a transcription of Meta's
+ ``SamPredictor`` driving the same MobileSAM weights, the three masks of a point prompt reach IoU 0.962, 0.967 and
+ 0.956 with kornia's filter and 0.969, 0.969 and 0.968 with SAM's.
+
+ Two details depart on purpose from Meta's ``SamPredictor`` (``segment-anything@3518c86``):
+
+ - The resized short side is truncated, where the reference rounds it (a 1380 x 2076 image becomes 680 x 1024
+ here and 681 x 1024 there). Truncation is the rule of :class:`kornia.augmentation.Resize`, and the masks are
+ resized back through the same recorded input size.
+ - Keypoints follow the half-pixel map :math:`x \mapsto (x + 0.5)\,s - 0.5`, kornia's pixel-centre convention and
+ the map the image resize samples on, where the reference's ``apply_coords`` uses :math:`x \mapsto x\,s` for
+ points too. With the scale :math:`s = 8`, the keypoint (40, 30) goes to (323.5, 243.5) here and to (320, 240) in
+ the reference.
+
+ The held model follows the mode rule of :ref:`pretrained-models-conventions`: a config that loads weights gives a
+ model in evaluation mode, and a randomly initialised one stays in training mode, where MobileSAM's BatchNorm
+ normalises with the statistics of the batch. Call ``prompter.model.eval()`` before inference on random weights.
Args:
config: A model config to generate the model. Now just the SAM model is supported.
@@ -54,13 +107,9 @@ class VisualPrompter:
>>> prompter = VisualPrompter(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'
+ >>> # The K box prompts of the image, as a (1, K, 4) xyxy tensor; here K = 1.
+ >>> boxes = Boxes.from_tensor(
+ ... torch.tensor([[[0.0, 0.0, 10.0, 10.0]]], device=prompter.device, dtype=torch.float32), mode='xyxy'
... )
>>> prediction = prompter.predict(boxes=boxes)
>>> prediction.logits.shape
@@ -80,7 +129,7 @@ class VisualPrompter:
if isinstance(config, SamConfig):
self.model = Sam.from_config(config)
- transforms = (LongestMaxSize(self.model.image_encoder.img_size, p=1.0),)
+ transforms = (Resize(self.model.image_encoder.img_size, side="long", align_corners=False, antialias=True),)
self.pixel_mean: Optional[torch.Tensor] = (
torch.tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
)
@@ -98,6 +147,7 @@ class VisualPrompter:
self._original_image_size: tuple[int, int] | None = None
self._input_image_size: tuple[int, int] | None = None
self._input_encoder_size: tuple[int, int] | None = None
+ self._prompt_scale: Optional[torch.Tensor] = None
self.reset_image()
def preprocess_image(
@@ -138,28 +188,62 @@ class VisualPrompter:
) -> 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.
+ Resize the image to the size given by ``transforms``, with SAM's filter (see the class docstring), and prepare
+ it with the preprocess method.
Args:
- image: RGB image. Normally images with range of [0-1], the model preprocess F.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)`.
+ image: One RGB image, shape :math:`(3, H, W)` or :math:`(1, 3, H, W)`, in the dtype of the model. Normally
+ images with range of [0-1], the model preprocess F.normalize the pixel values with the mean and std
+ defined in its initialization. A batch of more than one image raises; use
+ :meth:`kornia.models.sam.Sam.forward` for batches.
mean: mean value of dataset for normalization.
std: standard deviation of dataset for normalization.
"""
+ KORNIA_CHECK(
+ image.is_floating_point(),
+ f"VisualPrompter takes a floating-point image with values in [0, 1]; got {image.dtype}.",
+ )
if image.ndim == 3:
KORNIA_CHECK_SHAPE(image, ["3", "H", "W"])
image = image.unsqueeze(0)
else:
KORNIA_CHECK_SHAPE(image, ["B", "3", "H", "W"])
+ KORNIA_CHECK(
+ image.shape[0] == 1,
+ f"VisualPrompter takes one image, (3, H, W) or (1, 3, H, W); got a batch of {image.shape[0]}. "
+ "Use `Sam.forward` to segment a batch of images with per-image prompts.",
+ )
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
+ # The Resize augmentation gives the output size; the image itself is resized with the filter of SAM's
+ # reference, and the prompts with the per-axis scales (see the class docstring).
+ stages = list(self.transforms.children())
+ KORNIA_CHECK(
+ len(stages) == 1 and isinstance(stages[0], Resize),
+ "VisualPrompter.transforms must hold exactly one stage, kornia.augmentation.Resize, which gives the size "
+ f"of the resized image; got {[type(stage).__name__ for stage in stages]}.",
+ )
+ self._tfs_params = self.transforms.forward_parameters(image.shape)
+ resize_params = self._tfs_params[0].data
+ if not isinstance(resize_params, dict):
+ raise TypeError(f"Expected the parameters of the Resize augmentation. Got {type(resize_params)}.")
+ height, width = (int(side) for side in resize_params["output_size"][0])
+ encoder_size = self.model.image_encoder.img_size
+ KORNIA_CHECK(
+ max(height, width) <= encoder_size,
+ f"VisualPrompter.transforms resizes the image to {height} x {width}, larger than the image encoder's input "
+ f"size {encoder_size}: the padding to {encoder_size} would crop the image while the prompts are scaled "
+ "for all of it.",
+ )
+ prompt_dtype = torch.promote_types(self.model.prompt_encoder.point_embeddings[0].weight.dtype, torch.float32)
+ self._prompt_scale = torch.tensor(
+ [width / image.shape[-1], height / image.shape[-2]], device=image.device, dtype=prompt_dtype
+ )
+ image = _resize_like_sam(image, (height, width))
self._input_image_size = (image.shape[-2], image.shape[-1])
image = self.preprocess_image(image, mean, std)
@@ -180,34 +264,60 @@ class VisualPrompter:
return keypoints
- def _valid_boxes(self, boxes: Boxes | torch.Tensor) -> Boxes:
- """Validate the boxes shape and ensure to be a Boxes into xyxy mode."""
+ def _valid_boxes(self, boxes: Boxes | torch.Tensor) -> torch.Tensor:
+ """Validate the box prompts and return them as a ``(K, 4)`` xyxy tensor.
+
+ The boxes are the ``K`` box prompts of the one image set. A ``(K, 4)`` or ``(1, K, 4)`` xyxy tensor is taken
+ as given. A :class:`~kornia.geometry.boxes.Boxes` holding ``(K, 4, 2)`` or ``(1, K, 4, 2)`` vertices is read
+ through ``to_tensor(mode="xyxy")``.
+ """
if isinstance(boxes, torch.Tensor):
if boxes.ndim == 2:
KORNIA_CHECK_SHAPE(boxes.data, ["K", "4"])
else:
KORNIA_CHECK_SHAPE(boxes.data, ["B", "K", "4"])
+ # ``Boxes.from_tensor`` checks the values (finite, positive extents). Its vertices are not used: their
+ # round trip widens a sub-pixel box ([10, 20, 10.5, 20.5] comes back as [9.5, 19.5, 11, 21]) and, in
+ # bfloat16, rounds the -1 offset away ([256, 256, 258, 258] comes back as [256, 256, 256, 256]).
+ Boxes.from_tensor(boxes, mode="xyxy")
+ images = boxes.shape[0] if boxes.ndim == 3 else 1
+ xyxy = boxes if boxes.is_floating_point() else boxes.to(torch.get_default_dtype())
+ else:
+ images = boxes.data.shape[0] if boxes.data.ndim == 4 else 1
+ exported = boxes.to_tensor(mode="xyxy")
+ if not isinstance(exported, torch.Tensor):
+ raise TypeError(f"Expected the boxes as a tensor. Got {type(exported)}.")
+ xyxy = exported
+
+ KORNIA_CHECK(
+ images == 1,
+ f"VisualPrompter takes the boxes of its one image, (K, 4) or (1, K, 4); got boxes for {images} images. "
+ "Use `Sam.forward` to prompt a batch of images.",
+ )
- boxes = Boxes.from_tensor(boxes, mode="xyxy")
-
- return boxes if boxes.mode == "xyxy" else Boxes.from_tensor(boxes.to_tensor(mode="xyxy"), mode="xyxy")
+ return xyxy.reshape(-1, 4)
def _valid_masks(self, masks: torch.Tensor) -> torch.Tensor:
"""Validate the input masks shape."""
KORNIA_CHECK_SHAPE(masks, ["K", "1", "256", "256"])
return masks
- def _transform_prompts(
- self, *prompts: torch.Tensor | Boxes | Keypoints, data_keys: Optional[list[str]] = None
- ) -> dict[str, torch.Tensor | Boxes | Keypoints]:
- transformed_prompts = self.transforms(*prompts, data_keys=data_keys, params=self._tfs_params)
- if data_keys is None:
- data_keys = []
+ def _scale(self, like: torch.Tensor) -> torch.Tensor:
+ """The per-axis scales ``(s_x, s_y)`` recorded by ``set_image``, on the device of ``like``."""
+ scale = self._prompt_scale
+ if scale is None:
+ raise BaseError("An image must be set with `self.set_image(...)` before its prompts can be mapped.")
+ return scale.to(like.device)
- # prevent unpacking torch.Tensor when creating the output dict (issue #2627)
- if not isinstance(transformed_prompts, (list, tuple)):
- transformed_prompts = [transformed_prompts]
- return {key: transformed_prompts[idx] for idx, key in enumerate(data_keys)}
+ def _map_keypoints(self, keypoints: torch.Tensor) -> torch.Tensor:
+ """Map pixel-centre keypoints ``(..., 2)`` of the original image with the half-pixel map, in float32 or more."""
+ scale = self._scale(keypoints)
+ return (keypoints.to(scale.dtype) + 0.5) * scale - 0.5
+
+ def _map_box_edges(self, boxes: torch.Tensor) -> torch.Tensor:
+ """Map xyxy boxes ``(K, 4)`` of the original image, whose corners are pixel edges, in float32 or wider."""
+ scale = self._scale(boxes)
+ return (boxes.to(scale.dtype).reshape(-1, 2, 2) * scale).reshape(-1, 4)
def preprocess_prompts(
self,
@@ -216,41 +326,34 @@ class VisualPrompter:
boxes: Optional[Boxes | torch.Tensor] = None,
masks: Optional[torch.Tensor] = None,
) -> Prompts:
- """Validate and preprocess the given prompts to be aligned with the input image."""
- data_keys = []
- to_transform: list[Keypoints | Boxes | torch.Tensor] = []
+ r"""Validate and preprocess the given prompts to be aligned with the input image.
+ Keypoints follow the half-pixel map :math:`(x + 0.5)\,s - 0.5` of a pixel centre, and both corners of each
+ xyxy box the edge map :math:`x\,s`, as the reference's ``apply_boxes`` does, with the per-axis scales recorded
+ by :meth:`set_image`. They are computed, and returned, in float32 (float64 for a float64 model). A tensor box
+ is taken as given; a :class:`~kornia.geometry.boxes.Boxes` is read through ``to_tensor(mode="xyxy")``.
+ """
+ points: Optional[tuple[torch.Tensor, torch.Tensor]] = None
if isinstance(keypoints, (Keypoints, torch.Tensor)) and isinstance(keypoints_labels, torch.Tensor):
keypoints = self._valid_keypoints(keypoints, keypoints_labels)
- data_keys.append("keypoints")
- to_transform.append(keypoints)
+ keypoints_tensor = keypoints.to_tensor()
+ if not isinstance(keypoints_tensor, torch.Tensor):
+ raise TypeError(f"Expected the keypoints as a tensor. Got {type(keypoints_tensor)}.")
+ points = (self._map_keypoints(keypoints_tensor), keypoints_labels)
+ elif keypoints is not None:
+ KORNIA_CHECK(
+ False,
+ "keypoints_labels must be given with keypoints: a (K, N) tensor, 1 for a foreground point and 0 for "
+ "a background point.",
+ )
+ bbox: Optional[torch.Tensor] = None
if isinstance(boxes, (Boxes, torch.Tensor)):
- self._valid_boxes(boxes)
- data_keys.append("bbox_xyxy")
- to_transform.append(boxes)
+ bbox = self._map_box_edges(self._valid_boxes(boxes))
if isinstance(masks, torch.Tensor):
self._valid_masks(masks)
- # No prompt at all is a valid query (SAM then predicts from the image embedding alone); the
- # augmentation container cannot be called with nothing to transform.
- data = self._transform_prompts(*to_transform, data_keys=data_keys) if to_transform else {}
-
- 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, 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()
@@ -270,8 +373,11 @@ class VisualPrompter:
`N` is the number of points and `K` the number of prompts.
keypoints_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 torch.Tensor, should be in a xyxy mode. Shape :math:`(K, 4)`
+ prompts. Required with `keypoints`.
+ boxes: Box prompts to the model, one per prompt: a torch.Tensor in xyxy mode, shape :math:`(K, 4)` or
+ :math:`(1, K, 4)`, whose corners are taken as given, or a :class:`~kornia.geometry.boxes.Boxes` of
+ shape :math:`(K, 4, 2)` or :math:`(1, K, 4, 2)`, read through ``to_tensor(mode="xyxy")``. `K` is
+ the number of prompts.
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
@@ -324,12 +430,13 @@ class VisualPrompter:
clean state.
In practice, this resets:
- - transformed-image parameters,
+ - transformed-image parameters and the prompt scales,
- original/input/encoder spatial sizes,
- cached image embeddings,
- ``is_image_set`` status flag.
"""
self._tfs_params = None
+ self._prompt_scale = None
self._original_image_size = None
self._input_image_size = None
self._input_encoder_size = None
diff --git a/kornia/models/common.py b/kornia/models/common.py
index 38dd13cf4..11a36a9ed 100644
--- a/kornia/models/common.py
+++ b/kornia/models/common.py
@@ -149,7 +149,13 @@ class DropPath(nn.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
class LayerNorm2d(nn.Module):
- """Apply Layer Normalization over a 4D input tensor (NCHW)."""
+ """Apply Layer Normalization over a 4D input tensor (NCHW).
+
+ A float16 or bfloat16 input is normalised in float32, and the result is cast to the promoted dtype of the input and
+ the weight (a float16 input with float32 weights gives float32). In float16, the squared deviations overflow once a
+ value is more than 255.9 from its channel mean, and the variance becomes ``inf``, which leaves only the bias.
+ MobileSAM's neck reaches about 560, and a float16 variance there gives empty masks.
+ """
def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
super().__init__()
@@ -169,10 +175,16 @@ class LayerNorm2d(nn.Module):
Tensor with the same shape as ``x`` after normalizing across the
channel dimension and applying learned affine parameters.
"""
+ if x.dtype in (torch.float16, torch.bfloat16):
+ out_dtype = torch.promote_types(x.dtype, self.weight.dtype)
+ return self._normalize(x.float(), self.weight.float(), self.bias.float()).to(out_dtype)
+ return self._normalize(x, self.weight, self.bias)
+
+ def _normalize(self, x: torch.Tensor, weight: torch.Tensor, bias: 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()
- return self.weight[:, None, None] * x + self.bias[:, None, None]
+ return weight[:, None, None] * x + bias[:, None, None]
def window_partition(x: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
diff --git a/kornia/models/sam/architecture/prompt_encoder.py b/kornia/models/sam/architecture/prompt_encoder.py
index 873445b66..21d5ca8dc 100644
--- a/kornia/models/sam/architecture/prompt_encoder.py
+++ b/kornia/models/sam/architecture/prompt_encoder.py
@@ -99,7 +99,8 @@ class PromptEncoder(nn.Module):
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 pixel
+ # Shift to center of pixel, in the encoding's (at least float32) dtype: in bfloat16 the shift is lost above 256.
+ points = points.to(self.pe_layer._compute_dtype()) + 0.5
if pad:
padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
@@ -114,7 +115,8 @@ class PromptEncoder(nn.Module):
def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
"""Embeds box prompts."""
- boxes = boxes + 0.5 # Shift to center of pixel
+ # Shift to center of pixel, in the encoding's (at least float32) dtype: in bfloat16 the shift is lost above 256.
+ boxes = boxes.to(self.pe_layer._compute_dtype()) + 0.5
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
@@ -163,7 +165,9 @@ class PromptEncoder(nn.Module):
"""
bs = self._get_batch_size(points, boxes, masks)
- sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
+ sparse_embeddings = torch.empty(
+ (bs, 0, self.embed_dim), device=self._get_device(), dtype=self.point_embeddings[0].weight.dtype
+ )
if points is not None:
coords, labels = points
point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
@@ -183,7 +187,14 @@ class PromptEncoder(nn.Module):
class PositionEmbeddingRandom(nn.Module):
- """Positional encoding using random spatial frequencies."""
+ """Positional encoding using random spatial frequencies.
+
+ The encoding is computed in at least float32 (float64 for a float64 matrix), with autocast disabled, and returned
+ in the dtype of the Gaussian matrix. Computed in the half dtypes throughout, the encoding of a 64 x 64 grid is off
+ by 0.10-0.14 in bfloat16 and 0.013-0.015 in float16 against the float32 encoding of the same frequencies, measured
+ with MobileSAM's released frequencies and four draws of SAM's 128 frequencies from N(0, 1), whose phases reach
+ 24-29 radians. Computed in float32, it differs only by the rounding of its output.
+ """
def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
super().__init__()
@@ -191,21 +202,28 @@ class PositionEmbeddingRandom(nn.Module):
scale = 1.0
self.register_buffer("positional_encoding_gaussian_matrix", scale * torch.randn((2, num_pos_feats)))
+ def _compute_dtype(self) -> torch.dtype:
+ return torch.promote_types(self.positional_encoding_gaussian_matrix.dtype, torch.float32)
+
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 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 torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
+ matrix = self.positional_encoding_gaussian_matrix
+ # Autocast would run the matmul in its half dtype whatever the operands are.
+ with torch.autocast(device_type=coords.device.type, enabled=False):
+ coords = 2 * coords.to(self._compute_dtype()) - 1
+ coords = coords @ matrix.to(self._compute_dtype())
+ coords = 2 * pi * coords
+ # outputs d_1 x ... x d_n x C shape
+ encoding = torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
+ return encoding.to(matrix.dtype)
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
device = _dev if isinstance(_dev, torch.device) else None
- grid = torch.ones((h, w), device=device, dtype=torch.float32)
+ grid = torch.ones((h, w), device=device, dtype=self._compute_dtype())
y_embed = grid.cumsum(dim=0) - 0.5
x_embed = grid.cumsum(dim=1) - 0.5
y_embed = y_embed / h
@@ -216,7 +234,7 @@ class PositionEmbeddingRandom(nn.Module):
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 = coords_input.to(dtype=self._compute_dtype(), copy=True)
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
+ return self._pe_encoding(coords) # B x N x C
diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.py
index eafa4112b..ffddbc30f 100644
--- a/kornia/models/sam/model.py
+++ b/kornia/models/sam/model.py
@@ -75,16 +75,22 @@ class SamConfig:
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`
- - 3, 'mobile_sam', or :func:`kornia.contrib.sam.SamModelType.mobile_sam`
+ - 0, 'vit_h' or :attr:`kornia.models.sam.SamModelType.vit_h`
+ - 1, 'vit_l' or :attr:`kornia.models.sam.SamModelType.vit_l`
+ - 2, 'vit_b' or :attr:`kornia.models.sam.SamModelType.vit_b`
+ - 3, 'mobile_sam', or :attr:`kornia.models.sam.SamModelType.mobile_sam`
+ With ``None``, the image encoder is a ViT built from the four ``encoder_*`` fields below, which are
+ ignored when ``model_type`` is set.
checkpoint: URL or a path for a file with the weights of the model
+ pretrained: load the released weights of ``model_type``, which must then be set. A ``checkpoint`` takes
+ precedence, with a warning. With ``False`` (the default) and no ``checkpoint``, the weights are randomly
+ initialised.
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.
+ encoder_global_attn_indexes: Encoder indexes for blocks using global attention: a tuple or a list of
+ indexes, or one index as an ``int``.
"""
@@ -95,7 +101,7 @@ class SamConfig:
encoder_embed_dim: Optional[int] = None
encoder_depth: Optional[int] = None
encoder_num_heads: Optional[int] = None
- encoder_global_attn_indexes: Optional[tuple[int, ...]] = None
+ encoder_global_attn_indexes: Optional[int | tuple[int, ...] | list[int]] = None
class Sam(ONNXExportMixin, ModelBase[SamConfig]):
@@ -125,7 +131,9 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
@staticmethod
def from_name(name: str) -> Sam:
- """Build/load the SAM model based on it's name.
+ """Build a randomly initialised SAM of the given type.
+
+ Use ``Sam.from_config(SamConfig(name, pretrained=True))`` for the released weights.
Args:
name: The name of the SAM model. Valid names are:
@@ -223,13 +231,16 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
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)
+ and isinstance(config.encoder_global_attn_indexes, (int, tuple, list))
):
+ global_attn_indexes = config.encoder_global_attn_indexes
model = _build_sam(
encoder_embed_dim=config.encoder_embed_dim,
encoder_depth=config.encoder_depth,
encoder_num_heads=config.encoder_num_heads,
- encoder_global_attn_indexes=config.encoder_global_attn_indexes,
+ encoder_global_attn_indexes=(
+ (global_attn_indexes,) if isinstance(global_attn_indexes, int) else tuple(global_attn_indexes)
+ ),
)
else:
@@ -238,6 +249,11 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
checkpoint = config.checkpoint
if config.pretrained:
if checkpoint is None:
+ KORNIA_CHECK(
+ isinstance(model_type, SamModelType),
+ "SamConfig(pretrained=True) needs a model_type: the released weights exist only for 'vit_h', "
+ "'vit_l', 'vit_b' and 'mobile_sam'. Give a checkpoint to load weights into a custom encoder.",
+ )
checkpoint = urls[model_type]
else:
warnings.warn("checkpoint is not None. pretrained=True is ignored", stacklevel=1)
@@ -343,7 +359,7 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
- 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.
+ - scores: The predicted IoU of each mask, :math:`(K, C)`.
"""
KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])
diff --git a/kornia/models/structures.py b/kornia/models/structures.py
index 0c2d2744b..5f642168f 100644
--- a/kornia/models/structures.py
+++ b/kornia/models/structures.py
@@ -31,8 +31,10 @@ 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, C)`
+ logits: Results logits with shape :math:`(K, C, H, W)` for one image: :math:`K` is the number of its prompts
+ (the leading size of its point, box or mask prompts; 1 when it has none), :math:`C` the number of masks
+ predicted per prompt (3 with ``multimask_output``, else 1), and :math:`H = W = 256` for SAM.
+ scores: The predicted IoU of each mask. Shape :math:`(K, C)`
mask_threshold: The threshold value to generate the `binary_masks` from the `logits`
"""
@@ -46,7 +48,7 @@ class SegmentationResults:
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.
+ Shape will be the same of logits :math:`(K, C, H, W)` where :math:`C` is the number masks predicted per prompt.
.. note:: If you run `original_res_logits`, this will generate the masks
based on the original resolution logits.
diff --git a/tests/contrib/test_visual_prompter.py b/tests/contrib/test_visual_prompter.py
index 2235a6fef..c2f329f4a 100644
--- a/tests/contrib/test_visual_prompter.py
+++ b/tests/contrib/test_visual_prompter.py
@@ -19,13 +19,71 @@ from types import SimpleNamespace
import pytest
import torch
+import torch.nn.functional as F
+from torch import nn
+import kornia.augmentation as K
+from kornia.augmentation.container.augment import AugmentationSequential
from kornia.contrib.visual_prompter import VisualPrompter
+from kornia.core.exceptions import BaseError
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
from kornia.models.sam import Sam, SamConfig
+from kornia.models.structures import SegmentationResults
from testing.base import BaseTester
+class _StubImageEncoder(nn.Module):
+ """Stand-in for SAM's image encoder: a fixed, seeded ``(B, 256, 64, 64)`` embedding.
+
+ It keeps ``img_size`` (read by ``VisualPrompter.preprocess_image``) and records its input, the resized and padded
+ image. A random MobileSAM encoder at 1024 x 1024 takes 0.7 s in float32 but 16-18 s in float16 or bfloat16 on CPU
+ with two threads, and what these tests check sits before and after it.
+ """
+
+ img_size = 1024
+
+ def __init__(self, device: torch.device, dtype: torch.dtype) -> None:
+ super().__init__()
+ generator = torch.Generator().manual_seed(0)
+ # SAM's 1024-pixel input over 16-pixel patches gives a 64 x 64 grid of 256-channel (``prompt_embed_dim``)
+ # embeddings.
+ self.embedding = torch.randn(1, 256, 64, 64, generator=generator).to(device=device, dtype=dtype)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ self.last_input = x
+ return self.embedding.expand(x.shape[0], -1, -1, -1)
+
+
+def _prompt_dtype(dtype: torch.dtype) -> torch.dtype:
+ """The dtype of mapped prompts: at least float32, whatever the model dtype."""
+ return torch.promote_types(dtype, torch.float32)
+
+
+def _skip_float64_on_mps(device: torch.device, dtype: torch.dtype) -> None:
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+
+
+def _prompter_with_stub(device: torch.device, dtype: torch.dtype) -> tuple[VisualPrompter, _StubImageEncoder]:
+ """Random-init MobileSAM prompter in evaluation mode, with the stub encoder and no image set."""
+ _skip_float64_on_mps(device, dtype)
+ prompter = VisualPrompter(SamConfig("mobile_sam"), device=device, dtype=dtype)
+ prompter.model.eval()
+ stub = _StubImageEncoder(device, dtype)
+ prompter.model.image_encoder = stub
+ return prompter, stub
+
+
+def _prompter_with_stub_encoder(device: torch.device, dtype: torch.dtype) -> VisualPrompter:
+ """Random-init MobileSAM prompter in evaluation mode, with the stub encoder and a seeded 77 x 128 image set."""
+ prompter, _ = _prompter_with_stub(device, dtype)
+ generator = torch.Generator().manual_seed(0)
+ prompter.set_image(torch.rand(3, 77, 128, generator=generator).to(device=device, dtype=dtype))
+ return prompter
+
+
class TestVisualPrompter(BaseTester):
def test_default_config(self, monkeypatch):
captured_configs = []
@@ -50,9 +108,7 @@ class TestVisualPrompter(BaseTester):
assert captured_configs[0].pretrained is True
def test_smoke(self, device, dtype):
- if dtype not in (torch.float32, torch.float16):
- pytest.skip("VisualPrompter (SAM) primarily supports float32 and float16")
-
+ _skip_float64_on_mps(device, dtype)
prompter = VisualPrompter(SamConfig("mobile_sam"), device=device, dtype=dtype)
assert prompter is not None
assert not prompter.is_image_set
@@ -60,30 +116,32 @@ class TestVisualPrompter(BaseTester):
@pytest.mark.slow
def test_batching_pipeline(self, device, dtype):
if dtype not in (torch.float32, torch.float16):
- pytest.skip("VisualPrompter (SAM) primarily supports float32 and float16")
+ pytest.skip("the real MobileSAM encoder runs here; test_predict_in_every_dtype covers the other dtypes")
prompter = VisualPrompter(SamConfig("mobile_sam"), device=device, dtype=dtype)
+ prompter.model.eval()
- batch_size = 2
- image = torch.rand(batch_size, 3, 256, 256).to(device=device, dtype=dtype)
+ # One image at a time: a batch of images goes through ``Sam.forward``.
+ with pytest.raises(BaseError, match=r"Sam\.forward"):
+ prompter.set_image(torch.rand(2, 3, 256, 256, device=device, dtype=dtype))
+ assert not prompter.is_image_set
- prompter.set_image(image)
+ prompter.set_image(torch.rand(1, 3, 256, 256, device=device, dtype=dtype))
assert prompter.is_image_set
- assert prompter.image_embeddings.shape[0] == batch_size
+ # SAM's 1024-pixel input over its 16-pixel patches gives a 64 x 64 grid of 256-channel embeddings.
+ assert prompter.image_embeddings.shape == (1, 256, 64, 64)
- boxes_tensor = torch.tensor(
- [[[10.0, 10.0, 50.0, 50.0]], [[20.0, 20.0, 80.0, 80.0]]],
- device=device,
- dtype=dtype,
- )
+ # The batch axis of the prompts is the prompt axis K: two box prompts for the one image.
+ boxes_tensor = torch.tensor([[[10.0, 10.0, 50.0, 50.0], [20.0, 20.0, 80.0, 80.0]]], device=device, dtype=dtype)
results = prompter.predict(boxes=boxes_tensor)
- assert results.logits.shape == (batch_size, 3, 256, 256)
+ assert results.logits.shape == (2, 3, 256, 256)
+ assert results.scores.shape == (2, 3)
@pytest.mark.slow
def test_predict_without_prompts(self, device, dtype):
if dtype not in (torch.float32, torch.float16):
- pytest.skip("VisualPrompter (SAM) primarily supports float32 and float16")
+ pytest.skip("the real MobileSAM encoder runs here; test_predict_in_every_dtype covers the other dtypes")
prompter = VisualPrompter(SamConfig("mobile_sam"), device=device, dtype=dtype)
prompter.set_image(torch.rand(3, 256, 256, device=device, dtype=dtype))
@@ -117,6 +175,241 @@ class TestVisualPrompter(BaseTester):
assert prompter.image_embeddings.shape == (1, 256, 64, 64)
assert prompter.image_embeddings.dtype == dtype
+ def test_tensor_box_reaches_the_model(self, device, dtype):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+ box = torch.tensor([[10.0, 20.0, 60.0, 50.0]], device=device, dtype=dtype)
+
+ from_tensor = prompter.preprocess_prompts(boxes=box).boxes
+ from_boxes = prompter.preprocess_prompts(boxes=Boxes.from_tensor(box[None], mode="xyxy")).boxes
+
+ assert from_tensor is not None
+ self.assert_close(from_tensor, from_boxes)
+ assert not torch.equal(prompter.predict(boxes=box).logits, prompter.predict().logits)
+
+ def test_keypoints_without_labels_raise(self, device, dtype):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+
+ keypoints = torch.tensor([[[40.0, 30.0]]], device=device, dtype=dtype)
+ for unlabelled in (keypoints, Keypoints.from_tensor(keypoints)):
+ with pytest.raises(BaseError, match="keypoints_labels"):
+ prompter.predict(keypoints=unlabelled)
+
+ def test_prompts_follow_the_half_pixel_resize(self, device, dtype):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+ # The long side 128 -> 1024 gives the scale s = 8 on both axes, and the short side 77 * 8 = 616.
+ assert prompter._input_image_size == (616, 1024)
+
+ keypoints = torch.tensor([[[40.0, 30.0]], [[0.0, 0.0]]], device=device, dtype=dtype)
+ labels = torch.ones(2, 1, device=device, dtype=dtype)
+ points = prompter.preprocess_prompts(keypoints, labels).keypoints
+
+ # Half-pixel map x' = (x + 0.5) * s - 0.5 (``Resize`` at ``align_corners=False``): (40, 30) ->
+ # (40.5 * 8 - 0.5, 30.5 * 8 - 0.5) = (323.5, 243.5); pixel 0's centre lands on the centre of output pixels
+ # 0..7, at 3.5. The corner-aligned map x * 1023 / 127, y * 615 / 76 gives (322.20, 242.76) and (0, 0).
+ expected = torch.tensor([[[323.5, 243.5]], [[3.5, 3.5]]], device=device, dtype=_prompt_dtype(dtype))
+ self.assert_close(points, expected)
+
+ def test_box_edges_scale_with_the_image(self, device, dtype):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+ # kornia's xyxy corners are pixel edges (width = x2 - x1); an edge maps to x * s, as both corners do in the
+ # reference's ``apply_boxes``. At s = 8: the whole 77 x 128 image -> the whole 616 x 1024 resized image, and
+ # (10, 20, 60, 50) -> (80, 160, 480, 400). The half-pixel map of a pixel centre would give (3.5, 3.5, 1027.5,
+ # 619.5) for the whole image, past its far edges.
+ cases = (
+ ([0.0, 0.0, 128.0, 77.0], [0.0, 0.0, 1024.0, 616.0]),
+ ([10.0, 20.0, 60.0, 50.0], [80.0, 160.0, 480.0, 400.0]),
+ )
+ for box, mapped in cases:
+ box = torch.tensor([box], device=device, dtype=dtype)
+ expected = torch.tensor([mapped], device=device, dtype=_prompt_dtype(dtype))
+ for boxes in (box, Boxes.from_tensor(box[None], mode="xyxy")):
+ self.assert_close(prompter.preprocess_prompts(boxes=boxes).boxes, expected)
+
+ # Bound of each case: at 77 x 128 the bilinear upscale reproduces a ramp exactly. At 1500 x 2000 the
+ # antialiasing filter of SAM's reference (torch's, the same as PIL's bilinear reduce) starts and ends its taps on
+ # whole source pixels, which moves a ramp in a sawtooth of up to 0.022 px, in float64 as well.
+ @pytest.mark.parametrize("height, width, bound", [(77, 128, 1e-3), (1500, 2000, 0.025)])
+ def test_resize_round_trip_is_aligned(self, device, dtype, height, width, bound):
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("a ramp of 2000 columns needs float32 or wider to resolve the bound")
+ prompter, stub = _prompter_with_stub(device, dtype)
+
+ # A horizontal ramp whose value is its own column index, centred on 0 to halve its float32 rounding, goes
+ # through set_image (without normalization) and back through the resize of ``SegmentationResults``.
+ ramp = (torch.arange(width, device=device, dtype=dtype) - width / 2).expand(3, height, width).contiguous()
+ prompter.set_image(ramp, torch.zeros(3, device=device, dtype=dtype), torch.ones(3, device=device, dtype=dtype))
+ back = SegmentationResults(stub.last_input[:, :1], torch.zeros(1, 1, device=device, dtype=dtype))
+ back = back.original_res_logits(
+ prompter._input_image_size, prompter._original_image_size, prompter._input_encoder_size
+ )
+
+ # The three outer columns on each side are left out: at 2000 -> 1024 the filter's taps are cut at the image
+ # border, which bends the ramp in column 0 (0.69 px), and the resize back spreads it to columns 1 and 2
+ # (0.15 and 0.04 px). A corner-aligned forward resize stretches the ramp about its centre, by up to 0.43 px at
+ # 77 x 128 and 0.48 px at 1500 x 2000, most at the borders.
+ row = height // 2
+ self.assert_close(back[0, 0, row, 3:-3], ramp[0, row, 3:-3], rtol=0.0, atol=bound)
+
+ def test_downscale_is_antialiased(self, device, dtype):
+ prompter, stub = _prompter_with_stub(device, dtype)
+ generator = torch.Generator().manual_seed(0)
+ image = torch.rand(3, 1500, 2000, generator=generator).to(device=device, dtype=dtype)
+ no_normalization = torch.zeros(3, device=device, dtype=dtype), torch.ones(3, device=device, dtype=dtype)
+
+ prompter.set_image(image, *no_normalization)
+
+ # The long side 2000 -> 1024 scales by 0.512, so the short side is 1500 * 0.512 = 768. SAM's reference,
+ # ``ResizeLongestSide.apply_image_torch`` (segment-anything@3518c86), resizes with this interpolate call. It
+ # runs here on the CPU (torch 2.5.1 has no MPS kernel for it) and in float32 (none for the half dtypes on CPU).
+ compute_dtype = torch.promote_types(dtype, torch.float32)
+ expected = F.interpolate(
+ image[None].cpu().to(compute_dtype), (768, 1024), mode="bilinear", align_corners=False, antialias=True
+ ).to(device=device, dtype=dtype)
+ assert prompter._input_image_size == (768, 1024)
+ self.assert_close(stub.last_input[..., :768, :1024], expected)
+
+ def test_predict_in_every_dtype(self, device, dtype):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+ keypoints = torch.tensor([[[40.0, 30.0]]], device=device, dtype=dtype)
+ labels = torch.ones(1, 1, device=device, dtype=dtype)
+ box = torch.tensor([[10.0, 20.0, 60.0, 50.0]], device=device, dtype=dtype)
+
+ for results in (prompter.predict(), prompter.predict(keypoints, labels), prompter.predict(boxes=box)):
+ assert results.logits.dtype == dtype
+ assert results.logits.shape == (1, 3, 256, 256)
+
+ def test_set_image_rejects_a_batch(self, device, dtype):
+ _skip_float64_on_mps(device, dtype)
+ prompter = VisualPrompter(SamConfig("mobile_sam"), device=device, dtype=dtype)
+ prompter.model.image_encoder = _StubImageEncoder(device, dtype)
+
+ with pytest.raises(BaseError, match=r"Sam\.forward"):
+ prompter.set_image(torch.rand(2, 3, 77, 128, device=device, dtype=dtype))
+
+ prompter.set_image(torch.rand(1, 3, 77, 128, device=device, dtype=dtype))
+ assert prompter.is_image_set
+ assert prompter.image_embeddings.shape == (1, 256, 64, 64)
+
+ @pytest.mark.device_agnostic
+ def test_set_image_rejects_an_integer_image(self):
+ prompter, _ = _prompter_with_stub(torch.device("cpu"), torch.float32)
+ # The image is float in [0, 1]; a uint8 image in [0, 255] would be normalised as if it were.
+ generator = torch.Generator().manual_seed(0)
+ image = torch.randint(0, 256, (3, 77, 128), generator=generator, dtype=torch.uint8)
+
+ with pytest.raises(BaseError, match="floating-point"):
+ prompter.set_image(image)
+ assert not prompter.is_image_set
+
+ @pytest.mark.device_agnostic
+ def test_transforms_must_be_one_resize(self):
+ prompter, _ = _prompter_with_stub(torch.device("cpu"), torch.float32)
+ resize = K.Resize(1024, side="long", align_corners=False, antialias=True)
+ # A first stage that is not a Resize has no output size; extra stages would move the image away from the
+ # prompts, which follow the Resize scales only.
+ for stages in ((K.RandomHorizontalFlip(),), (resize, K.RandomHorizontalFlip(p=1.0))):
+ prompter.transforms = AugmentationSequential(*stages, same_on_batch=True)
+ with pytest.raises(BaseError, match="exactly one stage"):
+ prompter.set_image(torch.rand(3, 77, 128))
+
+ # A Resize past the encoder's 1024 input would be cropped by the padding while the prompts are not.
+ prompter.transforms = AugmentationSequential(
+ K.Resize(2048, side="long", align_corners=False, antialias=True), same_on_batch=True
+ )
+ with pytest.raises(BaseError, match="larger than the image encoder's input size 1024"):
+ prompter.set_image(torch.rand(3, 77, 128))
+
+ prompter.transforms = AugmentationSequential(resize, same_on_batch=True)
+ prompter.set_image(torch.rand(3, 77, 128))
+ assert prompter._input_image_size == (616, 1024)
+
+ def test_half_prompts_map_in_float32(self, device, dtype):
+ prompter, _ = _prompter_with_stub(device, dtype)
+ prompter.set_image(torch.rand(3, 1380, 2076, device=device, dtype=dtype))
+ # The long side 2076 -> 1024; the short side is int(1380 * 1024 / 2076) = 680.
+ assert prompter._input_image_size == (680, 1024)
+ scale = torch.tensor([1024 / 2076, 680 / 1380], dtype=torch.float64)
+ # Keypoints that bfloat16 and float16 hold exactly, and a box with the same corners.
+ xy = torch.tensor([[[1504.0, 1000.0]], [[2000.0, 1296.0]], [[600.0, 400.0]]], dtype=torch.float64)
+ box = torch.tensor([[600.0, 400.0, 1504.0, 1000.0]], dtype=torch.float64)
+
+ labels = torch.ones(3, 1, device=device, dtype=dtype)
+ points = prompter.preprocess_prompts(xy.to(device=device, dtype=dtype), labels).keypoints
+ boxes = prompter.preprocess_prompts(boxes=box.to(device=device, dtype=dtype)).boxes
+
+ assert points.dtype == boxes.dtype == _prompt_dtype(dtype)
+ # Within float32 rounding (an ulp is 6e-5 at 1000) of the closed forms: (x + 0.5) * s - 0.5 for a keypoint,
+ # x * s for a box edge. Mapped in bfloat16 the keypoints were 2.26 px off, in float16 0.26 px; rounding even
+ # the exact map back to bfloat16 would cost 1.74 px.
+ expected_points = (xy + 0.5) * scale - 0.5
+ expected_box = (box.reshape(1, 2, 2) * scale).reshape(1, 4)
+ self.assert_close(points.cpu().double(), expected_points, rtol=0.0, atol=2e-4)
+ self.assert_close(boxes.cpu().double(), expected_box, rtol=0.0, atol=2e-4)
+ # The whole image covers the whole resized image after a downscale too. The box is given in float32, which
+ # holds 2076 and 1380 (bfloat16 does not); prompts of any float dtype are accepted.
+ whole = torch.tensor([[0.0, 0.0, 2076.0, 1380.0]], device=device)
+ self.assert_close(
+ prompter.preprocess_prompts(boxes=whole).boxes.cpu().double(),
+ torch.tensor([[0.0, 0.0, 1024.0, 680.0]], dtype=torch.float64),
+ rtol=0.0,
+ atol=2e-4,
+ )
+
+ def test_box_prompt_shapes(self, device, dtype):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+
+ # (1, K, 4) holds the K boxes of the one image, as K = 3 prompts of 3 masks each.
+ three = torch.tensor(
+ [[[10.0, 20.0, 60.0, 50.0], [5.0, 5.0, 120.0, 70.0], [30.0, 10.0, 90.0, 40.0]]], device=device, dtype=dtype
+ )
+ for boxes in (three, Boxes.from_tensor(three, mode="xyxy")):
+ assert prompter.predict(boxes=boxes).logits.shape == (3, 3, 256, 256)
+
+ # A leading size of 2 would be boxes for two images.
+ two = torch.tensor([[[10.0, 20.0, 60.0, 50.0]], [[5.0, 5.0, 120.0, 70.0]]], device=device, dtype=dtype)
+ for boxes in (two, Boxes.from_tensor(two, mode="xyxy")):
+ with pytest.raises(BaseError, match=r"Sam\.forward"):
+ prompter.predict(boxes=boxes)
+
+ # The values of a tensor box are checked as ``Boxes.from_tensor`` checks them: x2 > x1 and y2 > y1.
+ with pytest.raises(ValueError, match="negative widths"):
+ prompter.predict(boxes=torch.tensor([[60.0, 20.0, 10.0, 50.0]], device=device, dtype=dtype))
+
+ # A sub-pixel box, and one whose -1 vertex offset bfloat16 cannot represent at 256 (spacing 2): the ``Boxes``
+ # vertex round trip gives [9.5, 19.5, 11, 21] for the first and, in bfloat16, [256, 256, 256, 256] for the second.
+ @pytest.mark.parametrize("box", [[10.0, 20.0, 10.5, 20.5], [256.0, 256.0, 258.0, 258.0]], ids=["subpixel", "256"])
+ def test_tensor_box_corners_are_taken_as_given(self, device, dtype, box):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+ boxes = torch.tensor([box], device=device, dtype=dtype)
+
+ mapped = prompter.preprocess_prompts(boxes=boxes).boxes
+
+ # The edge map at s = 8 (77 x 128 -> 616 x 1024), x * 8 on each given corner, in the float32 prompt dtype.
+ expected = torch.tensor([box], dtype=torch.float64) * 8
+ self.assert_close(mapped, expected.to(device=device, dtype=_prompt_dtype(dtype)))
+
+ def test_box_prompts_stay_separate(self, device, dtype, cudnn_tf32_follows_option):
+ prompter = _prompter_with_stub_encoder(device, dtype)
+ boxes = torch.tensor(
+ [[10.0, 20.0, 60.0, 50.0], [5.0, 5.0, 120.0, 70.0], [30.0, 10.0, 90.0, 40.0]], device=device, dtype=dtype
+ )
+ # Each box's own edges scaled by s = 8 (77 x 128 -> 616 x 1024).
+ expected = boxes.to(_prompt_dtype(dtype)) * 8
+
+ # The four documented forms of K = 3 boxes: (K, 4), (1, K, 4), and Boxes of (K, 4, 2) and (1, K, 4, 2).
+ forms = (boxes, boxes[None], Boxes.from_tensor(boxes, mode="xyxy"), Boxes.from_tensor(boxes[None], mode="xyxy"))
+ for form in forms:
+ self.assert_close(prompter.preprocess_prompts(boxes=form).boxes, expected)
+
+ # Each prompt's masks are the ones of that box alone. `cudnn_tf32_follows_option` keeps the mask decoder's two
+ # ConvTranspose2d out of cuDNN's default TF32 on CUDA, which moves a float32 result by 1.8e-4 between batch
+ # sizes (2.7e-7 in real float32), past the float32 tolerance.
+ together = prompter.predict(boxes=boxes, output_original_size=False)
+ for k in range(3):
+ alone = prompter.predict(boxes=boxes[k : k + 1], output_original_size=False)
+ self.assert_close(together.logits[k], alone.logits[0])
+ self.assert_close(together.scores[k], alone.scores[0])
+
def test_gradcheck(self, device):
pytest.skip("Gradcheck is not currently applicable for VisualPrompter inference.")
diff --git a/tests/models/test_model_common.py b/tests/models/test_model_common.py
index 9600062d6..482505b4a 100644
--- a/tests/models/test_model_common.py
+++ b/tests/models/test_model_common.py
@@ -17,10 +17,24 @@
from __future__ import annotations
+import pytest
import torch
from kornia.models.common import MLP, ConvNormAct, DropPath, LayerNorm2d, window_partition, window_unpartition
+from testing.base import assert_close
+
+
+def _layer_norm_2d_case(device: torch.device, dtype: torch.dtype) -> tuple[LayerNorm2d, torch.Tensor]:
+ """A 256-channel LayerNorm2d with seeded affine parameters, and a seeded input spread over +-600."""
+ generator = torch.Generator().manual_seed(0)
+ layer = LayerNorm2d(256)
+ with torch.no_grad():
+ layer.weight.copy_(torch.rand(256, generator=generator) + 0.5)
+ layer.bias.copy_(torch.rand(256, generator=generator) * 2 - 1)
+ x = (torch.rand(2, 256, 4, 5, generator=generator) * 2 - 1) * 600
+ return layer.to(device=device, dtype=dtype), x.to(device=device, dtype=dtype)
+
class TestConvNormAct:
def test_odd_kernel_size(self):
@@ -143,6 +157,44 @@ class TestLayerNorm2d:
# Mean of out along channel dim should be ~0 for uniform input
assert out.abs().max() < 1e-5
+ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16], ids=["float16", "bfloat16"])
+ def test_half_input_is_normalised_in_float32(self, device, half):
+ # MobileSAM's neck feeds its last LayerNorm2d deviations from the channel mean of up to about 560. In float16
+ # their square overflows above 255.9 (sqrt(65504)), so a variance computed in float16 is inf.
+ layer, x = _layer_norm_2d_case(device, half)
+ reference_layer, _ = _layer_norm_2d_case(device, torch.float32)
+
+ out = layer(x)
+
+ assert out.dtype == half
+ assert torch.isfinite(out).all()
+ # The float32 result on the same (half-rounded) input and parameters, cast to the half dtype.
+ assert_close(out, reference_layer(x.float()).to(half))
+
+ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16], ids=["float16", "bfloat16"])
+ def test_half_input_with_float32_weights_gives_float32(self, device, half):
+ # As ``weight * x`` promotes: a float32 model under autocast feeds the neck a half input and keeps float32.
+ layer, x = _layer_norm_2d_case(device, torch.float32)
+ x = x.to(half)
+
+ out = layer(x)
+
+ assert out.dtype == torch.float32
+ assert torch.equal(out, layer(x.float()))
+
+ @pytest.mark.parametrize("full", [torch.float32, torch.float64], ids=["float32", "float64"])
+ def test_full_precision_formula_is_unchanged(self, device, full):
+ if device.type == "mps" and full == torch.float64:
+ pytest.skip("MPS does not support float64")
+ layer, x = _layer_norm_2d_case(device, full)
+
+ # The formula of Meta's LayerNorm2d (segment-anything@3518c86, modeling/common.py), bit for bit.
+ u = x.mean(1, keepdim=True)
+ s = (x - u).pow(2).mean(1, keepdim=True)
+ expected = layer.weight[:, None, None] * ((x - u) / (s + layer.eps).sqrt()) + layer.bias[:, None, None]
+
+ assert torch.equal(layer(x), expected)
+
class TestWindowPartition:
def test_no_padding_needed(self):
diff --git a/tests/models/test_prompter.py b/tests/models/test_prompter.py
index 518cb416e..f8196182f 100644
--- a/tests/models/test_prompter.py
+++ b/tests/models/test_prompter.py
@@ -34,6 +34,12 @@ class TestVisualPrompter(BaseTester):
prompter.set_image(data)
assert prompter.is_image_set
+ keypoints = torch.tensor([[[40.0, 30.0]]], device=device, dtype=dtype)
+ labels = torch.ones(1, 1, device=device, dtype=dtype)
+ out = prompter.predict(keypoints, labels)
+ assert out.logits.dtype == dtype
+ assert out.logits.shape == (1, 3, 256, 256)
+
prompter.reset_image()
assert not prompter.is_image_set
diff --git a/tests/models/test_sam.py b/tests/models/test_sam.py
index 54f95cfc9..af12a6d81 100644
--- a/tests/models/test_sam.py
+++ b/tests/models/test_sam.py
@@ -20,7 +20,9 @@ import torch
import torch.nn.functional as F
from torch import nn
+from kornia.core.exceptions import BaseError
from kornia.models.sam import Sam, SamConfig
+from kornia.models.sam.architecture.prompt_encoder import PositionEmbeddingRandom, PromptEncoder
from testing.base import BaseTester
@@ -136,6 +138,116 @@ class TestSam(BaseTester):
assert {m.training for m in Sam.from_name("mobile_sam").modules()} == {True}
assert len(loaded) == 2
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("global_attn_indexes", [(1,), [1], 1])
+ def test_from_config_builds_a_custom_encoder(self, global_attn_indexes):
+ config = SamConfig(
+ encoder_embed_dim=16, encoder_depth=2, encoder_num_heads=1, encoder_global_attn_indexes=global_attn_indexes
+ )
+ encoder = Sam.from_config(config).image_encoder
+
+ # Block 1 attends globally (window size 0); block 0 keeps SAM's 14 x 14 windows (``_build_sam``).
+ assert [block.window_size for block in encoder.blocks] == [14, 0]
+ # 684,272 parameters, mostly the neck's 3 x 3 convolution, 256 * 256 * 9 = 589,824; ViT-B's encoder has
+ # 89.7M. The whole model is not bounded: ``_build_sam`` always attaches the full mask decoder.
+ assert sum(p.numel() for p in encoder.parameters()) < 1e6
+
+ @pytest.mark.device_agnostic
+ def test_pretrained_needs_a_model_type(self):
+ config = SamConfig(
+ encoder_embed_dim=16, encoder_depth=1, encoder_num_heads=1, encoder_global_attn_indexes=0, pretrained=True
+ )
+ with pytest.raises(BaseError, match="needs a model_type"):
+ Sam.from_config(config)
+
+ def test_positional_encoding_keeps_float32_precision(self, device, dtype):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # SAM's prompt encoder: 256-dimensional embeddings, so 128 random frequencies drawn from N(0, 1).
+ generator = torch.Generator().manual_seed(0)
+ pe = PositionEmbeddingRandom(128).to(device)
+ pe.positional_encoding_gaussian_matrix.copy_(torch.randn(2, 128, generator=generator))
+ pe = pe.to(dtype)
+ # The reference: the same, possibly rounded, frequencies, encoded in float32.
+ reference = PositionEmbeddingRandom(128).to(device)
+ reference.positional_encoding_gaussian_matrix.copy_(pe.positional_encoding_gaussian_matrix.float())
+ # Keypoints in the 1024 x 1024 input frame, exact in bfloat16 (spacing 4 between 512 and 1024): the image
+ # centre, a corner pixel and a point near the far corner.
+ coords = torch.tensor([[[512.0, 512.0], [4.0, 4.0], [1020.0, 1016.0]]], device=device)
+
+ dense, points = pe((64, 64)), pe.forward_with_coords(coords.to(dtype), (1024, 1024))
+
+ assert dense.dtype == points.dtype == dtype
+ # Within the rounding of the float32 encoding. Computed in bfloat16 throughout, this seed's dense encoding is
+ # off by 0.12 (0.013 in float16).
+ self.assert_close(dense, reference((64, 64)).to(dtype))
+ self.assert_close(points, reference.forward_with_coords(coords, (1024, 1024)).to(dtype))
+
+ def test_positional_encoding_of_a_float64_model_is_float64(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ generator = torch.Generator().manual_seed(0)
+ pe = PositionEmbeddingRandom(128).to(device=device, dtype=torch.float64)
+ pe.positional_encoding_gaussian_matrix.copy_(torch.randn(2, 128, generator=generator, dtype=torch.float64))
+
+ def closed_form(dtype: torch.dtype) -> torch.Tensor:
+ # SAM's dense encoding of a 64 x 64 grid at pixel centres, (2 c - 1) M, then sin and cos of 2 pi times it.
+ centres = (torch.arange(64, device=device, dtype=dtype) + 0.5) / 64
+ grid = torch.stack(torch.meshgrid(centres, centres, indexing="xy"), dim=-1)
+ phase = 2 * torch.pi * ((2 * grid - 1) @ pe.positional_encoding_gaussian_matrix.to(dtype))
+ return torch.cat([torch.sin(phase), torch.cos(phase)], dim=-1).permute(2, 0, 1).to(torch.float64)
+
+ dense = pe((64, 64))
+
+ assert dense.dtype == torch.float64
+ self.assert_close(dense, closed_form(torch.float64), rtol=0.0, atol=1e-12)
+ # The same encoding computed in float32 is off by about 1e-6, so the comparison above can tell them apart.
+ assert (closed_form(torch.float32) - dense).abs().max() > 1e-8
+
+ def test_prompt_encoder_shifts_to_pixel_centres_in_float32(self, device, dtype):
+ if device.type == "mps" and dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ # SAM's prompt encoder for a 1024 x 1024 input and a 64 x 64 embedding (``_build_sam``).
+ encoder = PromptEncoder(256, (64, 64), (1024, 1024), mask_in_chans=16).to(device=device, dtype=dtype)
+ seen = []
+ forward_with_coords = encoder.pe_layer.forward_with_coords
+
+ def spy(coords: torch.Tensor, image_size: tuple[int, int]) -> torch.Tensor:
+ seen.append(coords)
+ return forward_with_coords(coords, image_size)
+
+ encoder.pe_layer.forward_with_coords = spy
+ # Coordinates that bfloat16 holds (its spacing is 2 between 256 and 512 and 4 between 512 and 1024), so a
+ # +0.5 shift computed in bfloat16 is rounded away.
+ points = torch.tensor([[[1000.0, 600.0]]], device=device, dtype=dtype)
+ boxes = torch.tensor([[260.0, 400.0, 1020.0, 800.0]], device=device, dtype=dtype)
+
+ encoder(points=(points, torch.ones(1, 1, device=device, dtype=dtype)), boxes=boxes, masks=None)
+
+ point_coords, box_coords = seen
+ compute_dtype = torch.promote_types(dtype, torch.float32)
+ assert point_coords.dtype == box_coords.dtype == compute_dtype
+ expected_points = torch.tensor([[[1000.5, 600.5]]], device=device, dtype=compute_dtype)
+ expected_boxes = torch.tensor([[[260.5, 400.5], [1020.5, 800.5]]], device=device, dtype=compute_dtype)
+ self.assert_close(point_coords, expected_points, rtol=0.0, atol=0.0)
+ self.assert_close(box_coords, expected_boxes, rtol=0.0, atol=0.0)
+
+ def test_positional_encoding_ignores_autocast(self, device):
+ # Autocast runs a matmul in its half dtype whatever its operands are; the encoding turns it off.
+ autocast_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ generator = torch.Generator().manual_seed(0)
+ pe = PositionEmbeddingRandom(128).to(device)
+ pe.positional_encoding_gaussian_matrix.copy_(torch.randn(2, 128, generator=generator))
+ coords = torch.tensor([[[512.0, 512.0], [4.0, 4.0], [1020.0, 1016.0]]], device=device)
+ dense, points = pe((64, 64)), pe.forward_with_coords(coords, (1024, 1024))
+
+ with torch.autocast(device_type=device.type, dtype=autocast_dtype):
+ dense_autocast, points_autocast = pe((64, 64)), pe.forward_with_coords(coords, (1024, 1024))
+
+ # Under bfloat16 autocast, a matmul in bfloat16 moves the dense encoding by up to 0.14.
+ assert torch.equal(dense_autocast, dense)
+ assert torch.equal(points_autocast, points)
+
@pytest.mark.slow
def test_mobile_sam_pretrained_is_batch_independent(self):
encoder = Sam.from_config(SamConfig("mobile_sam", pretrained=True)).image_encoder
diff --git a/tests/models/test_sam_onnx.py b/tests/models/test_sam_onnx.py
index 9bb129a1e..74316c758 100644
--- a/tests/models/test_sam_onnx.py
+++ b/tests/models/test_sam_onnx.py
@@ -17,8 +17,6 @@
"""ONNX export tests for SAM (image encoder subgraph)."""
-import sys
-
import pytest
import torch
@@ -35,21 +33,18 @@ def test_sam_has_to_onnx():
@pytest.mark.timeout(120)
- sys.platform == "darwin",
- reason="TorchScript tracing of the SAM encoder exceeds the 120s timeout on macOS CI runners",
-)
@pytest.mark.xfail(
torch_version_ge(2, 14) and torch_version_lt(2, 15, 0),
reason=(
- "torch 2.14's dynamo ONNX exporter cannot translate aten.mul.Scalar for this graph: "
- "DispatchError 'No decompositions registered for the real-valued input'; not yet "
- "reported upstream"
+ "torch 2.14's dynamo ONNX exporter cannot translate aten.mul.Scalar for this graph in the CPU "
+ "build (the CUDA build exports it): DispatchError 'No decompositions registered for the "
+ "real-valued input'; not yet reported upstream"
),
raises=torch.onnx.OnnxExporterError,
- # Strict: an upstream fix inside 2.14.x must announce itself as an XPASS failure rather
- # than sit silently until the 2.15 bound expires.
- strict=True,
+ # Strict on the CPU builds, where an upstream fix inside 2.14.x must announce itself as an XPASS failure rather
+ # than sit silently until the 2.15 bound expires. A CUDA build of 2.14.0 exports this graph (2.14.0+cu130 on
+ # Linux), so there the marker is not strict.
+ strict=torch.version.cuda is None,
)
def test_sam_encoder_to_onnx(tmp_path):
"""Sam.to_onnx() exports the image encoder subgraph with correct output name."""
@@ -58,7 +53,7 @@ def test_sam_encoder_to_onnx(tmp_path):
# Create a tiny pseudo-SAM model to prevent CI timeouts during ONNX trace
config = SamConfig(
- model_type="vit_b",
+ model_type=None,
encoder_embed_dim=16,
encoder_depth=1,
encoder_num_heads=1,
@@ -66,6 +61,8 @@ def test_sam_encoder_to_onnx(tmp_path):
)
model = Sam.from_config(config)
model.eval()
+ # The tiny encoder, not ViT-B (89.7M encoder parameters): 680,128, mostly the neck's 3 x 3 convolution.
+ assert sum(p.numel() for p in model.image_encoder.parameters()) < 1e6
onnx_path = tmp_path / "sam_encoder.onnx"
# Export only the image encoder (Sam.to_onnx overrides the full-model export).