π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Implement Siglip2 in kornia.models (#3412)
Edgar Riba5c04bfc84d2a
diff --git a/kornia/models/siglip2/__init__.py b/kornia/models/siglip2/__init__.pynew file mode 100644index 000000000..1d451030e--- /dev/null+++ b/kornia/models/siglip2/__init__.py@@ -0,0 +1,25 @@+# 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.+#++"""SigLip2 vision-language model implementation."""++from .builder import SigLip2Builder+from .config import SigLip2Config+from .model import SigLip2Model, SigLip2Result+from .preprocessor import SigLip2ImagePreprocessor++__all__ = ["SigLip2Builder", "SigLip2Config", "SigLip2ImagePreprocessor", "SigLip2Model", "SigLip2Result"]diff --git a/kornia/models/siglip2/attention.py b/kornia/models/siglip2/attention.pynew file mode 100644index 000000000..4ec629b86--- /dev/null+++ b/kornia/models/siglip2/attention.py@@ -0,0 +1,141 @@+# 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.+#++"""Attention modules for SigLip2."""++from __future__ import annotations++import math+from typing import Optional++import torch+import torch.nn.functional as F+from torch import nn++from kornia.core.check import KORNIA_CHECK++__all__ = ["SigLip2Attention"]+++class SigLip2Attention(nn.Module):+ """Multi-head self-attention mechanism for SigLip2.++ This module implements the standard multi-head self-attention used in+ transformer architectures, with support for attention masks.++ Args:+ hidden_size: Hidden dimension size.+ num_heads: Number of attention heads.+ dropout: Dropout probability for attention weights.+ head_dim: Dimension of each attention head. If None, computed as hidden_size // num_heads.+ """++ def __init__(+ self,+ hidden_size: int,+ num_heads: int,+ dropout_p: float = 0.0,+ head_dim: Optional[int] = None,+ ) -> None:+ super().__init__()+ self.hidden_size = hidden_size+ self.num_heads = num_heads++ if head_dim is None:+ head_dim = hidden_size // num_heads+ self.head_dim = head_dim++ KORNIA_CHECK(+ hidden_size % num_heads == 0,+ f"hidden_size ({hidden_size}) must be divisible by num_heads ({num_heads})",+ )++ self.scale = 1.0 / math.sqrt(self.head_dim)++ # Separate Q/K/V projections (matching HF structure)+ self.q_proj = nn.Linear(hidden_size, hidden_size)+ self.k_proj = nn.Linear(hidden_size, hidden_size)+ self.v_proj = nn.Linear(hidden_size, hidden_size)+ self.out_proj = nn.Linear(hidden_size, hidden_size)+ self.dropout = nn.Dropout(dropout_p)++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ ) -> torch.Tensor:+ """Forward pass of attention.++ Args:+ hidden_states: Input tensor of shape (batch_size, seq_len, hidden_size).+ attention_mask: Optional attention mask. Can be:+ - (batch_size, seq_len): 1D mask where 1 = attend, 0 = mask+ - (batch_size, seq_len, seq_len): 2D mask where 1 = attend, 0 = mask+ - (batch_size, 1, seq_len, seq_len): 4D mask (broadcastable)++ Returns:+ Output tensor of shape (batch_size, seq_len, hidden_size).+ """+ batch_size, seq_len, _ = hidden_states.shape++ # compute Q, K, V separately+ query = self.q_proj(hidden_states)+ key = self.k_proj(hidden_states)+ value = self.v_proj(hidden_states)++ # reshape to (batch_size, seq_len, num_heads, head_dim)+ query = query.reshape(batch_size, seq_len, self.num_heads, self.head_dim)+ key = key.reshape(batch_size, seq_len, self.num_heads, self.head_dim)+ value = value.reshape(batch_size, seq_len, self.num_heads, self.head_dim)++ # transpose to (batch_size, num_heads, seq_len, head_dim)+ query = query.transpose(1, 2)+ key = key.transpose(1, 2)+ value = value.transpose(1, 2)++ # Convert attention mask to format expected by scaled_dot_product_attention+ attn_mask = None+ if attention_mask is not None:+ # Handle different mask formats+ if attention_mask.dim() == 2:+ # (batch_size, seq_len) -> (batch_size, 1, seq_len, seq_len)+ # Create 2D mask: both query and key positions must be valid+ # Convert to boolean: 1 = attend (False = don't mask), 0 = mask (True = mask out)+ mask_bool = attention_mask.bool()+ # Expand to (batch_size, 1, seq_len, seq_len) where True means mask out+ # We need: if either query or key is masked, then mask that attention+ attn_mask = ~(mask_bool.unsqueeze(1).unsqueeze(2) & mask_bool.unsqueeze(1).unsqueeze(3))+ elif attention_mask.dim() == 3:+ # (batch_size, seq_len, seq_len) -> (batch_size, 1, seq_len, seq_len)+ attn_mask = ~attention_mask.bool().unsqueeze(1)+ elif attention_mask.dim() == 4:+ # Already in correct format (batch_size, 1, seq_len, seq_len)+ attn_mask = ~attention_mask.bool()+ else:+ raise ValueError(f"Unsupported attention_mask dimension: {attention_mask.dim()}")++ dropout_p = self.dropout.p if self.training and self.dropout.p > 0.0 else 0.0+ attention_output = F.scaled_dot_product_attention(+ query,+ key,+ value,+ attn_mask=attn_mask,+ dropout_p=dropout_p,+ )++ attention_output = attention_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.hidden_size)+ return self.out_proj(attention_output)diff --git a/kornia/models/siglip2/builder.py b/kornia/models/siglip2/builder.pynew file mode 100644index 000000000..ed8675a67--- /dev/null+++ b/kornia/models/siglip2/builder.py@@ -0,0 +1,166 @@+# 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.+#++"""Builder for SigLip2 models."""++from __future__ import annotations++import logging+from typing import Optional++import torch++from .config import SigLip2Config+from .model import SigLip2Model++logger = logging.getLogger(__name__)++__all__ = ["SigLip2Builder"]+++def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, torch.Tensor]:+ """Download model weights from HuggingFace Hub."""+ try:+ from huggingface_hub import hf_hub_download+ from safetensors import safe_open+ except ImportError as e:+ error_msg = (+ "safetensors library is required for loading model weights. Install it with: pip install safetensors"+ )+ logger.error(error_msg)+ raise ImportError(error_msg) from e++ try:+ weights_path = hf_hub_download(repo_id=model_name, filename="model.safetensors", cache_dir=cache_dir)+ state_dict = {}+ with safe_open(weights_path, framework="pt", device="cpu") as f:+ for key in f.keys():+ state_dict[key] = f.get_tensor(key)+ return state_dict+ except FileNotFoundError as e:+ error_msg = (+ f"Could not find model.safetensors for {model_name}. The model must be available in safetensors format."+ )+ logger.error(error_msg)+ raise FileNotFoundError(error_msg) from e+++def _infer_max_position_embeddings(config: SigLip2Config, state_dict: dict[str, torch.Tensor]) -> SigLip2Config:+ """Infer max_position_embeddings from checkpoint if not in config."""+ pos_emb_key = "text_model.embeddings.position_embedding.weight"+ if pos_emb_key in state_dict:+ pos_emb_size = state_dict[pos_emb_key].shape[0]+ if config.text_config.max_position_embeddings != pos_emb_size:+ config.text_config.max_position_embeddings = pos_emb_size+ return config+++class SigLip2Builder:+ """Builder for SigLip2 models.++ Provides convenient methods to create SigLip2 models from configs or+ load pretrained weights from HuggingFace.+ """++ @staticmethod+ def from_name(model_name: str) -> SigLip2Model:+ """Build model from model name without loading pretrained weights.++ Supports the same models as from_pretrained_hf().++ Args:+ model_name: HuggingFace model identifier.++ Returns:+ SigLip2Model instance with random initialization.+ """+ config = SigLip2Config.from_name(model_name)+ return SigLip2Model(config)++ @staticmethod+ def from_config(config: SigLip2Config) -> SigLip2Model:+ """Build model from configuration.++ Args:+ config: Model configuration.++ Returns:+ SigLip2Model instance.+ """+ return SigLip2Model(config)++ @staticmethod+ def from_pretrained_hf(+ model_name: str = "google/siglip2-base-patch16-224",+ cache_dir: Optional[str] = None,+ ) -> SigLip2Model:+ """Load pretrained model from HuggingFace Hub.++ Downloads model weights and config from HuggingFace Hub and loads them+ using pure PyTorch (no transformers dependency).++ Supports the following models:+ - google/siglip-base-patch16-224 (V1)+ - google/siglip2-base-patch16-224+ - google/siglip2-base-patch16-256+ - google/siglip2-base-patch16-384+ - google/siglip2-base-patch16-512+ - google/siglip2-large-patch16-256+ - google/siglip2-large-patch16-384+ - google/siglip2-large-patch16-512++ Args:+ model_name: HuggingFace model identifier. Default: "google/siglip2-base-patch16-224".+ cache_dir: Optional cache directory for model files.++ Returns:+ SigLip2Model instance with pretrained weights.++ .. note::+ This method requires the `huggingface_hub` library to download files.+ Install it with: ``pip install huggingface_hub``+ For safetensors files, also install: ``pip install safetensors``+ """+ # check for huggingface_hub dependency+ try:+ import huggingface_hub # noqa: F401+ except ImportError as e:+ raise ImportError(+ "huggingface_hub library is required for downloading pretrained models. "+ "Install it with: pip install huggingface_hub"+ ) from e++ # create config from model name+ config = SigLip2Config.from_name(model_name)++ # download model weights+ state_dict = _download_weights(model_name, cache_dir)++ # infer max_position_embeddings from checkpoint if not in config+ config = _infer_max_position_embeddings(config, state_dict)++ # handle vision position embedding: HF has position_embedding.weight, we use position_embedding+ if "vision_model.embeddings.position_embedding.weight" in state_dict:+ state_dict["vision_model.embeddings.position_embedding"] = state_dict.pop(+ "vision_model.embeddings.position_embedding.weight"+ )++ # create model and load weights directly (no transformation needed)+ model = SigLip2Model(config)+ model.load_state_dict(state_dict, strict=True)++ return modeldiff --git a/kornia/models/siglip2/config.py b/kornia/models/siglip2/config.pynew file mode 100644index 000000000..d246524f1--- /dev/null+++ b/kornia/models/siglip2/config.py@@ -0,0 +1,183 @@+# 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.+#++"""Configuration classes for SigLip2 model."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Optional+++@dataclass+class SigLip2VisionConfig:+ """Configuration for SigLip2 vision encoder.++ Args:+ image_size: Size of input images.+ patch_size: Size of image patches.+ num_channels: Number of input channels.+ hidden_size: Hidden dimension size.+ num_hidden_layers: Number of transformer layers.+ num_attention_heads: Number of attention heads.+ intermediate_size: Intermediate size in feed-forward network.+ hidden_act: Activation function (typically 'gelu').+ layer_norm_eps: Epsilon for layer normalization.+ dropout_p: Dropout probability.+ attention_dropout_p: Attention dropout probability.+ """++ image_size: int = 224+ patch_size: int = 16+ num_channels: int = 3+ hidden_size: int = 768+ num_hidden_layers: int = 12+ num_attention_heads: int = 12+ intermediate_size: int = 3072+ hidden_act: str = "gelu"+ layer_norm_eps: float = 1e-6+ dropout_p: float = 0.0+ attention_dropout_p: float = 0.0+++@dataclass+class SigLip2TextConfig:+ """Configuration for SigLip2 text encoder.++ Args:+ vocab_size: Vocabulary size.+ hidden_size: Hidden dimension size.+ num_hidden_layers: Number of transformer layers.+ num_attention_heads: Number of attention heads.+ intermediate_size: Intermediate size in feed-forward network.+ max_position_embeddings: Maximum sequence length.+ hidden_act: Activation function (typically 'gelu').+ layer_norm_eps: Epsilon for layer normalization.+ dropout_p: Dropout probability.+ attention_dropout_p: Attention dropout probability.+ """++ vocab_size: int = 256000+ hidden_size: int = 768+ num_hidden_layers: int = 12+ num_attention_heads: int = 12+ intermediate_size: int = 3072+ max_position_embeddings: int = 512+ hidden_act: str = "gelu"+ layer_norm_eps: float = 1e-6+ dropout_p: float = 0.0+ attention_dropout_p: float = 0.0+++@dataclass+class SigLip2Config:+ """Configuration for SigLip2 model.++ Args:+ vision_config: Vision encoder configuration.+ text_config: Text encoder configuration.+ projection_dim: Dimension of projection layers.+ logit_scale_init_value: Initial value for logit scale (temperature).+ """++ vision_config: Optional[SigLip2VisionConfig] = None+ text_config: Optional[SigLip2TextConfig] = None+ projection_dim: int = 768+ logit_scale_init_value: float = 2.6592++ def __post_init__(self) -> None:+ """Initialize default configs if not provided."""+ if self.vision_config is None:+ self.vision_config = SigLip2VisionConfig()+ if self.text_config is None:+ self.text_config = SigLip2TextConfig()++ @staticmethod+ def from_name(model_name: str) -> SigLip2Config:+ """Create config from model name.++ Supports the following models:+ - google/siglip-base-patch16-224 (V1)+ - google/siglip2-base-patch16-224+ - google/siglip2-base-patch16-256+ - google/siglip2-base-patch16-384+ - google/siglip2-base-patch16-512+ - google/siglip2-large-patch16-256+ - google/siglip2-large-patch16-384+ - google/siglip2-large-patch16-512++ Args:+ model_name: HuggingFace model identifier.++ Returns:+ SigLip2Config instance configured for the specified model.+ """+ # Parse model name+ is_v1 = "google/siglip-base-patch16-224" in model_name+ is_large = "large" in model_name++ # Extract image size from model name+ image_size = 224 # default+ if "224" in model_name:+ image_size = 224+ elif "256" in model_name:+ image_size = 256+ elif "384" in model_name:+ image_size = 384+ elif "512" in model_name:+ image_size = 512++ # Base vs Large configurations+ if is_large:+ hidden_size = 1024+ num_layers = 24+ num_heads = 16+ projection_dim = 1024+ else: # base+ hidden_size = 768+ num_layers = 12+ num_heads = 12+ projection_dim = 768++ # Intermediate size is typically 4x hidden_size+ intermediate_size = 4 * hidden_size++ # V1 vs V2 vocab size+ vocab_size = 32000 if is_v1 else 256000++ vision_config = SigLip2VisionConfig(+ image_size=image_size,+ patch_size=16,+ hidden_size=hidden_size,+ num_hidden_layers=num_layers,+ num_attention_heads=num_heads,+ intermediate_size=intermediate_size,+ )++ text_config = SigLip2TextConfig(+ vocab_size=vocab_size,+ hidden_size=hidden_size,+ num_hidden_layers=num_layers,+ num_attention_heads=num_heads,+ intermediate_size=intermediate_size,+ )++ return SigLip2Config(+ vision_config=vision_config,+ text_config=text_config,+ projection_dim=projection_dim,+ )diff --git a/kornia/models/siglip2/model.py b/kornia/models/siglip2/model.pynew file mode 100644index 000000000..89b8792d3--- /dev/null+++ b/kornia/models/siglip2/model.py@@ -0,0 +1,242 @@+# 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.+#++"""Main SigLip2 model."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Optional++import torch+import torch.nn.functional as F+from torch import nn++from .config import SigLip2Config+from .text_encoder import SigLip2TextModel+from .vision_encoder import SigLip2VisionModel++__all__ = ["SigLip2Model", "SigLip2Result"]+++@dataclass+class SigLip2Result:+ """Result from SigLip2 model forward pass.++ Attributes:+ image_embeds: Image embeddings of shape (batch_size, projection_dim) or None.+ text_embeds: Text embeddings of shape (batch_size, projection_dim) or None.+ logit_scale: Logit scale parameter (temperature)+ logits_per_image: Logits for image-to-text matching of shape (batch_size, batch_size) or None.+ logits_per_text: Logits for text-to-image matching of shape (batch_size, batch_size) or None.+ loss: Contrastive loss or None.+ """++ logit_scale: torch.Tensor+ image_embeds: Optional[torch.Tensor] = None+ text_embeds: Optional[torch.Tensor] = None+ logits_per_image: Optional[torch.Tensor] = None+ logits_per_text: Optional[torch.Tensor] = None+ loss: Optional[torch.Tensor] = None+++class SigLip2Model(nn.Module):+ """SigLip2 vision-language model.++ This model combines a vision encoder and text encoder with projection layers+ to produce aligned embeddings in a shared space.++ Args:+ config: Model configuration.++ Note:+ Image preprocessing: Images should be preprocessed to match SigLip2ImagePreprocessor.++ Example:+ >>> import torch+ >>> from kornia.models.siglip2 import SigLip2Model, SigLip2Config, SigLip2ImagePreprocessor+ >>>+ >>> # Create model+ >>> config = SigLip2Config()+ >>> model = SigLip2Model(config)+ >>>+ >>> # Create preprocessor and process images+ >>> preprocessor = SigLip2ImagePreprocessor(image_size=(224, 224))+ >>> images = torch.randint(0, 255, (2, 3, 256, 256), dtype=torch.float32)+ >>> pixel_values = preprocessor(images)+ >>>+ >>> # Process image features+ >>> image_features = model.get_image_features(pixel_values)+ >>>+ >>> # Process text features+ >>> input_ids = torch.randint(0, 32000, (2, 10))+ >>> text_features = model.get_text_features(input_ids)+ >>>+ >>> # Joint processing+ >>> output = model(pixel_values=pixel_values, input_ids=input_ids)+ >>> logits = output.logits_per_image # Image-text similarity scores+ """++ def __init__(self, config: SigLip2Config) -> None:+ super().__init__()+ self.config = config++ # vision and text encoders+ self.vision_model = SigLip2VisionModel(config.vision_config)+ self.text_model = SigLip2TextModel(config.text_config)++ # projection layers (use Identity when projection_dim == hidden_size)+ vision_hidden_size = config.vision_config.hidden_size+ text_hidden_size = config.text_config.hidden_size+ projection_dim = config.projection_dim++ if projection_dim != vision_hidden_size:+ self.vision_projection = nn.Linear(vision_hidden_size, projection_dim)+ else:+ self.vision_projection = nn.Identity()++ if projection_dim != text_hidden_size:+ self.text_projection = nn.Linear(text_hidden_size, projection_dim)+ else:+ self.text_projection = nn.Identity()++ # logit scale (temperature parameter)+ self.logit_scale = nn.Parameter(torch.tensor(config.logit_scale_init_value))++ # logit bias+ self.logit_bias = nn.Parameter(torch.tensor(0.0))++ def get_image_features(+ self,+ pixel_values: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ normalize: bool = True,+ ) -> torch.Tensor:+ """Get image features.++ Args:+ pixel_values: Input images of shape (batch_size, num_channels, height, width).+ attention_mask: Optional attention mask for vision encoder of shape (batch_size, seq_len).+ normalize: Whether to normalize the output features.++ Returns:+ Image features of shape (batch_size, projection_dim).+ """+ vision_outputs = self.vision_model(pixel_values, attention_mask=attention_mask)+ image_features = vision_outputs[0] # Pooled output++ # Apply projection (will be identity if projection_dim == hidden_size)+ image_features = self.vision_projection(image_features)++ if normalize:+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)++ return image_features++ def get_text_features(+ self,+ input_ids: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.Tensor] = None,+ normalize: bool = True,+ ) -> torch.Tensor:+ """Get text features.++ Args:+ input_ids: Token IDs of shape (batch_size, seq_len).+ attention_mask: Optional attention mask of shape (batch_size, seq_len).+ position_ids: Optional position IDs of shape (batch_size, seq_len).+ normalize: Whether to normalize the output features.++ Returns:+ Text features of shape (batch_size, projection_dim).+ """+ text_outputs = self.text_model(+ input_ids=input_ids,+ attention_mask=attention_mask,+ position_ids=position_ids,+ )+ text_features = text_outputs[0] # Pooled output++ # apply projection (will be identity if projection_dim == hidden_size)+ text_features = self.text_projection(text_features)++ if normalize:+ text_features = text_features / text_features.norm(dim=-1, keepdim=True)++ return text_features++ def forward(+ self,+ pixel_values: Optional[torch.Tensor] = None,+ input_ids: Optional[torch.Tensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.Tensor] = None,+ return_loss: bool = False,+ ) -> SigLip2Result:+ """Forward pass.++ Args:+ pixel_values: Input images of shape (batch_size, num_channels, height, width).+ input_ids: Token IDs of shape (batch_size, seq_len).+ attention_mask: Optional attention mask for text encoder of shape (batch_size, seq_len).+ position_ids: Optional position IDs for text encoder.+ return_loss: Whether to compute and return contrastive loss.++ Returns:+ SigLip2Result containing:+ - image_embeds: Image embeddings (if pixel_values provided)+ - text_embeds: Text embeddings (if input_ids provided)+ - logit_scale: Logit scale parameter+ - logits_per_image: Logits for image-to-text matching (if both provided)+ - logits_per_text: Logits for text-to-image matching (if both provided)+ - loss: Contrastive loss (if return_loss=True and both provided)+ """+ # get embeddings+ image_embeds = self.get_image_features(pixel_values, normalize=True) if pixel_values is not None else None+ text_embeds = (+ self.get_text_features(input_ids, attention_mask=attention_mask, position_ids=position_ids, normalize=True)+ if input_ids is not None+ else None+ )++ logit_scale = self.logit_scale.exp()+ logits_per_image = None+ logits_per_text = None+ loss = None++ # compute similarity logits if both embeddings available+ if image_embeds is not None and text_embeds is not None:+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale + self.logit_bias+ logits_per_image = logits_per_text.t()++ # compute loss if requested for training or evaluation+ if return_loss:+ batch_size = image_embeds.shape[0]+ labels = torch.arange(batch_size, device=image_embeds.device)+ loss_img = -F.logsigmoid(logits_per_image[labels, labels]).mean()+ loss_txt = -F.logsigmoid(logits_per_text[labels, labels]).mean()+ loss = (loss_img + loss_txt) / 2.0++ return SigLip2Result(+ image_embeds=image_embeds,+ text_embeds=text_embeds,+ logit_scale=logit_scale,+ logits_per_image=logits_per_image,+ logits_per_text=logits_per_text,+ loss=loss,+ )diff --git a/kornia/models/siglip2/preprocessor.py b/kornia/models/siglip2/preprocessor.pynew file mode 100644index 000000000..1c7381ef6--- /dev/null+++ b/kornia/models/siglip2/preprocessor.py@@ -0,0 +1,104 @@+# 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.+#++"""SigLip2 image preprocessor."""++from __future__ import annotations++import torch+from torch import nn++from kornia.enhance.normalize import Normalize+from kornia.enhance.rescale import Rescale+from kornia.geometry.transform import Resize+++class SigLip2ImagePreprocessor(nn.Module):+ """Image preprocessor for SigLip2 models.++ This preprocessor applies the following steps:+ - Rescales pixel values from [0, 255] to [0, 1]+ - Resizes images to the specified size (with bicubic interpolation and antialiasing)+ - Normalizes with mean=[0.5, 0.5, 0.5] and std=[0.5, 0.5, 0.5] (converts [0, 1] to [-1, 1])++ Args:+ image_size: Target image size (height, width). Default: (224, 224)+ mean: Normalization mean. Default: [0.5, 0.5, 0.5]+ std: Normalization std. Default: [0.5, 0.5, 0.5]+ rescale_factor: Rescaling factor. Default: 1/255++ Example:+ >>> import torch+ >>> from kornia.models.siglip2 import SigLip2ImagePreprocessor+ >>>+ >>> # Create preprocessor+ >>> preprocessor = SigLip2ImagePreprocessor(image_size=(224, 224))+ >>>+ >>> # Process image (assumes input in [0, 255] range)+ >>> image = torch.randint(0, 255, (3, 300, 400), dtype=torch.float32)+ >>> processed = preprocessor(image) # Shape: (3, 224, 224), range: [-1, 1]+ """++ def __init__(+ self,+ image_size: tuple[int, int] = (224, 224),+ mean: list[float] | tuple[float, float, float] = (0.5, 0.5, 0.5),+ std: list[float] | tuple[float, float, float] = (0.5, 0.5, 0.5),+ rescale_factor: float = 1.0 / 255.0,+ ) -> None:+ super().__init__()+ self.image_size = image_size+ self.mean = torch.tensor([mean]) if isinstance(mean, list | tuple) else mean+ self.std = torch.tensor([std]) if isinstance(std, list | tuple) else std+ self.rescale_factor = rescale_factor++ # build preprocessing pipeline+ preproc_list: list[nn.Module] = []++ # rescale first (convert [0, 255] to [0, 1])+ if rescale_factor != 1.0:+ preproc_list.append(Rescale(factor=rescale_factor))++ # resize (on [0, 1] range)+ preproc_list.append(Resize(size=image_size, interpolation="bicubic", align_corners=False, antialias=True))++ # normalize (convert [0, 1] to [-1, 1])+ preproc_list.append(Normalize(mean=self.mean, std=self.std))++ self.preprocessor = nn.Sequential(*preproc_list)++ def forward(self, images: torch.Tensor) -> torch.Tensor:+ # ensure batch dimension+ if images.dim() == 3:+ images = images.unsqueeze(0)++ # process through pipeline+ return self.preprocessor(images)++ @classmethod+ def from_config(cls, image_size: int | tuple[int, int]) -> SigLip2ImagePreprocessor:+ """Create preprocessor from image size configuration.++ Args:+ image_size: Image size (single int for square, or tuple for (height, width))++ Returns:+ Preprocessor instance+ """+ if isinstance(image_size, int):+ image_size = (image_size, image_size)+ return cls(image_size=image_size)diff --git a/kornia/models/siglip2/text_encoder.py b/kornia/models/siglip2/text_encoder.pynew file mode 100644index 000000000..948bc9833--- /dev/null+++ b/kornia/models/siglip2/text_encoder.py@@ -0,0 +1,256 @@+# 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.+#++"""Text encoder for SigLip2."""++from __future__ import annotations++from typing import Optional++import torch+from torch import nn++from .attention import SigLip2Attention+from .config import SigLip2TextConfig++__all__ = ["SigLip2TextEmbeddings", "SigLip2TextEncoder", "SigLip2TextLayer", "SigLip2TextModel"]+++class SigLip2TextEmbeddings(nn.Module):+ """Text embeddings for SigLip2.++ Combines token embeddings and position embeddings.++ Args:+ config: Text encoder configuration.+ """++ def __init__(self, config: SigLip2TextConfig) -> None:+ super().__init__()+ self.config = config+ self.vocab_size = config.vocab_size+ self.hidden_size = config.hidden_size+ self.max_position_embeddings = config.max_position_embeddings++ # token embeddings - [vocab_size, hidden_size]+ self.token_embedding = nn.Embedding(config.vocab_size, config.hidden_size)++ # position embeddings - [max_position_embeddings, hidden_size]+ self.position_embedding = nn.Embedding(config.max_position_embeddings, config.hidden_size)++ def forward(self, input_ids: torch.Tensor, position_ids: Optional[torch.Tensor] = None) -> torch.Tensor:+ """Forward pass.++ Args:+ input_ids: Token IDs of shape (batch_size, seq_len).+ position_ids: Optional position IDs of shape (batch_size, seq_len).+ If None, uses sequential positions.++ Returns:+ Embedded tokens of shape (batch_size, seq_len, hidden_size).+ """+ batch_size, seq_len = input_ids.shape++ # token embeddings - [batch_size, seq_len, hidden_size]+ token_embeddings = self.token_embedding(input_ids)++ # position embeddings - [batch_size, seq_len, hidden_size]+ if position_ids is None:+ position_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0).expand(batch_size, -1)+ position_embeddings = self.position_embedding(position_ids)++ # combine embeddings - [batch_size, seq_len, hidden_size]+ embeddings = token_embeddings + position_embeddings++ return embeddings+++class SigLip2TextMLP(nn.Module):+ """MLP (feed-forward network) for text encoder.++ Args:+ config: Text encoder configuration.+ """++ def __init__(self, config: SigLip2TextConfig) -> None:+ super().__init__()+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)+ self.activation = nn.GELU()+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)+ self.dropout = nn.Dropout(config.dropout_p)++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ # linear transformation - [batch_size, seq_len, intermediate_size]+ hidden_states = self.fc1(hidden_states)+ # activation function - [batch_size, seq_len, intermediate_size]+ hidden_states = self.activation(hidden_states)+ # linear transformation - [batch_size, seq_len, hidden_size]+ hidden_states = self.fc2(hidden_states)+ hidden_states = self.dropout(hidden_states)+ return hidden_states+++class SigLip2TextLayer(nn.Module):+ """Transformer layer for SigLip2 text encoder.++ Implements pre-norm architecture with residual connections.++ Args:+ config: Text encoder configuration.+ """++ def __init__(self, config: SigLip2TextConfig) -> None:+ super().__init__()+ self.self_attn = SigLip2Attention(+ hidden_size=config.hidden_size,+ num_heads=config.num_attention_heads,+ dropout_p=config.attention_dropout_p,+ )+ self.mlp = SigLip2TextMLP(config)+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)++ def forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:+ """Forward pass.++ Args:+ hidden_states: Input tensor of shape (batch_size, seq_len, hidden_size).+ attention_mask: Optional attention mask.++ Returns:+ Output tensor of shape (batch_size, seq_len, hidden_size).+ """+ # self-attention with pre-norm+ residual = hidden_states+ hidden_states = self.layer_norm1(hidden_states)+ hidden_states = self.self_attn(hidden_states, attention_mask=attention_mask)+ hidden_states = residual + hidden_states++ # MLP with pre-norm - [batch_size, seq_len, hidden_size]+ residual = hidden_states+ hidden_states = self.layer_norm2(hidden_states)+ hidden_states = self.mlp(hidden_states)+ hidden_states = residual + hidden_states++ # return the hidden states - [batch_size, seq_len, hidden_size]+ return hidden_states+++class SigLip2TextEncoder(nn.Module):+ """Text encoder stack for SigLip2.++ Args:+ config: Text encoder configuration.+ """++ def __init__(self, config: SigLip2TextConfig) -> None:+ super().__init__()+ self.layers = nn.ModuleList([SigLip2TextLayer(config) for _ in range(config.num_hidden_layers)])++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ output_hidden_states: bool = False,+ ) -> tuple[torch.Tensor, ...]:+ """Forward pass through encoder layers.++ Args:+ hidden_states: Input embeddings of shape (batch_size, seq_len, hidden_size).+ attention_mask: Optional attention mask of shape (batch_size, seq_len).+ output_hidden_states: Whether to return hidden states from all layers.++ Returns:+ Tuple of (last_hidden_state,) or (last_hidden_state, all_hidden_states).+ """+ all_hidden_states = [] if output_hidden_states else None++ for layer in self.layers:+ if output_hidden_states:+ all_hidden_states.append(hidden_states)+ hidden_states = layer(hidden_states, attention_mask=attention_mask)++ if output_hidden_states:+ all_hidden_states.append(hidden_states)+ return (hidden_states, tuple(all_hidden_states))++ return (hidden_states,)+++class SigLip2TextModel(nn.Module):+ """Complete text encoder model for SigLip2.++ Args:+ config: Text encoder configuration.+ """++ def __init__(self, config: SigLip2TextConfig) -> None:+ super().__init__()+ self.config = config+ self.embeddings = SigLip2TextEmbeddings(config)+ self.encoder = SigLip2TextEncoder(config)+ # final layer norm - [batch_size, hidden_size]+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)+ # head layer - [batch_size, hidden_size]+ self.head = nn.Linear(config.hidden_size, config.hidden_size)++ def forward(+ self,+ input_ids: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ position_ids: Optional[torch.Tensor] = None,+ output_hidden_states: bool = False,+ ) -> tuple[torch.Tensor, ...]:+ """Forward pass.++ Args:+ input_ids: Token IDs of shape (batch_size, seq_len).+ attention_mask: Optional attention mask of shape (batch_size, seq_len).+ Values should be 1 for unmasked tokens and 0 for masked tokens.+ position_ids: Optional position IDs.+ output_hidden_states: Whether to return hidden states from all layers.++ Returns:+ Tuple containing:+ - Pooled output (EOS token)+ - Last hidden state+ - All hidden states (if output_hidden_states=True)+ """+ # get embeddings - [batch_size, seq_len, hidden_size]+ hidden_states = self.embeddings(input_ids, position_ids=position_ids)++ # encode - [batch_size, seq_len, hidden_size]+ encoder_outputs = self.encoder(+ hidden_states,+ attention_mask=attention_mask,+ output_hidden_states=output_hidden_states,+ )++ last_hidden_state = encoder_outputs[0]++ # apply final layer norm - [batch_size, hidden_size]+ last_hidden_state = self.final_layer_norm(last_hidden_state)++ # pool: use the last token - [batch_size, hidden_size]+ pooled_output = last_hidden_state[:, -1]++ # apply head layer - [batch_size, hidden_size]+ pooled_output = self.head(pooled_output)++ if output_hidden_states:+ return (pooled_output, last_hidden_state, encoder_outputs[1])+ return (pooled_output, last_hidden_state)diff --git a/kornia/models/siglip2/vision_encoder.py b/kornia/models/siglip2/vision_encoder.pynew file mode 100644index 000000000..8c0aac1b9--- /dev/null+++ b/kornia/models/siglip2/vision_encoder.py@@ -0,0 +1,302 @@+# 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.+#++"""Vision encoder for SigLip2."""++from __future__ import annotations++from typing import Optional++import torch+from torch import nn++from .attention import SigLip2Attention+from .config import SigLip2VisionConfig++__all__ = [+ "SigLip2MultiheadAttentionPoolingHead",+ "SigLip2VisionEmbeddings",+ "SigLip2VisionEncoder",+ "SigLip2VisionLayer",+ "SigLip2VisionModel",+]+++class SigLip2VisionEmbeddings(nn.Module):+ """Vision embeddings for SigLip2.++ Combines patch embedding and position embeddings.++ Args:+ config: Vision encoder configuration.+ """++ def __init__(self, config: SigLip2VisionConfig) -> None:+ super().__init__()+ self.config = config+ self.patch_size = config.patch_size+ self.image_size = config.image_size+ self.num_channels = config.num_channels+ self.hidden_size = config.hidden_size++ # extract patches from the image using a convolutional layer+ self.patch_embedding = nn.Conv2d(+ in_channels=config.num_channels,+ out_channels=config.hidden_size,+ kernel_size=config.patch_size,+ stride=config.patch_size,+ bias=True,+ )++ # calculate the number of patches in the image+ self.num_patches = (config.image_size // config.patch_size) ** 2++ # position embeddings - [num_patches, hidden_size]+ self.position_embedding = nn.Parameter(torch.randn(self.num_patches, config.hidden_size))++ # dropout or identity+ self.dropout = nn.Dropout(config.dropout_p)++ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:+ """Forward pass.++ Args:+ pixel_values: Input images of shape (batch_size, num_channels, height, width).++ Returns:+ Embedded patches of shape (batch_size, num_patches, hidden_size).+ """+ # extract patches from the image+ embeddings = self.patch_embedding(pixel_values) # (batch_size, hidden_size, H', W')+ embeddings = embeddings.flatten(2).transpose(1, 2) # (batch_size, num_patches, hidden_size)++ # add position embeddings to the embeddings+ embeddings = embeddings + self.position_embedding.unsqueeze(0)++ return embeddings+++class SigLip2VisionMLP(nn.Module):+ """MLP (feed-forward network) for vision encoder.++ Args:+ config: Vision encoder configuration.+ """++ def __init__(self, config: SigLip2VisionConfig) -> None:+ super().__init__()+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)+ self.activation = nn.GELU()+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)+ self.dropout = nn.Dropout(config.dropout_p)++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ hidden_states = self.fc1(hidden_states)+ hidden_states = self.activation(hidden_states)+ hidden_states = self.fc2(hidden_states)+ hidden_states = self.dropout(hidden_states)+ return hidden_states+++class SigLip2VisionLayer(nn.Module):+ """Transformer layer for vision encoder.++ Implements pre-norm architecture with residual connections.++ Args:+ config: Vision encoder configuration.+ """++ def __init__(self, config: SigLip2VisionConfig) -> None:+ super().__init__()+ self.self_attn = SigLip2Attention(+ hidden_size=config.hidden_size,+ num_heads=config.num_attention_heads,+ dropout_p=config.attention_dropout_p,+ )+ self.mlp = SigLip2VisionMLP(config)+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)++ def forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:+ """Forward pass.++ Args:+ hidden_states: Input tensor of shape (batch_size, seq_len, hidden_size).+ attention_mask: Optional attention mask.++ Returns:+ Output tensor of shape (batch_size, seq_len, hidden_size).+ """+ # Self-attention with pre-norm+ residual = hidden_states+ hidden_states = self.layer_norm1(hidden_states)+ hidden_states = self.self_attn(hidden_states, attention_mask=attention_mask)+ hidden_states = residual + hidden_states++ # MLP with pre-norm+ residual = hidden_states+ hidden_states = self.layer_norm2(hidden_states)+ hidden_states = self.mlp(hidden_states)+ hidden_states = residual + hidden_states++ return hidden_states+++class SigLip2MultiheadAttentionPoolingHead(nn.Module):+ """Multi-head attention pooling head for vision encoder.++ This implements the pooling mechanism used by HF SigLip vision model.+ Uses a learnable probe token with multi-head attention to pool the sequence.++ Args:+ config: Vision encoder configuration.+ """++ def __init__(self, config: SigLip2VisionConfig) -> None:+ super().__init__()+ # Learnable probe (query token)+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))++ # Multi-head attention (using PyTorch's built-in for compatibility)+ self.attention = nn.MultiheadAttention(+ embed_dim=config.hidden_size,+ num_heads=config.num_attention_heads,+ batch_first=True,+ )+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)+ self.mlp = SigLip2VisionMLP(config)++ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:+ # repeat the probe token for the batch size+ batch_size = hidden_state.shape[0]+ probe = self.probe.repeat(batch_size, 1, 1) # (batch_size, 1, hidden_size)++ # multi-head attention: probe as query, hidden_state as key/value+ hidden_state, _ = self.attention(probe, hidden_state, hidden_state)++ # residual connection with layer norm and MLP+ residual = hidden_state+ hidden_state = self.layernorm(hidden_state)+ hidden_state = residual + self.mlp(hidden_state)++ # return the first (and only) token - [batch_size, hidden_size]+ return hidden_state[:, 0]+++class SigLip2VisionEncoder(nn.Module):+ """Vision encoder stack for SigLip2.++ Args:+ config: Vision encoder configuration.+ """++ def __init__(self, config: SigLip2VisionConfig) -> None:+ super().__init__()+ self.layers = nn.ModuleList([SigLip2VisionLayer(config) for _ in range(config.num_hidden_layers)])++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ output_hidden_states: bool = False,+ ) -> tuple[torch.Tensor, ...]:+ """Forward pass through encoder layers.++ Args:+ hidden_states: Input embeddings of shape (batch_size, seq_len, hidden_size).+ attention_mask: Optional attention mask.+ output_hidden_states: Whether to return hidden states from all layers.++ Returns:+ Tuple of (last_hidden_state,) or (last_hidden_state, all_hidden_states).+ """+ all_hidden_states = [] if output_hidden_states else None++ for layer in self.layers:+ if output_hidden_states:+ all_hidden_states.append(hidden_states)+ hidden_states = layer(hidden_states, attention_mask=attention_mask)++ if output_hidden_states:+ all_hidden_states.append(hidden_states)+ return (hidden_states, tuple(all_hidden_states))++ return (hidden_states,)+++class SigLip2VisionModel(nn.Module):+ """Complete vision encoder model for SigLip2.++ Args:+ config: Vision encoder configuration.+ """++ def __init__(self, config: SigLip2VisionConfig) -> None:+ super().__init__()+ self.config = config+ self.embeddings = SigLip2VisionEmbeddings(config)+ self.encoder = SigLip2VisionEncoder(config)++ # post layer norm - [batch_size, hidden_size]+ self.post_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)++ # head: multi-head attention pooling - [batch_size, hidden_size]+ self.head = SigLip2MultiheadAttentionPoolingHead(config)++ def forward(+ self,+ pixel_values: torch.Tensor,+ attention_mask: Optional[torch.Tensor] = None,+ output_hidden_states: bool = False,+ ) -> tuple[torch.Tensor, ...]:+ """Forward pass.++ Args:+ pixel_values: Input images of shape (batch_size, num_channels, height, width).+ attention_mask: Optional attention mask.+ output_hidden_states: Whether to return hidden states from all layers.++ Returns:+ Tuple containing:+ - Pooled output (mean pooled)+ - Last hidden state+ - All hidden states (if output_hidden_states=True)+ """+ # Get embeddings+ hidden_states = self.embeddings(pixel_values)++ # Encode+ encoder_outputs = self.encoder(+ hidden_states,+ attention_mask=attention_mask,+ output_hidden_states=output_hidden_states,+ )++ last_hidden_state = encoder_outputs[0]++ # apply post layer norm - [batch_size, hidden_size]+ last_hidden_state = self.post_layernorm(last_hidden_state)++ # pool: multi-head attention pooling - [batch_size, hidden_size]+ pooled_output = self.head(last_hidden_state)++ if output_hidden_states:+ return (pooled_output, last_hidden_state, encoder_outputs[1])++ # return the pooled output and the last hidden state - [batch_size, hidden_size]+ return (pooled_output, last_hidden_state)diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.pynew file mode 100644index 000000000..ded2f1164--- /dev/null+++ b/tests/models/test_siglip2.py@@ -0,0 +1,349 @@+# 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 SigLip2 model."""++import pytest+import torch++from kornia.models.siglip2 import SigLip2Config, SigLip2Model, SigLip2Result+from kornia.models.siglip2.attention import SigLip2Attention+from kornia.models.siglip2.config import SigLip2TextConfig, SigLip2VisionConfig+from kornia.models.siglip2.preprocessor import SigLip2ImagePreprocessor+from kornia.models.siglip2.text_encoder import SigLip2TextEmbeddings, SigLip2TextEncoder, SigLip2TextModel+from kornia.models.siglip2.vision_encoder import SigLip2VisionEmbeddings, SigLip2VisionEncoder, SigLip2VisionModel++from testing.base import BaseTester+++def config():+ """Fixture for SigLip2Config."""+ return SigLip2Config()+++def model(device, dtype, config):+ """Fixture for SigLip2Model."""+ return SigLip2Model(config).to(device, dtype).eval()+++def _create_input_ids(batch_size, seq_len, config, device):+ """Create input_ids with smaller range to avoid memory issues with large vocab."""+ return torch.randint(0, min(100, config.text_config.vocab_size), (batch_size, seq_len), device=device)+++class TestSigLip2Model(BaseTester):+ """Test suite for SigLip2 model."""++ def test_smoke(self, device, dtype, config):+ """Test basic model instantiation."""+ model = SigLip2Model(config).to(device, dtype)+ assert model is not None++ @pytest.mark.parametrize("batch_size", [1, 2, 4])+ def test_cardinality(self, device, dtype, model, config, batch_size):+ """Test output shapes with different inputs and batch sizes."""+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)+ seq_len = 10+ input_ids = _create_input_ids(batch_size, seq_len, config, device)++ with torch.no_grad():+ # Image only+ output: SigLip2Result = model(pixel_values=pixel_values)+ assert output.image_embeds is not None+ assert output.image_embeds.shape == (batch_size, config.projection_dim)+ assert output.text_embeds is None++ # Text only+ output: SigLip2Result = model(input_ids=input_ids)+ assert output.text_embeds is not None+ assert output.text_embeds.shape == (batch_size, config.projection_dim)+ assert output.image_embeds is None++ # Joint+ output: SigLip2Result = model(pixel_values=pixel_values, input_ids=input_ids)+ assert output.image_embeds.shape == (batch_size, config.projection_dim)+ assert output.text_embeds.shape == (batch_size, config.projection_dim)+ assert output.logits_per_image.shape == (batch_size, batch_size)+ assert output.logits_per_text.shape == (batch_size, batch_size)++ def test_exception(self, device, dtype, model, config):+ """Test exception handling."""+ # Test invalid pixel_values shape (wrong number of dimensions)+ with pytest.raises((RuntimeError, ValueError, IndexError)):+ invalid_pixel_values = torch.randn(3, 224, 224, device=device, dtype=dtype) # Missing batch dimension+ model.get_image_features(invalid_pixel_values)++ # Test invalid attention mask shape+ with pytest.raises((RuntimeError, ValueError, IndexError)):+ input_ids = _create_input_ids(2, 10, config, device)+ invalid_attention_mask = torch.ones(2, 5, device=device) # Wrong sequence length+ model.get_text_features(input_ids, attention_mask=invalid_attention_mask)++ # Test input_ids with wrong number of dimensions+ with pytest.raises((RuntimeError, ValueError, IndexError)):+ invalid_input_ids = torch.randint(0, 100, (10,), device=device) # Missing batch dimension+ model.get_text_features(invalid_input_ids)++ def test_get_image_features(self, device, dtype, model, config):+ """Test get_image_features method."""++ batch_size = 2+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)++ with torch.no_grad():+ features = model.get_image_features(pixel_values)++ assert features.shape == (batch_size, config.projection_dim)+ # Check normalization+ norms = features.norm(dim=-1)+ self.assert_close(norms, torch.ones_like(norms), rtol=1e-5, atol=1e-5)++ def test_get_text_features(self, device, dtype, model, config):+ """Test get_text_features method."""++ batch_size = 2+ seq_len = 10+ input_ids = _create_input_ids(batch_size, seq_len, config, device)+ attention_mask = torch.ones(batch_size, seq_len, device=device)++ with torch.no_grad():+ features = model.get_text_features(input_ids, attention_mask=attention_mask)++ assert features.shape == (batch_size, config.projection_dim)+ # Check normalization+ norms = features.norm(dim=-1)+ self.assert_close(norms, torch.ones_like(norms), rtol=1e-5, atol=1e-5)++ def test_attention_mask_handling(self, device, dtype, model, config):+ """Test attention mask handling in text encoder."""++ batch_size = 2+ seq_len = 10+ input_ids = _create_input_ids(batch_size, seq_len, config, device)++ # Create attention mask with different lengths+ attention_mask = torch.ones(batch_size, seq_len, device=device)+ attention_mask[0, 5:] = 0 # First sequence has 5 tokens+ attention_mask[1, 8:] = 0 # Second sequence has 8 tokens++ with torch.no_grad():+ features = model.get_text_features(input_ids, attention_mask=attention_mask)++ assert features.shape == (batch_size, config.projection_dim)++ def test_return_loss(self, device, dtype, model, config):+ """Test forward pass with return_loss=True."""++ batch_size = 2+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)+ seq_len = 10+ input_ids = _create_input_ids(batch_size, seq_len, config, device)++ with torch.no_grad():+ output = model(pixel_values=pixel_values, input_ids=input_ids, return_loss=True)++ assert output.loss is not None+ assert output.loss.item() >= 0.0 # Loss should be non-negative++ def test_gradcheck(self, device, dtype, config):+ """Test gradient computation correctness."""+ # Convert model to float64 for gradcheck+ model = SigLip2Model(config).to(device, torch.float64).train()+ batch_size = 1+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=torch.float64, requires_grad=True)+ seq_len = 5+ input_ids = _create_input_ids(batch_size, seq_len, config, device).to(torch.int64)++ # Only check gradients for pixel_values (input_ids are indices, not differentiable)+ def func(pixel_vals):+ # Use input_ids as closure variable, not as gradcheck input+ return model.get_image_features(pixel_vals) + model.get_text_features(input_ids)++ self.gradcheck(func, pixel_values, raise_exception=True, fast_mode=True)++ def test_dynamo(self, device, dtype, torch_optimizer, model, config):+ """Test torch.compile compatibility."""+ batch_size = 1+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)+ seq_len = 10+ input_ids = _create_input_ids(batch_size, seq_len, config, device)++ model_optimized = torch_optimizer(model)++ with torch.no_grad():+ expected = model(pixel_values=pixel_values, input_ids=input_ids)+ actual = model_optimized(pixel_values=pixel_values, input_ids=input_ids)++ self.assert_close(actual.image_embeds, expected.image_embeds)+ self.assert_close(actual.text_embeds, expected.text_embeds)+++class TestSigLip2Components(BaseTester):+ """Test suite for SigLip2 individual components."""++ def test_vision_embeddings(self, device, dtype):+ """Test SigLip2VisionEmbeddings."""+ config = SigLip2VisionConfig(image_size=224, patch_size=16, hidden_size=768)+ embeddings = SigLip2VisionEmbeddings(config).to(device, dtype)++ batch_size = 2+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)++ with torch.no_grad():+ output = embeddings(pixel_values)++ num_patches = (224 // 16) ** 2+ assert output.shape == (batch_size, num_patches, config.hidden_size)++ def test_vision_encoder(self, device, dtype):+ """Test SigLip2VisionEncoder."""+ config = SigLip2VisionConfig(+ image_size=224, patch_size=16, hidden_size=768, num_hidden_layers=2, num_attention_heads=12+ )+ encoder = SigLip2VisionEncoder(config).to(device, dtype)+ embeddings = SigLip2VisionEmbeddings(config).to(device, dtype)++ batch_size = 2+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)++ with torch.no_grad():+ # Encoder expects embeddings, not raw pixel values+ hidden_states = embeddings(pixel_values)+ output = encoder(hidden_states)++ num_patches = (224 // 16) ** 2+ assert output[0].shape == (batch_size, num_patches, config.hidden_size)++ def test_vision_model(self, device, dtype):+ """Test SigLip2VisionModel."""+ config = SigLip2VisionConfig(+ image_size=224, patch_size=16, hidden_size=768, num_hidden_layers=2, num_attention_heads=12+ )+ model = SigLip2VisionModel(config).to(device, dtype)++ batch_size = 2+ pixel_values = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)++ with torch.no_grad():+ pooled_output, last_hidden_state = model(pixel_values)++ assert pooled_output.shape == (batch_size, config.hidden_size)+ num_patches = (224 // 16) ** 2+ assert last_hidden_state.shape == (batch_size, num_patches, config.hidden_size)++ def test_text_embeddings(self, device, dtype):+ """Test SigLip2TextEmbeddings."""+ config = SigLip2TextConfig(vocab_size=1000, hidden_size=768, max_position_embeddings=512)+ embeddings = SigLip2TextEmbeddings(config).to(device, dtype)++ batch_size = 2+ seq_len = 10+ input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len), device=device)++ with torch.no_grad():+ output = embeddings(input_ids)++ assert output.shape == (batch_size, seq_len, config.hidden_size)++ def test_text_encoder(self, device, dtype):+ """Test SigLip2TextEncoder."""+ config = SigLip2TextConfig(+ vocab_size=1000,+ hidden_size=768,+ num_hidden_layers=2,+ num_attention_heads=12,+ max_position_embeddings=512,+ )+ encoder = SigLip2TextEncoder(config).to(device, dtype)+ embeddings = SigLip2TextEmbeddings(config).to(device, dtype)++ batch_size = 2+ seq_len = 10+ input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len), device=device)+ attention_mask = torch.ones(batch_size, seq_len, device=device)++ with torch.no_grad():+ # Encoder expects hidden_states (embeddings), not input_ids+ hidden_states = embeddings(input_ids)+ output = encoder(hidden_states, attention_mask=attention_mask)++ assert output[0].shape == (batch_size, seq_len, config.hidden_size)++ def test_text_model(self, device, dtype):+ """Test SigLip2TextModel."""+ config = SigLip2TextConfig(+ vocab_size=1000,+ hidden_size=768,+ num_hidden_layers=2,+ num_attention_heads=12,+ max_position_embeddings=512,+ )+ model = SigLip2TextModel(config).to(device, dtype)++ batch_size = 2+ seq_len = 10+ input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len), device=device)+ attention_mask = torch.ones(batch_size, seq_len, device=device)++ with torch.no_grad():+ pooled_output, last_hidden_state = model(input_ids=input_ids, attention_mask=attention_mask)++ assert pooled_output.shape == (batch_size, config.hidden_size)+ assert last_hidden_state.shape == (batch_size, seq_len, config.hidden_size)++ def test_attention(self, device, dtype):+ """Test SigLip2Attention."""+ hidden_size = 768+ num_heads = 12+ attention = SigLip2Attention(hidden_size=hidden_size, num_heads=num_heads).to(device, dtype)++ batch_size = 2+ seq_len = 10+ hidden_states = torch.randn(batch_size, seq_len, hidden_size, device=device, dtype=dtype)+ attention_mask = torch.ones(batch_size, seq_len, device=device)++ with torch.no_grad():+ output = attention(hidden_states, attention_mask=attention_mask)++ # Attention returns a single tensor, not a tuple+ assert output.shape == (batch_size, seq_len, hidden_size)++ @pytest.mark.parametrize("batch_size", [1, 2, 4])+ @pytest.mark.parametrize("input_size", [(256, 256), (300, 400), (512, 512)])+ @pytest.mark.parametrize("image_size", [(224, 224), (256, 256), (384, 384)])+ def test_image_preprocessor(self, device, dtype, batch_size, input_size, image_size):+ """Test SigLip2ImagePreprocessor with different configurations."""+ preprocessor = SigLip2ImagePreprocessor(image_size=image_size).to(device, dtype)++ # Test with batch of images (4D tensor)+ images = torch.randint(0, 255, (batch_size, 3, *input_size), device=device, dtype=dtype)+ with torch.no_grad():+ output = preprocessor(images)+ assert output.shape == (batch_size, 3, image_size[0], image_size[1])++ def test_image_preprocessor_single_image(self, device, dtype):+ """Test SigLip2ImagePreprocessor with single image (3D tensor)."""+ image_size = (224, 224)+ preprocessor = SigLip2ImagePreprocessor(image_size=image_size).to(device, dtype)++ # Test with single image (3D tensor) - preprocessor adds batch dimension+ image = torch.randint(0, 255, (3, 256, 256), device=device, dtype=dtype)+ with torch.no_grad():+ output = preprocessor(image)+ assert output.shape == (1, 3, image_size[0], image_size[1])