Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor(models)!: remove the kornia.models.sam3 stub (#6029)

Dmytro Mishkince149a50c0a7
diff --git a/changelog.d/6029.breaking.md b/changelog.d/6029.breaking.md
new file mode 100644
index 000000000..40778a8cf
--- /dev/null
+++ b/changelog.d/6029.breaking.md
@@ -0,0 +1 @@
+`kornia.models.sam3` is removed: `import kornia.models.sam3` raises `ModuleNotFoundError`. It shipped in v0.8.3 and v0.9.0rc1 as randomly initialised Phase 1–2 modules of #3406 (an image encoder that was a plain single-scale ViT, and a prompt encoder and mask decoder whose masks ignored point and box prompts), with no weights and no loader. SAM 3 is a different model under Meta's SAM License; a port would be a separate decision.
diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.py
index 6ccf9c905..7a8f91ad8 100644
--- a/docs/export_support/cases_models.py
+++ b/docs/export_support/cases_models.py
@@ -286,31 +286,6 @@ for tagname, mdl, err in (("mobile_sam", sam_mobile, _e_sm), ("vit_b,random", sa
)
)
-# ============================================================================= kornia.models.sam3
-from kornia.models.sam3 import ImageEncoderHiera # noqa: E402
-
-A(
- mcase(
- "models.sam3.ImageEncoderHiera[tiny,random]",
- "models.sam3",
- lambda: ev(ImageEncoderHiera(img_size=64, patch_size=16, embed_dim=64, depth=2, num_heads=2)),
- lambda m: m,
- [torch.rand(1, 3, 64, 64)],
- note="random init, img_size=64 (square, pos_embed fixed to img_size)",
- tags=("model",),
- )
-)
-A(
- case(
- "models.sam3.ImageEncoderHiera[default 1024]",
- "models.sam3",
- None,
- [],
- skip="default config = ViT-B at 1024x1024 random init; no weights loader exists in kornia; "
- "tiny variant exported",
- )
-)
-
# ============================================================================= kornia.models.yunet
from kornia.models.yunet import YuNet # noqa: E402
from kornia.models.yunet.processors import PriorBox, decode # noqa: E402
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index 00b535f6f..b6bf3786f 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -20434,40 +20434,6 @@
"variant": "single,vit_b,random",
"where": ""
},
- {
- "compile": "ok",
- "compile_detail": "",
- "export": "ok",
- "export_detail": "",
- "graph_breaks": 0,
- "name": "models.sam3.ImageEncoderHiera[tiny,random]",
- "note": "random init, img_size=64 (square, pos_embed fixed to img_size)",
- "onnx": "ok",
- "onnx_detail": "",
- "operator": "ImageEncoderHiera",
- "package": "kornia.models",
- "ref": "",
- "section": "sam3",
- "variant": "tiny,random",
- "where": ""
- },
- {
- "compile": "n/a",
- "compile_detail": "default config = ViT-B at 1024x1024 random init; no weights loader exists in kornia; tiny variant exported",
- "export": "n/a",
- "export_detail": "default config = ViT-B at 1024x1024 random init; no weights loader exists in kornia; tiny variant exported",
- "graph_breaks": 0,
- "name": "models.sam3.ImageEncoderHiera[default 1024]",
- "note": "",
- "onnx": "n/a",
- "onnx_detail": "default config = ViT-B at 1024x1024 random init; no weights loader exists in kornia; tiny variant exported",
- "operator": "ImageEncoderHiera",
- "package": "kornia.models",
- "ref": "",
- "section": "sam3",
- "variant": "default 1024",
- "where": ""
- },
{
"compile": "ok",
"compile_detail": "",
diff --git a/kornia/models/sam3/__init__.py b/kornia/models/sam3/__init__.py
deleted file mode 100644
index a0c78c957..000000000
--- a/kornia/models/sam3/__init__.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""SAM-3 (Segment Anything Model v3) integration for Kornia.
-
-This module provides the Segment Anything Model v3 (SAM-3) implementation for image segmentation tasks.
-SAM-3 is a foundation model for image segmentation that can segment any object in an image with zero-shot
-capability.
-"""
-
-from __future__ import annotations
-
-from .architecture import ImageEncoderHiera
-
-__all__ = ["ImageEncoderHiera"]
diff --git a/kornia/models/sam3/architecture/__init__.py b/kornia/models/sam3/architecture/__init__.py
deleted file mode 100644
index a97801918..000000000
--- a/kornia/models/sam3/architecture/__init__.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""SAM-3 architecture modules for Kornia."""
-
-from __future__ import annotations
-
-from .common import Attention, MLPBlock
-from .image_encoder import ImageEncoderHiera, PatchEmbedding, ViTBlock
-from .mask_decoder import CrossAttentionTransformer, MaskDecoder
-from .prompt_encoder import PositionalEncoding, PromptEncoder
-
-__all__ = [
- "Attention",
- "CrossAttentionTransformer",
- "ImageEncoderHiera",
- "MLPBlock",
- "MaskDecoder",
- "PatchEmbedding",
- "PositionalEncoding",
- "PromptEncoder",
- "ViTBlock",
-]
diff --git a/kornia/models/sam3/architecture/common.py b/kornia/models/sam3/architecture/common.py
deleted file mode 100644
index 5e6751053..000000000
--- a/kornia/models/sam3/architecture/common.py
+++ /dev/null
@@ -1,115 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Common components for SAM-3 architecture.
-
-This module provides shared building blocks for SAM-3 including:
-- Normalization layers
-- Activation functions
-- Attention primitives
-- Helper utilities
-"""
-
-from __future__ import annotations
-
-import torch
-import torch.nn.functional as F
-from torch import nn
-
-
-class MLPBlock(nn.Module):
- """Multi-layer Perceptron block.
-
- A simple feedforward network with two linear layers and GELU activation.
- """
-
- def __init__(self, embedding_dim: int, mlp_dim: int) -> None:
- """Initialize MLPBlock.
-
- Args:
- embedding_dim: Dimension of input and output features.
- mlp_dim: Dimension of the hidden layer.
- """
- super().__init__()
- self.lin1 = nn.Linear(embedding_dim, mlp_dim)
- self.lin2 = nn.Linear(mlp_dim, embedding_dim)
- self.act = nn.GELU()
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """Apply MLP block.
-
- Args:
- x: Input tensor.
-
- Returns:
- Output tensor of the same shape as input.
- """
- return self.lin2(self.act(self.lin1(x)))
-
-
-class Attention(nn.Module):
- """Multi-head attention block.
-
- Standard multi-head self-attention implementation following the Transformer architecture.
- """
-
- def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0) -> None:
- """Initialize Attention.
-
- Args:
- dim: Dimension of the input features. Should be divisible by heads * dim_head if project_out=False.
- heads: Number of attention heads.
- dim_head: Dimension of each attention head.
- dropout: Dropout probability.
- """
- super().__init__()
- inner_dim = dim_head * heads
- project_out = not (heads == 1 and dim_head == dim)
-
- self.heads = heads
- self.dropout = nn.Dropout(dropout)
-
- self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
-
- self.to_out = (
- nn.Sequential(
- nn.Linear(inner_dim, dim),
- nn.Dropout(dropout),
- )
- if project_out
- else nn.Identity()
- )
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """Apply multi-head attention.
-
- Args:
- x: Input tensor of shape (B, N, D) where B is batch size, N is sequence length, D is feature dimension.
-
- Returns:
- Output tensor of the same shape as input.
- """
- qkv = self.to_qkv(x).chunk(3, dim=-1)
- q, k, v = tuple(t.view(t.shape[0], t.shape[1], self.heads, -1).transpose(1, 2) for t in qkv)
-
- dropout_p = self.dropout.p if self.training and self.dropout.p > 0.0 else 0.0
- out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
- out = out.transpose(1, 2).contiguous().view(x.shape[0], x.shape[1], -1)
- return self.to_out(out)
-
-
-__all__ = ["Attention", "MLPBlock"]
diff --git a/kornia/models/sam3/architecture/image_encoder.py b/kornia/models/sam3/architecture/image_encoder.py
deleted file mode 100644
index 6af5eba26..000000000
--- a/kornia/models/sam3/architecture/image_encoder.py
+++ /dev/null
@@ -1,229 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""SAM-3 Image Encoder (Hiera-based backbone).
-
-This module implements the Hiera-based image encoder for SAM-3.
-The encoder processes input images and extracts multi-scale feature representations.
-"""
-
-from __future__ import annotations
-
-import torch
-from torch import nn
-
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
-
-from .common import Attention, MLPBlock
-
-
-class PatchEmbedding(nn.Module):
- """Patch embedding layer for vision transformers.
-
- Converts image patches to embeddings through a convolutional layer.
- """
-
- def __init__(self, img_size: int, patch_size: int, in_channels: int, embed_dim: int) -> None:
- """Initialize PatchEmbedding.
-
- Args:
- img_size: Input image size (assumed square).
- patch_size: Size of each patch.
- in_channels: Number of input channels (typically 3 for RGB).
- embed_dim: Embedding dimension.
- """
- super().__init__()
- self.img_size = img_size
- self.patch_size = patch_size
- self.num_patches = (img_size // patch_size) ** 2
-
- self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
- self.norm = nn.LayerNorm(embed_dim)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """Apply patch embedding.
-
- Args:
- x: Input tensor of shape (B, C, H, W).
-
- Returns:
- Tensor of shape (B, num_patches, embed_dim).
-
- Raises:
- ValueError: If image dimensions are not divisible by patch_size.
- """
- KORNIA_CHECK_SHAPE(x, ["B", "C", "H", "W"])
- KORNIA_CHECK(
- x.shape[2] % self.patch_size == 0 and x.shape[3] % self.patch_size == 0,
- f"Image dimensions must be divisible by patch_size={self.patch_size}, got H={x.shape[2]}, W={x.shape[3]}",
- )
- x = self.proj(x) # (B, embed_dim, H//patch_size, W//patch_size)
- x = x.flatten(2).transpose(1, 2) # (B, H*W, embed_dim)
- return self.norm(x)
-
-
-class ViTBlock(nn.Module):
- """Vision Transformer block with self-attention and MLP.
-
- Standard transformer block used in Vision Transformers.
- """
-
- def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, dropout: float = 0.0) -> None:
- """Initialize ViTBlock.
-
- Args:
- dim: Embedding dimension.
- num_heads: Number of attention heads.
- mlp_ratio: Ratio of mlp hidden dim to embedding dim.
- dropout: Dropout probability.
- """
- super().__init__()
- self.norm1 = nn.LayerNorm(dim)
- self.attn = Attention(dim, heads=num_heads, dropout=dropout)
- self.norm2 = nn.LayerNorm(dim)
- mlp_dim = int(dim * mlp_ratio)
- self.mlp = MLPBlock(dim, mlp_dim)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """Apply ViT block.
-
- Args:
- x: Input tensor of shape (B, N, D).
-
- Returns:
- Output tensor of the same shape.
- """
- x = x + self.attn(self.norm1(x))
- return x + self.mlp(self.norm2(x))
-
-
-class ImageEncoderHiera(nn.Module):
- """Hiera-based image encoder for SAM-3.
-
- This encoder extracts multi-scale features from input images using a Hiera backbone.
- The Hiera architecture is designed for efficient hierarchical feature extraction.
- """
-
- def __init__(
- self,
- img_size: int = 1024,
- patch_size: int = 16,
- in_channels: int = 3,
- embed_dim: int = 768,
- depth: int = 12,
- num_heads: int = 12,
- mlp_ratio: float = 4.0,
- dropout: float = 0.0,
- ) -> None:
- """Initialize ImageEncoderHiera.
-
- Args:
- img_size: Input image size (assumed square). Default: 1024
- patch_size: Patch size for patch embedding. Default: 16
- in_channels: Number of input channels. Default: 3
- embed_dim: Embedding dimension. Default: 768
- depth: Number of transformer blocks. Default: 12
- num_heads: Number of attention heads. Default: 12
- mlp_ratio: Ratio of mlp hidden dim to embedding dim. Default: 4.0
- dropout: Dropout probability. Default: 0.0
- """
- super().__init__()
- self.img_size = img_size
- self.patch_size = patch_size
- self.embed_dim = embed_dim
- self.depth = depth
- self.num_heads = num_heads
-
- # Patch embedding
- self.patch_embed = PatchEmbedding(img_size, patch_size, in_channels, embed_dim)
-
- # Positional embedding
- num_patches = (img_size // patch_size) ** 2
- self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
- nn.init.trunc_normal_(self.pos_embed, std=0.02)
-
- # Transformer blocks
- self.blocks = nn.ModuleList([ViTBlock(embed_dim, num_heads, mlp_ratio, dropout) for _ in range(depth)])
-
- # Final norm
- self.norm = nn.LayerNorm(embed_dim)
-
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- """Forward pass of the image encoder.
-
- Args:
- x: Input tensor of shape (B, C, H, W) where C should match in_channels and H, W should match img_size.
-
- Returns:
- Tensor of shape (B, num_patches, embed_dim) containing the encoded features.
-
- Raises:
- ValueError: If input channels don't match in_channels or image size doesn't match img_size.
-
- Example:
- >>> encoder = ImageEncoderHiera(img_size=1024, patch_size=16, embed_dim=768)
- >>> images = torch.randn(1, 3, 1024, 1024)
- >>> features = encoder(images)
- >>> features.shape
- torch.Size([1, 4096, 768])
- """
- expected_channels = self.patch_embed.proj.in_channels
- KORNIA_CHECK_SHAPE(x, ["B", str(expected_channels), "H", "W"])
- KORNIA_CHECK(
- x.shape[2] == self.img_size and x.shape[3] == self.img_size,
- f"Input image size must be {self.img_size}x{self.img_size}, got {x.shape[2]}x{x.shape[3]}",
- )
-
- # Patch embedding
- x = self.patch_embed(x) # (B, num_patches, embed_dim)
-
- # Add positional embedding
- x = x + self.pos_embed
-
- # Apply transformer blocks
- for block in self.blocks:
- x = block(x)
-
- # Final normalization
- return self.norm(x)
-
- def get_output_shape(self, input_shape: tuple[int, ...]) -> tuple[int, ...]:
- """Get output shape given input shape.
-
- Args:
- input_shape: Input tensor shape (B, C, H, W).
-
- Returns:
- Output tensor shape (B, num_patches, embed_dim).
-
- Raises:
- ValueError: If input_shape doesn't have 4 dimensions or dimensions are not divisible by patch_size.
- """
- KORNIA_CHECK(
- len(input_shape) == 4,
- f"Input shape must have 4 dimensions (B, C, H, W), got {len(input_shape)}",
- )
- B, _, H, W = input_shape
- KORNIA_CHECK(
- H % self.patch_size == 0 and W % self.patch_size == 0,
- f"Image dimensions must be divisible by patch_size={self.patch_size}, got H={H}, W={W}",
- )
- num_patches = (H // self.patch_size) * (W // self.patch_size)
- return (B, num_patches, self.embed_dim)
-
-
-__all__ = ["ImageEncoderHiera", "PatchEmbedding", "ViTBlock"]
diff --git a/kornia/models/sam3/architecture/mask_decoder.py b/kornia/models/sam3/architecture/mask_decoder.py
deleted file mode 100644
index 4cc44abf0..000000000
--- a/kornia/models/sam3/architecture/mask_decoder.py
+++ /dev/null
@@ -1,251 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""SAM-3 Mask Decoder for generating segmentation masks.
-
-This module implements the mask decoder for SAM-3 which takes image embeddings
-and prompt embeddings to generate segmentation masks and IoU predictions.
-"""
-
-from __future__ import annotations
-
-import torch
-from torch import nn
-
-from kornia.core.check import KORNIA_CHECK
-
-from .common import Attention, MLPBlock
-
-
-class CrossAttentionTransformer(nn.Module):
- """Transformer block with cross-attention between image and prompt embeddings.
-
- Applies cross-attention from prompt embeddings to image embeddings, followed by self-attention.
- """
-
- def __init__(self, embed_dim: int, num_heads: int = 8, mlp_ratio: float = 4.0) -> None:
- """Initialize CrossAttentionTransformer.
-
- Args:
- embed_dim: Embedding dimension.
- num_heads: Number of attention heads.
- mlp_ratio: Ratio of mlp hidden dim to embedding dim.
- """
- super().__init__()
- self.norm1 = nn.LayerNorm(embed_dim)
- self.cross_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
- self.norm2 = nn.LayerNorm(embed_dim)
- self.self_attn = Attention(embed_dim, heads=num_heads)
- self.norm3 = nn.LayerNorm(embed_dim)
- mlp_dim = int(embed_dim * mlp_ratio)
- self.mlp = MLPBlock(embed_dim, mlp_dim)
-
- def forward(
- self,
- prompts: torch.Tensor,
- image_embeddings: torch.Tensor,
- ) -> torch.Tensor:
- """Apply cross-attention transformer.
-
- Args:
- prompts: Prompt embeddings of shape (B, M, D).
- image_embeddings: Image embeddings of shape (B, N, D).
-
- Returns:
- Updated prompt embeddings of shape (B, M, D).
- """
- # Cross-attention: prompts attend to image embeddings
- prompts_norm = self.norm1(prompts)
- attn_out, _ = self.cross_attn(prompts_norm, image_embeddings, image_embeddings)
- prompts = prompts + attn_out
-
- # Self-attention on prompts
- prompts_norm = self.norm2(prompts)
- self_attn_out = self.self_attn(prompts_norm)
- prompts = prompts + self_attn_out
-
- # MLP
- prompts_norm = self.norm3(prompts)
- mlp_out = self.mlp(prompts_norm)
- return prompts + mlp_out
-
-
-class MaskDecoder(nn.Module):
- """Mask decoder for SAM-3 that generates segmentation masks.
-
- Takes image embeddings and prompt embeddings to produce segmentation masks
- and IoU predictions for the prompted regions.
- """
-
- def __init__(
- self,
- embed_dim: int = 256,
- num_multimask_outputs: int = 3,
- activation: str = "gelu",
- iou_head_depth: int = 3,
- iou_head_hidden_dim: int = 256,
- ) -> None:
- """Initialize MaskDecoder.
-
- Args:
- embed_dim: Embedding dimension.
- num_multimask_outputs: Number of mask outputs per prompt.
- activation: Activation function name.
- iou_head_depth: Depth of IoU prediction head.
- iou_head_hidden_dim: Hidden dimension of IoU head.
- """
- super().__init__()
- self.embed_dim = embed_dim
- self.num_multimask_outputs = num_multimask_outputs
- self.activation = activation
-
- # Transformer for processing prompts
- self.transformer = CrossAttentionTransformer(embed_dim)
-
- # Mask prediction head
- # NOTE: Phase 2 supports single-mask output only
- # Multi-mask generation deferred to Phase 3 when mask_tokens and hypernetwork MLPs will be used
- self.output_upscaling = nn.Sequential(
- nn.ConvTranspose2d(embed_dim, embed_dim // 4, kernel_size=2, stride=2),
- nn.GroupNorm(1, embed_dim // 4),
- nn.ConvTranspose2d(embed_dim // 4, embed_dim // 8, kernel_size=2, stride=2),
- )
- # NOTE: Phase 2 stub - mask_tokens and hypernetwork MLPs will be used in Phase 3 for multi-mask generation
-
- # IoU prediction head
- self.iou_prediction_head = nn.Sequential(
- nn.Linear(embed_dim, iou_head_hidden_dim),
- nn.ReLU(),
- nn.Linear(iou_head_hidden_dim, iou_head_hidden_dim),
- nn.ReLU(),
- nn.Linear(iou_head_hidden_dim, num_multimask_outputs),
- )
-
- def _predict_masks(
- self,
- image_embeddings: torch.Tensor,
- sparse_prompt_embeddings: torch.Tensor,
- dense_prompt_embeddings: torch.Tensor,
- ) -> tuple[torch.Tensor, torch.Tensor]:
- """Predict masks from embeddings.
-
- Args:
- image_embeddings: Image embeddings of shape (B, N, D).
- sparse_prompt_embeddings: Sparse prompt embeddings of shape (B, M, D).
- dense_prompt_embeddings: Dense prompt embeddings of shape (B, D, H, W).
-
- Returns:
- Tuple of (masks, iou_pred) where:
- - masks: Tensor of shape (B, num_masks, H, W).
- - iou_pred: Tensor of shape (B, num_masks).
- """
- B, N, _ = image_embeddings.shape
-
- # Infer spatial dimensions from sequence length
- # image_embeddings: (B, N, D) where N = H*W for square grid (per batch)
- H = W = int(N**0.5)
- KORNIA_CHECK(H * W == N, f"image_embeddings must form a square grid. Got N={N}")
-
- # Reshape image embeddings to spatial form for processing
- image_embeddings_spatial = image_embeddings.view(B, H, W, self.embed_dim).permute(0, 3, 1, 2)
-
- # Add dense prompts to image embeddings
- if dense_prompt_embeddings.shape[1] > 0:
- # Resize dense prompts to match image embedding spatial size
- dense_resized = torch.nn.functional.interpolate(
- dense_prompt_embeddings,
- size=(H, W),
- mode="bilinear",
- align_corners=False,
- )
- # Add to image embeddings
- image_embeddings_spatial = image_embeddings_spatial + dense_resized
-
- # Reshape back to sequence form
- image_with_prompts = image_embeddings_spatial.permute(0, 2, 3, 1).reshape(B, H * W, self.embed_dim)
-
- # Process sparse prompts through transformer
- if sparse_prompt_embeddings.shape[1] > 0:
- sparse_processed = self.transformer(sparse_prompt_embeddings, image_with_prompts)
- else:
- sparse_processed = sparse_prompt_embeddings
-
- # Upscale for mask prediction
- masks = self.output_upscaling(image_embeddings_spatial) # (B, D/8, H_out, W_out)
-
- # Predict IoU scores
- if sparse_processed.shape[1] > 0:
- iou_input = sparse_processed.mean(dim=1) # (B, D)
- else:
- iou_input = torch.zeros(B, self.embed_dim, device=image_embeddings.device, dtype=image_embeddings.dtype)
-
- iou_pred = self.iou_prediction_head(iou_input) # (B, num_masks)
-
- return masks, iou_pred
-
- def forward(
- self,
- image_embeddings: torch.Tensor,
- sparse_prompt_embeddings: torch.Tensor,
- dense_prompt_embeddings: torch.Tensor,
- multimask_output: bool = True,
- ) -> tuple[torch.Tensor, torch.Tensor]:
- """Generate segmentation masks from image and prompt embeddings.
-
- Args:
- image_embeddings: Image embeddings of shape (B, N, D) from image encoder.
- sparse_prompt_embeddings: Sparse prompt embeddings of shape (B, M, D) from prompt encoder.
- dense_prompt_embeddings: Dense prompt embeddings of shape (B, D, H, W) from prompt encoder.
- multimask_output: If True, output multiple masks per prompt. Otherwise, output single mask.
-
- Returns:
- Tuple of (masks, iou_pred) where:
- - masks: Segmentation masks of shape (B, num_masks, H, W).
- - iou_pred: IoU predictions of shape (B, num_masks).
-
- Raises:
- ValueError: If image_embeddings shape is invalid.
- """
- KORNIA_CHECK(
- image_embeddings.ndim == 3,
- f"image_embeddings must be 3D (B, N, D), got shape {image_embeddings.shape}",
- )
- KORNIA_CHECK(
- sparse_prompt_embeddings.ndim == 3,
- f"sparse_prompt_embeddings must be 3D (B, M, D), got shape {sparse_prompt_embeddings.shape}",
- )
- KORNIA_CHECK(
- dense_prompt_embeddings.ndim == 4,
- f"dense_prompt_embeddings must be 4D (B, D, H, W), got shape {dense_prompt_embeddings.shape}",
- )
-
- # Predict masks
- # NOTE: positional encoding intentionally omitted in Phase 2
- masks, iou_pred = self._predict_masks(
- image_embeddings,
- sparse_prompt_embeddings,
- dense_prompt_embeddings,
- )
-
- # NOTE: Phase 2 generates single mask only
- # multimask_output parameter kept for forward compatibility but currently ignored
- # Multi-mask generation deferred to Phase 3
-
- return masks, iou_pred
-
-
-__all__ = ["CrossAttentionTransformer", "MaskDecoder"]
diff --git a/kornia/models/sam3/architecture/prompt_encoder.py b/kornia/models/sam3/architecture/prompt_encoder.py
deleted file mode 100644
index a7c65c26a..000000000
--- a/kornia/models/sam3/architecture/prompt_encoder.py
+++ /dev/null
@@ -1,267 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""SAM-3 Prompt Encoder for encoding user prompts.
-
-This module implements the prompt encoder for SAM-3 which processes point prompts,
-bounding boxes, and mask prompts into dense and sparse embeddings.
-"""
-
-from __future__ import annotations
-
-import torch
-from torch import nn
-
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
-
-
-class PositionalEncoding(nn.Module):
- """Positional encoding for 2D coordinates.
-
- Encodes 2D coordinates using sinusoidal positional encoding.
- """
-
- def __init__(self, embed_dim: int) -> None:
- """Initialize PositionalEncoding.
-
- Args:
- embed_dim: Embedding dimension (must be even).
- """
- super().__init__()
- self.embed_dim = embed_dim
- KORNIA_CHECK(
- embed_dim % 2 == 0,
- f"embed_dim must be even, got {embed_dim}",
- )
-
- def forward(self, coords: torch.Tensor) -> torch.Tensor:
- """Apply positional encoding to coordinates using sinusoidal basis functions.
-
- Encodes coordinates (x, y) using sin/cos at multiple frequency scales.
- Implementation note: builds 2*embed_dim intermediate representation from x,y encoding,
- then truncates to embed_dim to maintain dimensional consistency with input embeddings.
-
- Args:
- coords: Coordinate tensor of shape (B, N, 2) where last dimension is (x, y).
-
- Returns:
- Encoded tensor of shape (B, N, embed_dim).
-
- Raises:
- ValueError: If coords does not have shape (B, N, 2).
- """
- KORNIA_CHECK_SHAPE(coords, ["B", "N", "2"])
- B, N, _ = coords.shape
-
- # Create frequency bands
- freqs = torch.arange(0, self.embed_dim // 2, dtype=torch.float32, device=coords.device)
- freqs = 2.0 ** (freqs / (self.embed_dim // 2)) * torch.pi
-
- # Expand coordinates and frequency bands for broadcasting
- coords_expanded = coords.unsqueeze(-1) # (B, N, 2, 1)
- freqs_expanded = freqs.view(1, 1, 1, -1) # (1, 1, 1, embed_dim//2)
-
- # Compute sin and cos components
- args = coords_expanded * freqs_expanded # (B, N, 2, embed_dim//2)
- sin_part = torch.sin(args) # (B, N, 2, embed_dim//2)
- cos_part = torch.cos(args) # (B, N, 2, embed_dim//2)
-
- # Interleave sin and cos for each coordinate
- encoded = torch.stack([sin_part, cos_part], dim=-1) # (B, N, 2, embed_dim//2, 2)
- encoded = encoded.view(B, N, 2, self.embed_dim) # (B, N, 2, embed_dim)
-
- # Separate x and y encodings and concatenate
- x_encoded = encoded[:, :, 0, :] # (B, N, embed_dim)
- y_encoded = encoded[:, :, 1, :] # (B, N, embed_dim)
- output = torch.cat([x_encoded, y_encoded], dim=-1) # (B, N, 2*embed_dim)
-
- # Truncate to embed_dim for dimensional consistency with input embeddings
- return output[:, :, : self.embed_dim]
-
-
-class PromptEncoder(nn.Module):
- """Encoder for SAM-3 prompts (points, boxes, masks).
-
- Encodes user prompts into sparse and dense embeddings that can be used
- by the mask decoder.
- """
-
- def __init__(
- self,
- embed_dim: int = 256,
- input_image_size: int = 1024,
- mask_in_chans: int = 16,
- ) -> None:
- """Initialize PromptEncoder.
-
- Args:
- embed_dim: Embedding dimension.
- input_image_size: Size of input image (assumed square).
- mask_in_chans: Number of input channels for mask encoding.
- """
- super().__init__()
- self.embed_dim = embed_dim
- self.input_image_size = input_image_size
- self.mask_in_chans = mask_in_chans
-
- # Point embedding
- self.pe_layer = PositionalEncoding(embed_dim)
- self.point_embeddings = nn.ModuleList(
- [nn.Embedding(1, embed_dim) for _ in range(4)]
- ) # (foreground, background, box top-left, box bottom-right)
-
- # Dense embedding (for masks)
- self.mask_downscaling = nn.Sequential(
- nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
- nn.GroupNorm(1, mask_in_chans // 4),
- nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
- nn.GroupNorm(1, mask_in_chans),
- )
- self.no_mask_embed = nn.Embedding(1, embed_dim)
-
- def _encode_points(
- self,
- points: tuple[torch.Tensor, torch.Tensor],
- ) -> torch.Tensor:
- """Encode point prompts into embeddings.
-
- Args:
- points: Tuple of (coords, labels) where:
- - coords: Tensor of shape (B, N, 2) with normalized coordinates.
- - labels: Tensor of shape (B, N) with labels (0=background, 1=foreground).
-
- Returns:
- Sparse embeddings of shape (B, N, embed_dim).
-
- Raises:
- ValueError: If coords and labels have incompatible shapes.
- """
- coords, labels = points
- KORNIA_CHECK_SHAPE(coords, ["B", "N", "2"])
- KORNIA_CHECK_SHAPE(labels, ["B", "N"])
- KORNIA_CHECK(
- coords.shape[:2] == labels.shape,
- f"coords and labels must have matching batch and point dimensions, "
- f"got {coords.shape[:2]} vs {labels.shape}",
- )
-
- B, N, _ = coords.shape
-
- # Encode coordinates using positional encoding
- pe = self.pe_layer(coords) # (B, N, embed_dim)
-
- # Simple approach: use label to select embedding
- # NOTE: loop-based implementation for clarity; can be vectorized in future optimization
- label_embeddings = torch.zeros(B, N, self.embed_dim, device=coords.device, dtype=coords.dtype)
- for b in range(B):
- for i in range(N):
- label = int(labels[b, i].item())
- label_idx = min(label, 1) # 0 or 1 for background/foreground
- label_embeddings[b, i] = self.point_embeddings[label_idx].weight[0]
-
- return pe + label_embeddings
-
- def forward(
- self,
- *,
- points: tuple[torch.Tensor, torch.Tensor] | None = None,
- boxes: torch.Tensor | None = None,
- masks: torch.Tensor | None = None,
- ) -> tuple[torch.Tensor, torch.Tensor]:
- """Encode prompts into sparse and dense embeddings.
-
- Args:
- points: Optional tuple of (coords, labels) where:
- - coords: Tensor of shape (B, N, 2) with normalized coordinates in [0, 1].
- - labels: Tensor of shape (B, N) with binary labels (0 or 1).
- boxes: Optional tensor of shape (B, num_boxes, 4) with normalized bbox coordinates.
- Currently not implemented (returns zero embeddings).
- masks: Optional tensor of shape (B, 1, H, W) with binary masks.
- Currently not implemented (returns zero embeddings).
-
- Returns:
- Tuple of (sparse_embeddings, dense_embeddings) where:
- - sparse_embeddings: Tensor of shape (B, num_sparse, embed_dim) or (B, 0, embed_dim) if no prompts.
- - dense_embeddings: Tensor of shape (B, embed_dim, H, W) or zeros if no masks.
-
- Raises:
- ValueError: If no prompts are provided or point shapes are invalid.
- """
- sparse_embeddings = []
- B = 1 # Default batch size
- device = None
-
- # Determine batch size and device from inputs
- if points is not None:
- coords, labels = points
- B = coords.shape[0]
- device = coords.device
- elif boxes is not None:
- B = boxes.shape[0]
- device = boxes.device
- elif masks is not None:
- B = masks.shape[0]
- device = masks.device
-
- # Process point prompts
- if points is not None:
- coords, labels = points
- point_embeddings = self._encode_points((coords, labels))
- sparse_embeddings.append(point_embeddings)
-
- # Process box prompts (stub)
- if boxes is not None:
- KORNIA_CHECK_SHAPE(boxes, ["B", "num_boxes", "4"])
- # Boxes are intentionally stubbed in Phase 2
- # Full implementation (box corner encoding + corner embedding lookup) deferred to Phase 3
- num_boxes = boxes.shape[1]
- box_embeddings = torch.zeros(B, num_boxes, self.embed_dim, device=boxes.device, dtype=boxes.dtype)
- sparse_embeddings.append(box_embeddings)
-
- # Concatenate sparse embeddings
- if sparse_embeddings:
- sparse_embeddings = torch.cat(sparse_embeddings, dim=1)
- else:
- if device is None:
- device = torch.device("cpu")
- sparse_embeddings = torch.zeros(B, 0, self.embed_dim, device=device)
-
- # Process mask prompts (stub)
- if masks is not None:
- KORNIA_CHECK_SHAPE(masks, ["B", "1", "H", "W"])
- dense_embeddings = self.mask_downscaling(masks)
- # Resize to match expected output size
- dense_embeddings = torch.nn.functional.interpolate(
- dense_embeddings,
- size=(self.input_image_size // 4, self.input_image_size // 4),
- mode="bilinear",
- align_corners=False,
- )
- else:
- # No mask: use no_mask embedding
- if device is None:
- device = torch.device("cpu")
- dense_embeddings = self.no_mask_embed.weight.view(1, self.embed_dim, 1, 1)
- dense_embeddings = dense_embeddings.expand(
- B, self.embed_dim, self.input_image_size // 4, self.input_image_size // 4
- )
- dense_embeddings = dense_embeddings.to(device)
-
- return sparse_embeddings, dense_embeddings
-
-
-__all__ = ["PositionalEncoding", "PromptEncoder"]
diff --git a/pyproject.toml b/pyproject.toml
index ae5c1d258..9474830e9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -92,7 +92,6 @@ omit = [
"*/__main__.py",
"*/setup.py",
"kornia/models/sam/*",
- "kornia/models/sam3/*",
"kornia/models/siglip2/*",
"kornia/models/paligemma/*",
"kornia/models/kimi_vl/*",
diff --git a/tests/api_surface_removals.json b/tests/api_surface_removals.json
index 6971a1e28..43734ffe1 100644
--- a/tests/api_surface_removals.json
+++ b/tests/api_surface_removals.json
@@ -4,5 +4,36 @@
],
"kornia.contrib.boxmot_tracker": [
"BoxMotTracker"
+ ],
+ "kornia.models.sam3": [
+ "ImageEncoderHiera"
+ ],
+ "kornia.models.sam3.architecture": [
+ "Attention",
+ "CrossAttentionTransformer",
+ "ImageEncoderHiera",
+ "MLPBlock",
+ "MaskDecoder",
+ "PatchEmbedding",
+ "PositionalEncoding",
+ "PromptEncoder",
+ "ViTBlock"
+ ],
+ "kornia.models.sam3.architecture.common": [
+ "Attention",
+ "MLPBlock"
+ ],
+ "kornia.models.sam3.architecture.image_encoder": [
+ "ImageEncoderHiera",
+ "PatchEmbedding",
+ "ViTBlock"
+ ],
+ "kornia.models.sam3.architecture.mask_decoder": [
+ "CrossAttentionTransformer",
+ "MaskDecoder"
+ ],
+ "kornia.models.sam3.architecture.prompt_encoder": [
+ "PositionalEncoding",
+ "PromptEncoder"
]
}
diff --git a/tests/models/sam3/__init__.py b/tests/models/sam3/__init__.py
deleted file mode 100644
index 4d273d5cb..000000000
--- a/tests/models/sam3/__init__.py
+++ /dev/null
@@ -1,16 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
diff --git a/tests/models/sam3/test_sam3_architecture.py b/tests/models/sam3/test_sam3_architecture.py
deleted file mode 100644
index 5f96170eb..000000000
--- a/tests/models/sam3/test_sam3_architecture.py
+++ /dev/null
@@ -1,143 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Tests for SAM-3 architecture components."""
-
-from __future__ import annotations
-
-import pytest
-import torch
-from torch import nn
-
-from kornia.models.sam3.architecture import ImageEncoderHiera
-from kornia.models.sam3.architecture.common import Attention, MLPBlock
-
-from testing.base import BaseTester
-
-
-class TestSam3Common(BaseTester):
- """Test common components used in SAM-3."""
-
- @pytest.mark.parametrize("embed_dim", [64, 256, 512])
- def test_layer_norm_smoke(self, device: str, embed_dim: int) -> None:
- """Test LayerNorm basic functionality with different dimensions."""
- B, N = 2, 64
- ln = nn.LayerNorm(embed_dim).to(device)
- x = torch.randn(B, N, embed_dim, device=device)
- out = ln(x)
- assert out.shape == x.shape
- assert out.dtype == x.dtype
-
- @pytest.mark.parametrize("embed_dim,mlp_ratio", [(64, 4.0), (256, 4.0), (512, 2.0)])
- def test_mlp_block_smoke(self, device: str, embed_dim: int, mlp_ratio: float) -> None:
- """Test MLPBlock basic functionality with different configurations."""
- B, N = 2, 64
- mlp_dim = int(embed_dim * mlp_ratio)
- mlp = MLPBlock(embed_dim, mlp_dim).to(device)
- x = torch.randn(B, N, embed_dim, device=device)
- out = mlp(x)
- assert out.shape == x.shape
- assert out.dtype == x.dtype
-
- @pytest.mark.parametrize("dim,heads", [(256, 8), (512, 16), (768, 12)])
- def test_attention_smoke(self, device: str, dim: int, heads: int) -> None:
- """Test Attention basic functionality with different configurations."""
- B, N = 2, 64
- attn = Attention(dim, heads=heads).to(device)
- x = torch.randn(B, N, dim, device=device)
- out = attn(x)
- assert out.shape == x.shape
- assert out.dtype == x.dtype
-
-
-class TestImageEncoderHiera(BaseTester):
- """Test ImageEncoderHiera architecture."""
-
- @pytest.mark.parametrize("img_size,embed_dim", [(64, 128), (128, 256)])
- def test_image_encoder_hiera_smoke(self, device: str, img_size: int, embed_dim: int) -> None:
- """Test ImageEncoderHiera basic functionality with different configs."""
- patch_size = 16
- encoder = ImageEncoderHiera(
- img_size=img_size,
- patch_size=patch_size,
- embed_dim=embed_dim,
- depth=2,
- num_heads=4,
- ).to(device)
-
- B = 1
- x = torch.randn(B, 3, img_size, img_size, device=device)
- features = encoder(x)
-
- # Expected output shape
- num_patches = (img_size // patch_size) ** 2
- assert features.shape == (B, num_patches, embed_dim)
-
- @pytest.mark.parametrize("batch_size", [1, 2])
- def test_image_encoder_hiera_cardinality(self, device: str, batch_size: int) -> None:
- """Test ImageEncoderHiera output cardinality with different batch sizes."""
- encoder = ImageEncoderHiera(
- img_size=64,
- patch_size=16,
- embed_dim=128,
- depth=2,
- num_heads=4,
- ).to(device)
-
- x = torch.randn(batch_size, 3, 64, 64, device=device)
- features = encoder(x)
- assert features.shape == (batch_size, (64 // 16) ** 2, 128)
-
- def test_image_encoder_hiera_output_shape(self) -> None:
- """Test output shape computation method."""
- encoder = ImageEncoderHiera(
- img_size=1024,
- patch_size=16,
- embed_dim=256,
- )
-
- output_shape = encoder.get_output_shape((1, 3, 1024, 1024))
- expected = (1, (1024 // 16) ** 2, 256)
- assert output_shape == expected
-
- def test_mlp_block_gradcheck(self, device: str) -> None:
- """Test MLPBlock gradient computation."""
- mlp = MLPBlock(64, 256).to(device).double()
- x = torch.randn(2, 4, 64, device=device, dtype=torch.float64, requires_grad=True)
- self.gradcheck(mlp, (x,), raise_exception=True)
-
- def test_attention_gradcheck(self, device: str) -> None:
- """Test Attention gradient computation."""
- attn = Attention(256, heads=8).to(device).double()
- x = torch.randn(1, 16, 256, device=device, dtype=torch.float64, requires_grad=True)
- self.gradcheck(attn, (x,), raise_exception=True)
-
- def test_image_encoder_hiera_gradcheck(self, device: str) -> None:
- """Test ImageEncoderHiera gradient computation."""
- encoder = (
- ImageEncoderHiera(
- img_size=64,
- patch_size=16,
- embed_dim=64,
- depth=1,
- num_heads=2,
- )
- .to(device)
- .double()
- )
- x = torch.randn(1, 3, 64, 64, device=device, dtype=torch.float64, requires_grad=True)
- self.gradcheck(encoder, (x,), raise_exception=True)
diff --git a/tests/models/sam3/test_sam3_prompt_and_mask_architecture.py b/tests/models/sam3/test_sam3_prompt_and_mask_architecture.py
deleted file mode 100644
index 1806cabff..000000000
--- a/tests/models/sam3/test_sam3_prompt_and_mask_architecture.py
+++ /dev/null
@@ -1,246 +0,0 @@
-# LICENSE HEADER MANAGED BY add-license-header
-#
-# Copyright 2018 Kornia Team
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""Tests for SAM-3 Phase 2 architecture modules."""
-
-from __future__ import annotations
-
-import torch
-
-from kornia.models.sam3.architecture.mask_decoder import MaskDecoder
-from kornia.models.sam3.architecture.prompt_encoder import PromptEncoder
-
-
-class TestPromptEncoderPoints:
- """Test PromptEncoder with point prompts."""
-
- def test_prompt_encoder_with_points(self) -> None:
- """Test basic prompt encoding with point prompts."""
- embed_dim = 256
- batch_size = 2
- num_points = 5
-
- encoder = PromptEncoder(embed_dim=embed_dim)
-
- # Create dummy point prompts
- coords = torch.rand(batch_size, num_points, 2) # (B, N, 2)
- labels = torch.randint(0, 2, (batch_size, num_points)) # (B, N) with 0 or 1
-
- sparse_emb, dense_emb = encoder(points=(coords, labels))
-
- # Check output shapes
- assert sparse_emb.shape == (batch_size, num_points, embed_dim), f"Got {sparse_emb.shape}"
- assert dense_emb.shape[0] == batch_size, f"Got {dense_emb.shape}"
- assert dense_emb.shape[1] == embed_dim, f"Got {dense_emb.shape}"
-
- def test_prompt_encoder_without_prompts(self) -> None:
- """Test prompt encoder with no prompts."""
- embed_dim = 256
- batch_size = 1
-
- encoder = PromptEncoder(embed_dim=embed_dim)
-
- sparse_emb, dense_emb = encoder()
-
- # Check output shapes
- assert sparse_emb.shape[0] == batch_size, f"Got {sparse_emb.shape}"
- assert sparse_emb.shape[2] == embed_dim, f"Got {sparse_emb.shape}"
- assert dense_emb.shape[0] == batch_size, f"Got {dense_emb.shape}"
- assert dense_emb.shape[1] == embed_dim, f"Got {dense_emb.shape}"
-
- def test_prompt_encoder_with_boxes(self) -> None:
- """Test prompt encoder with box prompts."""
- embed_dim = 256
- batch_size = 2
- num_boxes = 3
-
- encoder = PromptEncoder(embed_dim=embed_dim)
-
- # Create dummy box prompts
- boxes = torch.rand(batch_size, num_boxes, 4)
-
- sparse_emb, dense_emb = encoder(boxes=boxes)
-
- # Check output shapes
- assert sparse_emb.shape == (batch_size, num_boxes, embed_dim), f"Got {sparse_emb.shape}"
- assert dense_emb.shape[0] == batch_size, f"Got {dense_emb.shape}"
-
- def test_prompt_encoder_with_masks(self) -> None:
- """Test prompt encoder with mask prompts."""
- embed_dim = 256
- batch_size = 2
- mask_in_chans = 16
-
- encoder = PromptEncoder(embed_dim=embed_dim, input_image_size=256, mask_in_chans=mask_in_chans)
-
- # Create dummy mask prompts
- masks = torch.rand(batch_size, 1, 256, 256)
-
- sparse_emb, dense_emb = encoder(masks=masks)
-
- # Check output shapes
- assert sparse_emb.shape[0] == batch_size, f"Got {sparse_emb.shape}"
- assert sparse_emb.shape[2] == embed_dim, f"Got {sparse_emb.shape}"
- assert dense_emb.shape[0] == batch_size, f"Got {dense_emb.shape}"
- assert dense_emb.ndim == 4, f"Dense embedding should be 4D, got {dense_emb.ndim}D"
- assert dense_emb.shape[2] == 64, f"Got spatial size {dense_emb.shape[2]}" # 256 // 4
-
- def test_prompt_encoder_with_combined_prompts(self) -> None:
- """Test prompt encoder with combined point and box prompts."""
- embed_dim = 256
- batch_size = 2
- num_points = 3
- num_boxes = 2
-
- encoder = PromptEncoder(embed_dim=embed_dim)
-
- # Create dummy prompts
- coords = torch.rand(batch_size, num_points, 2)
- labels = torch.randint(0, 2, (batch_size, num_points))
- boxes = torch.rand(batch_size, num_boxes, 4)
-
- sparse_emb, dense_emb = encoder(points=(coords, labels), boxes=boxes)
-
- # Check output shapes
- expected_num_sparse = num_points + num_boxes
- assert sparse_emb.shape == (batch_size, expected_num_sparse, embed_dim), f"Got {sparse_emb.shape}"
- assert dense_emb.shape[0] == batch_size, f"Got {dense_emb.shape}"
-
-
-class TestMaskDecoderSmoke:
- """Smoke tests for MaskDecoder."""
-
- def test_mask_decoder_forward(self) -> None:
- """Test basic mask decoder forward pass."""
- embed_dim = 256
- batch_size = 2
- num_patches = 1024 # 32x32
- num_prompts = 5
-
- decoder = MaskDecoder(embed_dim=embed_dim)
-
- # Create dummy embeddings
- image_embeddings = torch.randn(batch_size, num_patches, embed_dim)
- sparse_prompts = torch.randn(batch_size, num_prompts, embed_dim)
- dense_prompts = torch.randn(batch_size, embed_dim, 32, 32)
-
- masks, iou_pred = decoder(
- image_embeddings,
- sparse_prompts,
- dense_prompts,
- multimask_output=True,
- )
-
- # Check output shapes
- assert masks.ndim == 4, f"Masks should be 4D, got {masks.ndim}D"
- assert masks.shape[0] == batch_size, f"Got {masks.shape}"
- assert iou_pred.shape == (batch_size, decoder.num_multimask_outputs), f"Got {iou_pred.shape}"
-
- def test_mask_decoder_single_mask_output(self) -> None:
- """Test mask decoder output (Phase 2 generates single mask only)."""
- embed_dim = 256
- batch_size = 1
- num_patches = 1024
- num_prompts = 3
-
- decoder = MaskDecoder(embed_dim=embed_dim)
-
- # Create dummy embeddings
- image_embeddings = torch.randn(batch_size, num_patches, embed_dim)
- sparse_prompts = torch.randn(batch_size, num_prompts, embed_dim)
- dense_prompts = torch.randn(batch_size, embed_dim, 32, 32)
-
- masks, iou_pred = decoder(
- image_embeddings,
- sparse_prompts,
- dense_prompts,
- multimask_output=False,
- )
-
- # Check output shapes
- # Phase 2 generates single mask regardless of multimask_output flag
- assert masks.ndim == 4, f"Masks should be 4D, got {masks.ndim}D"
- assert masks.shape[0] == batch_size, f"Got {masks.shape}"
- assert iou_pred.shape == (batch_size, decoder.num_multimask_outputs), f"Got {iou_pred.shape}"
-
- def test_mask_decoder_no_sparse_prompts(self) -> None:
- """Test mask decoder with no sparse prompts."""
- embed_dim = 256
- batch_size = 1
- num_patches = 1024
-
- decoder = MaskDecoder(embed_dim=embed_dim)
-
- # Create dummy embeddings with empty sparse prompts
- image_embeddings = torch.randn(batch_size, num_patches, embed_dim)
- sparse_prompts = torch.randn(batch_size, 0, embed_dim)
- dense_prompts = torch.randn(batch_size, embed_dim, 32, 32)
-
- masks, iou_pred = decoder(
- image_embeddings,
- sparse_prompts,
- dense_prompts,
- )
-
- # Check output shapes
- assert masks.ndim == 4, f"Masks should be 4D, got {masks.ndim}D"
- assert iou_pred.shape[0] == batch_size, f"Got {iou_pred.shape}"
-
- def test_mask_decoder_no_dense_prompts(self) -> None:
- """Test mask decoder with no dense prompts."""
- embed_dim = 256
- batch_size = 1
- num_patches = 1024
- num_prompts = 2
-
- decoder = MaskDecoder(embed_dim=embed_dim)
-
- # Create dummy embeddings with zero dense prompts
- image_embeddings = torch.randn(batch_size, num_patches, embed_dim)
- sparse_prompts = torch.randn(batch_size, num_prompts, embed_dim)
- dense_prompts = torch.zeros(batch_size, embed_dim, 32, 32)
-
- masks, iou_pred = decoder(
- image_embeddings,
- sparse_prompts,
- dense_prompts,
- )
-
- # Check output shapes
- assert masks.ndim == 4, f"Masks should be 4D, got {masks.ndim}D"
- assert iou_pred.shape == (batch_size, decoder.num_multimask_outputs), f"Got {iou_pred.shape}"
-
- def test_mask_decoder_batch_processing(self) -> None:
- """Test mask decoder with different batch sizes."""
- embed_dim = 256
- num_patches = 1024
-
- decoder = MaskDecoder(embed_dim=embed_dim)
-
- for batch_size in [1, 2, 4]:
- image_embeddings = torch.randn(batch_size, num_patches, embed_dim)
- sparse_prompts = torch.randn(batch_size, 3, embed_dim)
- dense_prompts = torch.randn(batch_size, embed_dim, 32, 32)
-
- masks, iou_pred = decoder(
- image_embeddings,
- sparse_prompts,
- dense_prompts,
- )
-
- assert masks.shape[0] == batch_size, f"Batch size mismatch: {masks.shape[0]} vs {batch_size}"
- assert iou_pred.shape[0] == batch_size, f"Batch size mismatch in IoU: {iou_pred.shape[0]} vs {batch_size}"