Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(sam3): Implement Phase 2 architecture (PromptEncoder + MaskDecoder) (#3433)

arc-wonderse912db63c32a
diff --git a/kornia/models/sam3/architecture/__init__.py b/kornia/models/sam3/architecture/__init__.py
index 901d3446c..a97801918 100644
--- a/kornia/models/sam3/architecture/__init__.py
+++ b/kornia/models/sam3/architecture/__init__.py
@@ -21,11 +21,17 @@ 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/mask_decoder.py b/kornia/models/sam3/architecture/mask_decoder.py
new file mode 100644
index 000000000..8d48b6434
--- /dev/null
+++ b/kornia/models/sam3/architecture/mask_decoder.py
@@ -0,0 +1,253 @@
+# 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)
+ prompts = prompts + mlp_out
+
+ return prompts
+
+
+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
new file mode 100644
index 000000000..99c95825e
--- /dev/null
+++ b/kornia/models/sam3/architecture/prompt_encoder.py
@@ -0,0 +1,268 @@
+# 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]
+
+ output = pe + label_embeddings
+ return output
+
+ 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/tests/models/sam3/test_sam3_prompt_and_mask_architecture.py b/tests/models/sam3/test_sam3_prompt_and_mask_architecture.py
new file mode 100644
index 000000000..1806cabff
--- /dev/null
+++ b/tests/models/sam3/test_sam3_prompt_and_mask_architecture.py
@@ -0,0 +1,246 @@
+# 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}"