Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Feat/sam3 phase1 architecture (#3411)

arc-wondersd9649023ebf5
diff --git a/kornia/models/sam3/__init__.py b/kornia/models/sam3/__init__.py
new file mode 100644
index 000000000..a0c78c957
--- /dev/null
+++ b/kornia/models/sam3/__init__.py
@@ -0,0 +1,29 @@
+# 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
new file mode 100644
index 000000000..901d3446c
--- /dev/null
+++ b/kornia/models/sam3/architecture/__init__.py
@@ -0,0 +1,31 @@
+# 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
+
+__all__ = [
+ "Attention",
+ "ImageEncoderHiera",
+ "MLPBlock",
+ "PatchEmbedding",
+ "ViTBlock",
+]
diff --git a/kornia/models/sam3/architecture/common.py b/kornia/models/sam3/architecture/common.py
new file mode 100644
index 000000000..5e6751053
--- /dev/null
+++ b/kornia/models/sam3/architecture/common.py
@@ -0,0 +1,115 @@
+# 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
new file mode 100644
index 000000000..cc1d25f59
--- /dev/null
+++ b/kornia/models/sam3/architecture/image_encoder.py
@@ -0,0 +1,233 @@
+# 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)
+ x = self.norm(x)
+ return 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))
+ x = x + self.mlp(self.norm2(x))
+ return 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
+ x = self.norm(x)
+
+ return 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/tests/models/__init__.py b/tests/models/__init__.py
index 4d273d5cb..28c8d2f12 100644
--- a/tests/models/__init__.py
+++ b/tests/models/__init__.py
@@ -14,3 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+
+"""Tests for Kornia models."""
+
+__all__ = []
diff --git a/tests/models/sam3/__init__.py b/tests/models/sam3/__init__.py
new file mode 100644
index 000000000..4d273d5cb
--- /dev/null
+++ b/tests/models/sam3/__init__.py
@@ -0,0 +1,16 @@
+# 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
new file mode 100644
index 000000000..7256a325c
--- /dev/null
+++ b/tests/models/sam3/test_sam3_architecture.py
@@ -0,0 +1,143 @@
+# 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", [(512, 128), (1024, 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, 4])
+ 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=512,
+ patch_size=16,
+ embed_dim=256,
+ depth=2,
+ num_heads=8,
+ ).to(device)
+
+ x = torch.randn(batch_size, 3, 512, 512, device=device)
+ features = encoder(x)
+ assert features.shape == (batch_size, (512 // 16) ** 2, 256)
+
+ 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)