π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
added-naflex-feature as an independent module (#3451)
Mandeep Singhc775c33ffa06
diff --git a/kornia/models/processors.py b/kornia/models/processors.pydeleted file mode 100644index 2f82572ba..000000000--- a/kornia/models/processors.py+++ /dev/null@@ -1,128 +0,0 @@-# LICENSE HEADER MANAGED BY add-license-header-#-# Copyright 2018 Kornia Team-#-# Licensed under the Apache License, Version 2.0 (the "License");-# you may not use this file except in compliance with the License.-# You may obtain a copy of the License at-#-# http://www.apache.org/licenses/LICENSE-2.0-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License.-#--import warnings-from typing import List, Tuple, Union--import torch-from torch import nn--from kornia.geometry.transform import resize--__all__ = ["OutputRangePostProcessor", "ResizePostProcessor", "ResizePreProcessor"]---class ResizePreProcessor(nn.Module):- """Resize a list of image tensors to the given size.-- Additionally, also returns the original image sizes for further post-processing.- """-- def __init__(self, height: int, width: int, interpolation_mode: str = "bilinear") -> None:- """Construct ResizePreprocessor module.-- Args:- height: height of the resized image.- width: width of the resized image.- interpolation_mode: interpolation mode for image resizing. Supported values: ``nearest``, ``bilinear``,- ``bicubic``, ``area``, and ``nearest-exact``.-- """- super().__init__()- self.size = (height, width)- self.interpolation_mode = interpolation_mode-- def forward(self, imgs: Union[torch.Tensor, List[torch.Tensor]]) -> Tuple[torch.Tensor, torch.Tensor]:- """Run forward.-- Returns:- resized_imgs: resized images in a batch.- original_sizes: the original image sizes of (height, width).-- """- # TODO: support other input formats e.g. file path, numpy- resized_imgs: list[torch.Tensor] = []-- iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]- original_sizes = imgs[0].new_zeros((iters, 2))- for i in range(iters):- img = imgs[i]- original_sizes[i, 0] = img.shape[-2] # Height- original_sizes[i, 1] = img.shape[-1] # Width- resized_imgs.append(resize(img[None], size=self.size, interpolation=self.interpolation_mode))- return torch.cat(resized_imgs), original_sizes---class ResizePostProcessor(nn.Module):- """Rescale model outputs back to the original image dimensions.-- Args:- interpolation_mode: The algorithm used for upsampling. Default: "bilinear".- """-- def __init__(self, interpolation_mode: str = "bilinear") -> None:- super().__init__()- self.interpolation_mode = interpolation_mode-- def forward(- self, imgs: Union[torch.Tensor, List[torch.Tensor]], original_sizes: torch.Tensor- ) -> Union[torch.Tensor, List[torch.Tensor]]:- """Run forward.-- Returns:- resized_imgs: resized images in a batch.- original_sizes: the original image sizes of (height, width).-- """- # TODO: support other input formats e.g. file path, numpy- resized_imgs: list[torch.Tensor] = []-- if torch.onnx.is_in_onnx_export():- warnings.warn(- "ResizePostProcessor is not supported in ONNX export. "- "The output will not be resized back to the original size.",- stacklevel=1,- )- return imgs-- iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]- for i in range(iters):- img = imgs[i]- size = original_sizes[i]- resized_imgs.append(- resize(img[None], size=size.cpu().long().numpy().tolist(), interpolation=self.interpolation_mode)- )- return resized_imgs---class OutputRangePostProcessor(nn.Module):- """Clip and scale model outputs to a specific numerical range.-- Args:- min_val: The minimum value for clipping. Default: 0.0.- max_val: The maximum value for clipping. Default: 1.0.- """-- def __init__(self, min_val: float = 0.0, max_val: float = 1.0) -> None:- super().__init__()- self.min_val = min_val- self.max_val = max_val-- def forward(self, imgs: Union[torch.Tensor, List[torch.Tensor]]) -> Union[torch.Tensor, List[torch.Tensor]]:- if isinstance(imgs, torch.Tensor):- return torch.clamp(imgs, self.min_val, self.max_val)- return [img.clamp_(self.min_val, self.max_val) for img in imgs]diff --git a/kornia/models/processors/__init__.py b/kornia/models/processors/__init__.pynew file mode 100644index 000000000..eabfb1ed4--- /dev/null+++ b/kornia/models/processors/__init__.py@@ -0,0 +1,181 @@+# 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.+#+from typing import List, Tuple, Union++import torch+from torch import Tensor, nn++from kornia.geometry.transform import resize++from .naflex import NaFlex++__all__ = [+ "NaFlex",+ "OutputRangePostProcessor",+ "ResizePostProcessor",+ "ResizePreProcessor",+]+++class ResizePreProcessor(nn.Module):+ r"""Resize a list of image tensors to the given size.++ Additionally, also returns the original image sizes for further post-processing.++ Args:+ height: Height of the resized image.+ width: Width of the resized image.+ interpolation_mode: Interpolation mode for image resizing. Supported values:+ ``nearest``, ``bilinear``, ``bicubic``, ``area``, ``nearest-exact``.+ Default: "bilinear".++ Example:+ >>> import torch+ >>> from kornia.models.processors import ResizePreProcessor+ >>> processor = ResizePreProcessor(height=224, width=224)+ >>> imgs = torch.randn(2, 3, 480, 640)+ >>> resized, sizes = processor(imgs)+ >>> print(resized.shape, sizes.shape)+ torch.Size([2, 3, 224, 224]) torch.Size([2, 2])+ """++ def __init__(self, height: int, width: int, interpolation_mode: str = "bilinear") -> None:+ super().__init__()+ self.size = (height, width)+ self.interpolation_mode = interpolation_mode++ def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Tuple[Tensor, Tensor]:+ r"""Resize input images to the target size.++ Args:+ imgs: Input images, either a tensor of shape :math:`(B, C, H, W)` or+ a list of tensors of shape :math:`(C, H, W)`.++ Returns:+ Tuple containing:+ - resized_imgs: Resized images as a tensor of shape :math:`(B, C, H_{\text{new}}, W_{\text{new}})`.+ - original_sizes: Original image sizes of shape :math:`(B, 2)` containing (height, width).+ """+ resized_imgs: List[Tensor] = []++ iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]+ original_sizes = imgs[0].new_zeros((iters, 2))++ for i in range(iters):+ img = imgs[i]+ original_sizes[i, 0] = img.shape[-2] # Height+ original_sizes[i, 1] = img.shape[-1] # Width+ resized_imgs.append(resize(img[None], size=self.size, interpolation=self.interpolation_mode))++ return torch.cat(resized_imgs), original_sizes+++class ResizePostProcessor(nn.Module):+ r"""Rescale model outputs back to the original image dimensions.++ Args:+ interpolation_mode: The algorithm used for upsampling. Supported values:+ ``nearest``, ``bilinear``, ``bicubic``, ``area``, ``nearest-exact``.+ Default: "bilinear".++ Example:+ >>> import torch+ >>> from kornia.models.processors import ResizePostProcessor+ >>> processor = ResizePostProcessor()+ >>> imgs = torch.randn(2, 3, 224, 224)+ >>> original_sizes = torch.tensor([[480, 640], [360, 480]])+ >>> out = processor(imgs, original_sizes)+ """++ def __init__(self, interpolation_mode: str = "bilinear") -> None:+ super().__init__()+ self.interpolation_mode = interpolation_mode++ def forward(self, imgs: Union[Tensor, List[Tensor]], original_sizes: Tensor) -> Union[Tensor, List[Tensor]]:+ r"""Resize model outputs back to original dimensions.++ Args:+ imgs: Input images, either a tensor of shape :math:`(B, C, H, W)` or+ a list of tensors of shape :math:`(C, H, W)`.+ original_sizes: Original image sizes of shape :math:`(B, 2)` containing+ (height, width) pairs.++ Returns:+ Resized images in a batch with original dimensions. If ONNX export is active,+ returns inputs unchanged with a warning.++ Warning:+ ResizePostProcessor is not fully supported in ONNX export mode.+ """+ import warnings++ resized_imgs: List[Tensor] = []++ if torch.onnx.is_in_onnx_export():+ warnings.warn(+ "ResizePostProcessor is not supported in ONNX export. "+ "The output will not be resized back to the original size.",+ stacklevel=2,+ )+ return imgs++ iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]++ for i in range(iters):+ img = imgs[i]+ size = original_sizes[i]+ resized_imgs.append(+ resize(img[None], size=size.cpu().long().numpy().tolist(), interpolation=self.interpolation_mode)+ )++ return resized_imgs+++class OutputRangePostProcessor(nn.Module):+ r"""Clip and scale model outputs to a specific numerical range.++ Args:+ min_val: Minimum value for clipping. Default: 0.0.+ max_val: Maximum value for clipping. Default: 1.0.++ Example:+ >>> import torch+ >>> from kornia.models.processors import OutputRangePostProcessor+ >>> processor = OutputRangePostProcessor(min_val=0.0, max_val=1.0)+ >>> x = torch.randn(2, 3, 224, 224)+ >>> out = processor(x)+ >>> print(out.min(), out.max())+ tensor(0.) tensor(1.)+ """++ def __init__(self, min_val: float = 0.0, max_val: float = 1.0) -> None:+ super().__init__()+ self.min_val = min_val+ self.max_val = max_val++ def forward(self, imgs: Union[Tensor, List[Tensor]]) -> Union[Tensor, List[Tensor]]:+ r"""Clip output values to the specified range.++ Args:+ imgs: Input images, either a tensor or list of tensors.++ Returns:+ Clipped images with values in :math:`[\text{min\_val}, \text{max\_val}]`.+ """+ if isinstance(imgs, torch.Tensor):+ return torch.clamp(imgs, self.min_val, self.max_val)+ return [img.clamp(self.min_val, self.max_val) for img in imgs]diff --git a/kornia/models/processors/naflex.py b/kornia/models/processors/naflex.pynew file mode 100644index 000000000..1bb350d90--- /dev/null+++ b/kornia/models/processors/naflex.py@@ -0,0 +1,93 @@+# 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.+#+from __future__ import annotations++import math+from typing import Callable++from torch import Tensor, nn+from torch.nn import functional as F++__all__ = ["NaFlex"]+++class NaFlex(nn.Module):+ r"""NaFlex wrapper for vision embeddings that supports flexible image sizes.++ This module wraps a patch embedding function and a position embedding tensor.+ It computes patch embeddings and dynamically interpolates the position embeddings+ to match the input resolution using bilinear interpolation.++ Args:+ patch_embedding_fcn: A callable (e.g., Conv2d) that takes images and returns+ patch embeddings of shape :math:`(B, C, H, W)` or :math:`(B, N, C)`.+ position_embedding: Position embedding tensor of shape :math:`(N, C)` to be+ interpolated to match input resolution.++ Example:+ >>> import torch+ >>> from kornia.models.processors.naflex import NaFlex+ >>> patch_fcn = torch.nn.Conv2d(3, 768, kernel_size=16, stride=16)+ >>> pos_embed = torch.randn(196, 768) # 14x14 grid+ >>> model = NaFlex(patch_fcn, pos_embed)+ >>> x = torch.randn(1, 3, 224, 224)+ >>> out = model(x)+ >>> print(out.shape)+ torch.Size([1, 196, 768])+ """++ def __init__(+ self,+ patch_embedding_fcn: Callable[[Tensor], Tensor],+ position_embedding: Tensor,+ ) -> None:+ super().__init__()+ self.patch_embedding_fcn = patch_embedding_fcn+ self.register_buffer("position_embedding", position_embedding)++ def forward(self, pixel_values: Tensor) -> Tensor:+ r"""Forward pass through NaFlex wrapper.++ Args:+ pixel_values: Input tensor of shape :math:`(B, C, H, W)`.++ Returns:+ Embeddings with interpolated positional embeddings of shape :math:`(B, N, C)`.++ Raises:+ ValueError: If original positional embedding does not form a square grid.+ """+ embeddings = self.patch_embedding_fcn(pixel_values)+ if embeddings.ndim == 4:+ _, _, h_grid, w_grid = embeddings.shape+ embeddings = embeddings.flatten(2).transpose(1, 2)+ num_patches = h_grid * w_grid+ else:+ _, num_patches, _ = embeddings.shape+ h_grid = int(math.sqrt(num_patches))+ w_grid = h_grid+ if self.position_embedding.shape[0] == num_patches:+ return embeddings + self.position_embedding.unsqueeze(0)+ orig_num = int(self.position_embedding.shape[0])+ orig_grid = int(math.sqrt(orig_num))+ if orig_grid * orig_grid != orig_num:+ raise ValueError(f"Original positional embedding is not a square grid (got {orig_num} embeddings)")+ pos = self.position_embedding.view(orig_grid, orig_grid, -1).permute(2, 0, 1).unsqueeze(0)+ pos_resized = F.interpolate(pos, size=(h_grid, w_grid), mode="bilinear", align_corners=False)+ pos_resized = pos_resized.squeeze(0).permute(1, 2, 0).view(h_grid * w_grid, -1)++ return embeddings + pos_resized.unsqueeze(0)diff --git a/kornia/models/siglip2/__init__.py b/kornia/models/siglip2/__init__.pyindex 1d451030e..4c2af72d7 100644--- a/kornia/models/siglip2/__init__.py+++ b/kornia/models/siglip2/__init__.py@@ -22,4 +22,10 @@ from .config import SigLip2Configfrom .model import SigLip2Model, SigLip2Resultfrom .preprocessor import SigLip2ImagePreprocessor-__all__ = ["SigLip2Builder", "SigLip2Config", "SigLip2ImagePreprocessor", "SigLip2Model", "SigLip2Result"]+__all__ = [+ "SigLip2Builder",+ "SigLip2Config",+ "SigLip2ImagePreprocessor",+ "SigLip2Model",+ "SigLip2Result",+]diff --git a/tests/models/test_naflex.py b/tests/models/test_naflex.pynew file mode 100644index 000000000..687ef0702--- /dev/null+++ b/tests/models/test_naflex.py@@ -0,0 +1,96 @@+# 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.+#+import pytest+import torch+from torch import Tensor++from kornia.models.processors.naflex import NaFlex++from testing.base import BaseTester+++class TestNaFlex(BaseTester):+ @pytest.fixture+ def model(self) -> NaFlex:+ """Create a NaFlex model with mock embeddings for testing.++ Returns:+ NaFlex instance with mock patch embedding function and position embedding.+ """++ def mock_patch_embedding(x: Tensor) -> Tensor:+ """Mock patch embedding function simulating Conv2d output.++ Dynamically calculates output size based on patch_size=16.+ """+ B, _, H, W = x.shape+ h_out = H // 16+ w_out = W // 16+ return torch.randn(B, 768, h_out, w_out, dtype=x.dtype, device=x.device)++ position_embedding = torch.randn(196, 768)+ return NaFlex(+ patch_embedding_fcn=mock_patch_embedding,+ position_embedding=position_embedding,+ )++ def test_smoke(self, model: NaFlex, device: torch.device, dtype: torch.dtype) -> None:+ """Test basic forward pass with standard input."""+ input_data = torch.randn(1, 3, 224, 224, device=device, dtype=dtype)+ out = model(input_data)+ assert isinstance(out, Tensor)+ assert out.shape == (1, 196, 768)++ def test_cardinality(self, model: NaFlex, device: torch.device, dtype: torch.dtype) -> None:+ """Test output cardinality with non-square input resolution.++ For 224x320 input with 16x16 patches, expect 14x20=280 patches.+ """+ input_data = torch.randn(1, 3, 224, 320, device=device, dtype=dtype)+ out = model(input_data)+ assert out.shape[0] == 1+ assert out.shape[1] == 280+ assert out.shape[2] == 768++ def test_exception(self, device: torch.device, dtype: torch.dtype) -> None:+ """Test that invalid position embeddings raise appropriate errors."""++ def fake_patch_fcn(x: Tensor) -> Tensor:+ return torch.randn(1, 100, 768, device=device, dtype=dtype)++ bad_pos_embed = torch.randn(200, 768, device=device, dtype=dtype)+ wrapper_bad = NaFlex(fake_patch_fcn, bad_pos_embed)+ input_data = torch.randn(1, 3, 224, 224, device=device, dtype=dtype)++ with pytest.raises(ValueError, match="Original positional embedding is not a square grid"):+ wrapper_bad(input_data)++ def test_interpolation(self, device: torch.device, dtype: torch.dtype) -> None:+ """Test positional embedding interpolation for different input sizes."""++ def mock_patch_embedding_dynamic(x: Tensor) -> Tensor:+ """Dynamic mock for resizing tests."""+ B, _, H, W = x.shape+ h_out = H // 16+ w_out = W // 16+ return torch.randn(B, 768, h_out, w_out, dtype=x.dtype, device=x.device)++ position_embedding = torch.randn(196, 768)+ model = NaFlex(mock_patch_embedding_dynamic, position_embedding)+ input_448 = torch.randn(1, 3, 448, 448, device=device, dtype=dtype)+ out = model(input_448)+ assert out.shape == (1, 784, 768)