Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add EfficientViT model (#2607)

Edgar Ribae42641235199
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index f4dbd1062..dc9f42865 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -12,6 +12,40 @@ Base
:members:
:undoc-members:
+EfficientViT
+^^^^^^^^^^^^
+
+.. autoclass:: kornia.contrib.models.efficient_vit.EfficientViT
+ :members: from_config, forward, load_checkpoint
+ :undoc-members:
+ :special-members: __init__,
+
+
+.. autoclass:: kornia.contrib.models.efficient_vit.EfficientViTConfig
+ :members:
+ :undoc-members:
+
+Backbones
+^^^^^^^^^
+
+.. autoclass:: kornia.contrib.models.efficient_vit.backbone.EfficientViTBackbone
+ :members:
+ :undoc-members:
+
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b0
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b1
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b2
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_b3
+
+.. autoclass:: kornia.contrib.models.efficient_vit.backbone.EfficientViTLargeBackbone
+ :members:
+ :undoc-members:
+
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l0
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l1
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l2
+.. autofunction:: kornia.contrib.models.efficient_vit.backbone.efficientvit_backbone_l3
+
Structures
^^^^^^^^^^
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 2a55c30a6..d8e3adc50 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -93,6 +93,7 @@ Join the community
:caption: KORNIA MODELS
:hidden:
+ models/efficient_vit
models/rt_detr
models/segment_anything
models/mobile_sam
diff --git a/docs/source/models/efficient_vit.rst b/docs/source/models/efficient_vit.rst
new file mode 100644
index 000000000..82d789e85
--- /dev/null
+++ b/docs/source/models/efficient_vit.rst
@@ -0,0 +1,16 @@
+EfficientViT
+============
+
+.. card::
+ :link: https://arxiv.org/abs/2205.14756
+
+ **EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction**
+ ^^^
+ **Abstract:** High-resolution dense prediction enables many appealing real-world applications, such as computational photography, autonomous driving, etc. However, the vast computational cost makes deploying state-of-the-art high-resolution dense prediction models on hardware devices difficult. This work presents EfficientViT, a new family of high-resolution vision models with novel multi-scale linear attention. Unlike prior high-resolution dense prediction models that rely on heavy softmax attention, hardware-inefficient large-kernel convolution, or complicated topology structure to obtain good performances, our multi-scale linear attention achieves the global receptive field and multi-scale learning (two desirable features for high-resolution dense prediction) with only lightweight and hardware-efficient operations. As such, EfficientViT delivers remarkable performance gains over previous state-of-the-art models with significant speedup on diverse hardware platforms, including mobile CPU, edge GPU, and cloud GPU. Without performance loss on Cityscapes, our EfficientViT provides up to 13.9x and 6.2x GPU latency reduction over SegFormer and SegNeXt, respectively. For super-resolution, EfficientViT delivers up to 6.4x speedup over Restormer while providing 0.11dB gain in PSNR. For Segment Anything, EfficientViT delivers similar zero-shot image segmentation quality as ViT-Huge with 84x higher throughput on GPU. Code: this https URL.
+
+ **Tasks:** Classification, Segmentation, Detection
+
+ **Licence:** Apache 2.0
+
+ +++
+ **Authors:** Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
diff --git a/kornia/contrib/models/efficient_vit/__init__.py b/kornia/contrib/models/efficient_vit/__init__.py
new file mode 100644
index 000000000..51fe548c7
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/__init__.py
@@ -0,0 +1,3 @@
+from .model import EfficientViT, EfficientViTConfig
+
+__all__ = ["EfficientViT", "EfficientViTConfig"]
diff --git a/kornia/contrib/models/efficient_vit/backbone.py b/kornia/contrib/models/efficient_vit/backbone.py
new file mode 100644
index 000000000..b76c80777
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/backbone.py
@@ -0,0 +1,342 @@
+# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction
+# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
+# International Conference on Computer Vision (ICCV), 2023
+from __future__ import annotations
+
+from typing import Any
+
+import torch
+from torch import nn
+
+from kornia.contrib.models.efficient_vit.nn.ops import ( # type: ignore
+ ConvLayer,
+ DSConv,
+ EfficientViTBlock,
+ FusedMBConv,
+ IdentityLayer,
+ MBConv,
+ OpSequential,
+ ResBlock,
+ ResidualBlock,
+)
+from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config
+
+
+class EfficientViTBackbone(nn.Module):
+ def __init__(
+ self,
+ width_list: list[int],
+ depth_list: list[int],
+ in_channels: int = 3,
+ dim: int = 32,
+ expand_ratio: float = 4,
+ norm: str = "bn2d",
+ act_func: str = "hswish",
+ ) -> None:
+ super().__init__()
+
+ self.width_list = []
+ # input stem
+ input_stem = [
+ ConvLayer(in_channels=in_channels, out_channels=width_list[0], stride=2, norm=norm, act_func=act_func)
+ ]
+ for _ in range(depth_list[0]):
+ block = self.build_local_block(
+ in_channels=width_list[0],
+ out_channels=width_list[0],
+ stride=1,
+ expand_ratio=1,
+ norm=norm,
+ act_func=act_func,
+ )
+ input_stem.append(ResidualBlock(block, IdentityLayer()))
+ in_channels = width_list[0]
+ self.input_stem = OpSequential(input_stem)
+ self.width_list.append(in_channels)
+
+ # stages
+ stages = []
+ for w, d in zip(width_list[1:3], depth_list[1:3]):
+ stage = []
+ for i in range(d):
+ stride = 2 if i == 0 else 1
+ block = self.build_local_block(
+ in_channels=in_channels,
+ out_channels=w,
+ stride=stride,
+ expand_ratio=expand_ratio,
+ norm=norm,
+ act_func=act_func,
+ )
+ block = ResidualBlock(block, IdentityLayer() if stride == 1 else None)
+ stage.append(block)
+ in_channels = w
+ stages.append(OpSequential(stage))
+ self.width_list.append(in_channels)
+
+ for w, d in zip(width_list[3:], depth_list[3:]):
+ stage = []
+ block = self.build_local_block(
+ in_channels=in_channels,
+ out_channels=w,
+ stride=2,
+ expand_ratio=expand_ratio,
+ norm=norm,
+ act_func=act_func,
+ fewer_norm=True,
+ )
+ stage.append(ResidualBlock(block, None))
+ in_channels = w
+
+ for _ in range(d):
+ stage.append(
+ EfficientViTBlock(
+ in_channels=in_channels, dim=dim, expand_ratio=expand_ratio, norm=norm, act_func=act_func
+ )
+ )
+ stages.append(OpSequential(stage))
+ self.width_list.append(in_channels)
+ self.stages = nn.ModuleList(stages)
+
+ @staticmethod
+ def build_local_block(
+ in_channels: int,
+ out_channels: int,
+ stride: int,
+ expand_ratio: float,
+ norm: str,
+ act_func: str,
+ fewer_norm: bool = False,
+ ) -> nn.Module:
+ if expand_ratio == 1:
+ block = DSConv(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ stride=stride,
+ use_bias=(True, False) if fewer_norm else False,
+ norm=(None, norm) if fewer_norm else norm,
+ act_func=(act_func, None),
+ )
+ else:
+ block = MBConv(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ stride=stride,
+ expand_ratio=expand_ratio,
+ use_bias=(True, True, False) if fewer_norm else False,
+ norm=(None, None, norm) if fewer_norm else norm,
+ act_func=(act_func, act_func, None),
+ )
+ return block
+
+ def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
+ output_dict = {"input": x}
+ output_dict["stage0"] = x = self.input_stem(x)
+ for stage_id, stage in enumerate(self.stages, 1):
+ output_dict["stage%d" % stage_id] = x = stage(x)
+ output_dict["stage_final"] = x
+ return output_dict
+
+
+def efficientvit_backbone_b0(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
+ backbone = EfficientViTBackbone(
+ width_list=[8, 16, 32, 64, 128],
+ depth_list=[1, 2, 2, 2, 2],
+ dim=16,
+ **build_kwargs_from_config(kwargs, EfficientViTBackbone),
+ )
+ return backbone
+
+
+def efficientvit_backbone_b1(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
+ backbone = EfficientViTBackbone(
+ width_list=[16, 32, 64, 128, 256],
+ depth_list=[1, 2, 3, 3, 4],
+ dim=16,
+ **build_kwargs_from_config(kwargs, EfficientViTBackbone),
+ )
+ return backbone
+
+
+def efficientvit_backbone_b2(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
+ backbone = EfficientViTBackbone(
+ width_list=[24, 48, 96, 192, 384],
+ depth_list=[1, 3, 4, 4, 6],
+ dim=32,
+ **build_kwargs_from_config(kwargs, EfficientViTBackbone),
+ )
+ return backbone
+
+
+def efficientvit_backbone_b3(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
+ backbone = EfficientViTBackbone(
+ width_list=[32, 64, 128, 256, 512],
+ depth_list=[1, 4, 6, 6, 9],
+ dim=32,
+ **build_kwargs_from_config(kwargs, EfficientViTBackbone),
+ )
+ return backbone
+
+
+class EfficientViTLargeBackbone(nn.Module):
+ def __init__(
+ self,
+ width_list: list[int],
+ depth_list: list[int],
+ in_channels: int = 3,
+ qkv_dim: int = 32,
+ norm: str = "bn2d",
+ act_func: str = "gelu",
+ ) -> None:
+ super().__init__()
+
+ self.width_list = []
+ stages = []
+ # stage 0
+ stage0 = [
+ ConvLayer(in_channels=in_channels, out_channels=width_list[0], stride=2, norm=norm, act_func=act_func)
+ ]
+ for _ in range(depth_list[0]):
+ block = self.build_local_block(
+ stage_id=0,
+ in_channels=width_list[0],
+ out_channels=width_list[0],
+ stride=1,
+ expand_ratio=1,
+ norm=norm,
+ act_func=act_func,
+ )
+ stage0.append(ResidualBlock(block, IdentityLayer()))
+ in_channels = width_list[0]
+ stages.append(OpSequential(stage0))
+ self.width_list.append(in_channels)
+
+ for stage_id, (w, d) in enumerate(zip(width_list[1:4], depth_list[1:4]), start=1):
+ stage = []
+ for i in range(d + 1):
+ stride = 2 if i == 0 else 1
+ block = self.build_local_block(
+ stage_id=stage_id,
+ in_channels=in_channels,
+ out_channels=w,
+ stride=stride,
+ expand_ratio=4 if stride == 1 else 16,
+ norm=norm,
+ act_func=act_func,
+ fewer_norm=stage_id > 2,
+ )
+ block = ResidualBlock(block, IdentityLayer() if stride == 1 else None)
+ stage.append(block)
+ in_channels = w
+ stages.append(OpSequential(stage))
+ self.width_list.append(in_channels)
+
+ for stage_id, (w, d) in enumerate(zip(width_list[4:], depth_list[4:]), start=4):
+ stage = []
+ block = self.build_local_block(
+ stage_id=stage_id,
+ in_channels=in_channels,
+ out_channels=w,
+ stride=2,
+ expand_ratio=24,
+ norm=norm,
+ act_func=act_func,
+ fewer_norm=True,
+ )
+ stage.append(ResidualBlock(block, None))
+ in_channels = w
+
+ for _ in range(d):
+ stage.append(
+ EfficientViTBlock(
+ in_channels=in_channels, dim=qkv_dim, expand_ratio=6, norm=norm, act_func=act_func
+ )
+ )
+ stages.append(OpSequential(stage))
+ self.width_list.append(in_channels)
+ self.stages = nn.ModuleList(stages)
+
+ @staticmethod
+ def build_local_block(
+ stage_id: int,
+ in_channels: int,
+ out_channels: int,
+ stride: int,
+ expand_ratio: float,
+ norm: str,
+ act_func: str,
+ fewer_norm: bool = False,
+ ) -> nn.Module:
+ if expand_ratio == 1:
+ block = ResBlock(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ stride=stride,
+ use_bias=(True, False) if fewer_norm else False,
+ norm=(None, norm) if fewer_norm else norm,
+ act_func=(act_func, None),
+ )
+ elif stage_id <= 2:
+ block = FusedMBConv(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ stride=stride,
+ expand_ratio=expand_ratio,
+ use_bias=(True, False) if fewer_norm else False,
+ norm=(None, norm) if fewer_norm else norm,
+ act_func=(act_func, None),
+ )
+ else:
+ block = MBConv(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ stride=stride,
+ expand_ratio=expand_ratio,
+ use_bias=(True, True, False) if fewer_norm else False,
+ norm=(None, None, norm) if fewer_norm else norm,
+ act_func=(act_func, act_func, None),
+ )
+ return block
+
+ def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
+ output_dict = {"input": x}
+ for stage_id, stage in enumerate(self.stages):
+ output_dict["stage%d" % stage_id] = x = stage(x)
+ output_dict["stage_final"] = x
+ return output_dict
+
+
+def efficientvit_backbone_l0(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
+ backbone = EfficientViTLargeBackbone(
+ width_list=[32, 64, 128, 256, 512],
+ depth_list=[1, 1, 1, 4, 4],
+ **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
+ )
+ return backbone
+
+
+def efficientvit_backbone_l1(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
+ backbone = EfficientViTLargeBackbone(
+ width_list=[32, 64, 128, 256, 512],
+ depth_list=[1, 1, 1, 6, 6],
+ **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
+ )
+ return backbone
+
+
+def efficientvit_backbone_l2(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
+ backbone = EfficientViTLargeBackbone(
+ width_list=[32, 64, 128, 256, 512],
+ depth_list=[1, 2, 2, 8, 8],
+ **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
+ )
+ return backbone
+
+
+def efficientvit_backbone_l3(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
+ backbone = EfficientViTLargeBackbone(
+ width_list=[64, 128, 256, 512, 1024],
+ depth_list=[1, 2, 2, 8, 8],
+ **build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
+ )
+ return backbone
diff --git a/kornia/contrib/models/efficient_vit/model.py b/kornia/contrib/models/efficient_vit/model.py
new file mode 100644
index 000000000..3e3720b8e
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/model.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal
+
+import torch
+
+from kornia.contrib.models.base import ModelBase
+from kornia.contrib.models.efficient_vit import backbone as vit
+from kornia.core import Tensor
+
+
+def _get_base_url(model_type: Literal["b1", "b2", "b3"] = "b1", resolution: Literal[224, 256, 288] = 224) -> str:
+ """Return the base URL of the model weights."""
+ return f"https://huggingface.co/kornia/efficientvit_imagenet_{model_type}_r{resolution}/resolve/main/{model_type}-r{resolution}.pt"
+
+
+@dataclass
+class EfficientViTConfig:
+ """Configuration to construct EfficientViT model.
+
+ Model weights can be loaded from a checkpoint URL or local path.
+ The model weights are hosted on HuggingFace's model hub: https://huggingface.co/kornia.
+
+ Args:
+ checkpoint: URL or local path of model weights.
+ """
+
+ checkpoint: str = field(default_factory=_get_base_url)
+
+ @classmethod
+ def from_pretrained(
+ cls, model_type: Literal["b1", "b2", "b3"], resolution: Literal[224, 256, 288]
+ ) -> EfficientViTConfig:
+ """Return a configuration object from a pre-trained model.
+
+ Args:
+ model_type: model type, one of :obj:`"b1"`, :obj:`"b2"`, :obj:`"b3"`.
+ resolution: input resolution, one of :obj:`224`, :obj:`256`, :obj:`288`.
+ """
+ return cls(checkpoint=_get_base_url(model_type=model_type, resolution=resolution))
+
+
+class EfficientViT(ModelBase[EfficientViTConfig]):
+ """EfficientViT backbone model."""
+
+ def __init__(self, backbone: vit.EfficientViTBackbone | vit.EfficientViTLargeBackbone) -> None:
+ super().__init__()
+ self.backbone = backbone
+
+ @staticmethod
+ def from_config(config: EfficientViTConfig) -> EfficientViT:
+ """Build the EfficientViT model from a configuration object.
+
+ Args:
+ config: EfficientViT configuration object. See :class:`EfficientViTConfig`.
+
+ Returns:
+ EfficientViT: the EfficientViT model.
+ """
+ # load the model from the checkpoint
+ try:
+ model_file = torch.hub.load_state_dict_from_url(config.checkpoint, map_location="cpu")
+ model_file = model_file["state_dict"] if "state_dict" in model_file else model_file
+ except RuntimeError:
+ raise RuntimeError(f"Unable to load the model from {config.checkpoint}.")
+
+ file_name = config.checkpoint.split("/")[-1]
+ model_type = file_name.split("-")[0]
+
+ if model_type not in ["b0", "b1", "b2", "b3", "l0", "l1", "l2", "l3"]:
+ raise ValueError(f"Unknown model type: {model_type}.")
+
+ # create and load the model weights without strict until we polish the model files
+ model = getattr(vit, f"efficientvit_backbone_{model_type}")()
+ model.load_state_dict(model_file, strict=False)
+
+ return EfficientViT(backbone=model)
+
+ def forward(self, images: Tensor) -> Tensor:
+ """Extract features from the input images.
+
+ Args:
+ images: input images tensor of shape :math:`(B, C, H, W)`.
+
+ Returns:
+ Dict[str, Tensor]: a dictionary containing the features.
+ """
+ feats = self.backbone(images)
+ return feats
diff --git a/kornia/contrib/models/efficient_vit/nn/__init__.py b/kornia/contrib/models/efficient_vit/nn/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/kornia/contrib/models/efficient_vit/nn/act.py b/kornia/contrib/models/efficient_vit/nn/act.py
new file mode 100644
index 000000000..444d5b697
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/nn/act.py
@@ -0,0 +1,29 @@
+# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction
+# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
+# International Conference on Computer Vision (ICCV), 2023
+from __future__ import annotations
+
+from functools import partial
+from typing import Any, Optional, Union
+
+from torch import nn
+
+from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config
+
+# register activation function here
+REGISTERED_ACT_DICT: dict[str, type[nn.Module]] = {
+ "relu": nn.ReLU,
+ "relu6": nn.ReLU6,
+ "hswish": nn.Hardswish,
+ "silu": nn.SiLU,
+ "gelu": partial(nn.GELU, approximate="tanh"), # type: ignore
+}
+
+
+def build_act(name: Optional[str], **kwargs: dict[str, Any]) -> Union[nn.Module, None]:
+ if name in REGISTERED_ACT_DICT:
+ act_cls = REGISTERED_ACT_DICT[name]
+ args = build_kwargs_from_config(kwargs, act_cls)
+ return act_cls(**args)
+
+ return None
diff --git a/kornia/contrib/models/efficient_vit/nn/norm.py b/kornia/contrib/models/efficient_vit/nn/norm.py
new file mode 100644
index 000000000..45c3165f9
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/nn/norm.py
@@ -0,0 +1,37 @@
+# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction
+# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
+# International Conference on Computer Vision (ICCV), 2023
+from __future__ import annotations
+
+from typing import Any, Optional
+
+import torch
+from torch import nn
+
+from kornia.contrib.models.efficient_vit.utils import build_kwargs_from_config
+
+
+class LayerNorm2d(nn.LayerNorm):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ out = x - torch.mean(x, dim=1, keepdim=True)
+ out = out / torch.sqrt(torch.square(out).mean(dim=1, keepdim=True) + self.eps)
+ if self.elementwise_affine:
+ out = out * self.weight.view(1, -1, 1, 1) + self.bias.view(1, -1, 1, 1)
+ return out
+
+
+# register normalization function here
+REGISTERED_NORM_DICT: dict[str, type] = {"bn2d": nn.BatchNorm2d, "ln": nn.LayerNorm, "ln2d": LayerNorm2d}
+
+
+def build_norm(name: str = "bn2d", num_features: Optional[int] = None, **kwargs: Any) -> Optional[nn.Module]:
+ if name in ["ln", "ln2d"]:
+ kwargs["normalized_shape"] = num_features
+ else:
+ kwargs["num_features"] = num_features
+ if name in REGISTERED_NORM_DICT:
+ norm_cls = REGISTERED_NORM_DICT[name]
+ args = build_kwargs_from_config(kwargs, norm_cls)
+ return norm_cls(**args)
+ else:
+ return None
diff --git a/kornia/contrib/models/efficient_vit/nn/ops.py b/kornia/contrib/models/efficient_vit/nn/ops.py
new file mode 100644
index 000000000..2eecc705a
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/nn/ops.py
@@ -0,0 +1,414 @@
+# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction
+# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
+# International Conference on Computer Vision (ICCV), 2023
+
+# type: ignore
+from __future__ import annotations
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torch.cuda.amp import autocast
+
+from kornia.contrib.models.efficient_vit.nn.act import build_act
+from kornia.contrib.models.efficient_vit.nn.norm import build_norm
+from kornia.contrib.models.efficient_vit.utils import get_same_padding, val2tuple
+
+__all__ = [
+ "ConvLayer",
+ "DSConv",
+ "EfficientViTBlock",
+ "FusedMBConv",
+ "IdentityLayer",
+ "MBConv",
+ "OpSequential",
+ "ResBlock",
+ "ResidualBlock",
+]
+
+#################################################################################
+# Basic Layers #
+#################################################################################
+
+
+class ConvLayer(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size=3,
+ stride=1,
+ dilation=1,
+ groups=1,
+ use_bias=False,
+ dropout=0,
+ norm="bn2d",
+ act_func="relu",
+ ):
+ super().__init__()
+
+ padding = get_same_padding(kernel_size)
+ padding *= dilation
+
+ self.dropout = nn.Dropout2d(dropout, inplace=False) if dropout > 0 else None
+ self.conv = nn.Conv2d(
+ in_channels,
+ out_channels,
+ kernel_size=(kernel_size, kernel_size),
+ stride=(stride, stride),
+ padding=padding,
+ dilation=(dilation, dilation),
+ groups=groups,
+ bias=use_bias,
+ )
+ self.norm = build_norm(norm, num_features=out_channels)
+ self.act = build_act(act_func)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.dropout is not None:
+ x = self.dropout(x)
+ x = self.conv(x)
+ if self.norm:
+ x = self.norm(x)
+ if self.act:
+ x = self.act(x)
+ return x
+
+
+class IdentityLayer(nn.Module):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return x
+
+
+#################################################################################
+# Basic Blocks #
+#################################################################################
+
+
+class DSConv(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size=3,
+ stride=1,
+ use_bias=False,
+ norm=("bn2d", "bn2d"),
+ act_func=("relu6", None),
+ ):
+ super().__init__()
+
+ use_bias = val2tuple(use_bias, 2)
+ norm = val2tuple(norm, 2)
+ act_func = val2tuple(act_func, 2)
+
+ self.depth_conv = ConvLayer(
+ in_channels,
+ in_channels,
+ kernel_size,
+ stride,
+ groups=in_channels,
+ norm=norm[0],
+ act_func=act_func[0],
+ use_bias=use_bias[0],
+ )
+ self.point_conv = ConvLayer(
+ in_channels, out_channels, 1, norm=norm[1], act_func=act_func[1], use_bias=use_bias[1]
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.depth_conv(x)
+ x = self.point_conv(x)
+ return x
+
+
+class MBConv(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size=3,
+ stride=1,
+ mid_channels=None,
+ expand_ratio=6,
+ use_bias=False,
+ norm=("bn2d", "bn2d", "bn2d"),
+ act_func=("relu6", "relu6", None),
+ ):
+ super().__init__()
+
+ use_bias = val2tuple(use_bias, 3)
+ norm = val2tuple(norm, 3)
+ act_func = val2tuple(act_func, 3)
+ mid_channels = mid_channels or round(in_channels * expand_ratio)
+
+ self.inverted_conv = ConvLayer(
+ in_channels, mid_channels, 1, stride=1, norm=norm[0], act_func=act_func[0], use_bias=use_bias[0]
+ )
+ self.depth_conv = ConvLayer(
+ mid_channels,
+ mid_channels,
+ kernel_size,
+ stride=stride,
+ groups=mid_channels,
+ norm=norm[1],
+ act_func=act_func[1],
+ use_bias=use_bias[1],
+ )
+ self.point_conv = ConvLayer(
+ mid_channels, out_channels, 1, norm=norm[2], act_func=act_func[2], use_bias=use_bias[2]
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.inverted_conv(x)
+ x = self.depth_conv(x)
+ x = self.point_conv(x)
+ return x
+
+
+class FusedMBConv(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size=3,
+ stride=1,
+ mid_channels=None,
+ expand_ratio=6,
+ groups=1,
+ use_bias=False,
+ norm=("bn2d", "bn2d"),
+ act_func=("relu6", None),
+ ):
+ super().__init__()
+ use_bias = val2tuple(use_bias, 2)
+ norm = val2tuple(norm, 2)
+ act_func = val2tuple(act_func, 2)
+
+ mid_channels = mid_channels or round(in_channels * expand_ratio)
+
+ self.spatial_conv = ConvLayer(
+ in_channels,
+ mid_channels,
+ kernel_size,
+ stride,
+ groups=groups,
+ use_bias=use_bias[0],
+ norm=norm[0],
+ act_func=act_func[0],
+ )
+ self.point_conv = ConvLayer(
+ mid_channels, out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1]
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.spatial_conv(x)
+ x = self.point_conv(x)
+ return x
+
+
+class ResBlock(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size=3,
+ stride=1,
+ mid_channels=None,
+ expand_ratio=1,
+ use_bias=False,
+ norm=("bn2d", "bn2d"),
+ act_func=("relu6", None),
+ ):
+ super().__init__()
+ use_bias = val2tuple(use_bias, 2)
+ norm = val2tuple(norm, 2)
+ act_func = val2tuple(act_func, 2)
+
+ mid_channels = mid_channels or round(in_channels * expand_ratio)
+
+ self.conv1 = ConvLayer(
+ in_channels, mid_channels, kernel_size, stride, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0]
+ )
+ self.conv2 = ConvLayer(
+ mid_channels, out_channels, kernel_size, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1]
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.conv1(x)
+ x = self.conv2(x)
+ return x
+
+
+class LiteMLA(nn.Module):
+ r"""Lightweight multi-scale linear attention."""
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ heads: int or None = None,
+ heads_ratio: float = 1.0,
+ dim=8,
+ use_bias=False,
+ norm=(None, "bn2d"),
+ act_func=(None, None),
+ kernel_func="relu",
+ scales: tuple[int, ...] = (5,),
+ eps=1.0e-15,
+ ):
+ super().__init__()
+ self.eps = eps
+ heads = heads or int(in_channels // dim * heads_ratio)
+
+ total_dim = heads * dim
+
+ use_bias = val2tuple(use_bias, 2)
+ norm = val2tuple(norm, 2)
+ act_func = val2tuple(act_func, 2)
+
+ self.dim = dim
+ self.qkv = ConvLayer(in_channels, 3 * total_dim, 1, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0])
+ self.aggreg = nn.ModuleList(
+ [
+ nn.Sequential(
+ nn.Conv2d(
+ 3 * total_dim,
+ 3 * total_dim,
+ scale,
+ padding=get_same_padding(scale),
+ groups=3 * total_dim,
+ bias=use_bias[0],
+ ),
+ nn.Conv2d(3 * total_dim, 3 * total_dim, 1, groups=3 * heads, bias=use_bias[0]),
+ )
+ for scale in scales
+ ]
+ )
+ self.kernel_func = build_act(kernel_func, inplace=False)
+
+ self.proj = ConvLayer(
+ total_dim * (1 + len(scales)), out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1]
+ )
+
+ @autocast(enabled=False)
+ def relu_linear_att(self, qkv: torch.Tensor) -> torch.Tensor:
+ B, _, H, W = list(qkv.size())
+
+ if qkv.dtype == torch.float16:
+ qkv = qkv.float()
+
+ qkv = torch.reshape(qkv, (B, -1, 3 * self.dim, H * W))
+ qkv = torch.transpose(qkv, -1, -2)
+ q, k, v = (qkv[..., 0 : self.dim], qkv[..., self.dim : 2 * self.dim], qkv[..., 2 * self.dim :])
+
+ # lightweight linear attention
+ q = self.kernel_func(q)
+ k = self.kernel_func(k)
+
+ # linear matmul
+ trans_k = k.transpose(-1, -2)
+
+ v = F.pad(v, (0, 1), mode="constant", value=1)
+ kv = torch.matmul(trans_k, v)
+ out = torch.matmul(q, kv)
+ out = out[..., :-1] / (out[..., -1:] + self.eps)
+
+ out = torch.transpose(out, -1, -2)
+ out = torch.reshape(out, (B, -1, H, W))
+ return out
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ # generate multi-scale q, k, v
+ qkv = self.qkv(x)
+ multi_scale_qkv = [qkv]
+ for op in self.aggreg:
+ multi_scale_qkv.append(op(qkv))
+ multi_scale_qkv = torch.cat(multi_scale_qkv, dim=1)
+
+ out = self.relu_linear_att(multi_scale_qkv)
+ out = self.proj(out)
+
+ return out
+
+
+class EfficientViTBlock(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ heads_ratio: float = 1.0,
+ dim=32,
+ expand_ratio: float = 4,
+ norm="bn2d",
+ act_func="hswish",
+ ):
+ super().__init__()
+ self.context_module = ResidualBlock(
+ LiteMLA(
+ in_channels=in_channels, out_channels=in_channels, heads_ratio=heads_ratio, dim=dim, norm=(None, norm)
+ ),
+ IdentityLayer(),
+ )
+ local_module = MBConv(
+ in_channels=in_channels,
+ out_channels=in_channels,
+ expand_ratio=expand_ratio,
+ use_bias=(True, True, False),
+ norm=(None, None, norm),
+ act_func=(act_func, act_func, None),
+ )
+ self.local_module = ResidualBlock(local_module, IdentityLayer())
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.context_module(x)
+ x = self.local_module(x)
+ return x
+
+
+#################################################################################
+# Functional Blocks #
+#################################################################################
+
+
+class ResidualBlock(nn.Module):
+ def __init__(
+ self, main: nn.Module or None, shortcut: nn.Module or None, post_act=None, pre_norm: nn.Module or None = None
+ ):
+ super().__init__()
+
+ self.pre_norm = pre_norm
+ self.main = main
+ self.shortcut = shortcut
+ self.post_act = build_act(post_act)
+
+ def forward_main(self, x: torch.Tensor) -> torch.Tensor:
+ if self.pre_norm is None:
+ return self.main(x)
+ else:
+ return self.main(self.pre_norm(x))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.main is None:
+ res = x
+ elif self.shortcut is None:
+ res = self.forward_main(x)
+ else:
+ res = self.forward_main(x) + self.shortcut(x)
+ if self.post_act:
+ res = self.post_act(res)
+ return res
+
+
+class OpSequential(nn.Module):
+ def __init__(self, op_list: list[nn.Module or None]):
+ super().__init__()
+ valid_op_list = []
+ for op in op_list:
+ if op is not None:
+ valid_op_list.append(op)
+ self.op_list = nn.ModuleList(valid_op_list)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ for op in self.op_list:
+ x = op(x)
+ return x
diff --git a/kornia/contrib/models/efficient_vit/utils/__init__.py b/kornia/contrib/models/efficient_vit/utils/__init__.py
new file mode 100644
index 000000000..13abc2c2d
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/utils/__init__.py
@@ -0,0 +1,9 @@
+# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction
+# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
+# International Conference on Computer Vision (ICCV), 2023
+
+# TODO: promote this to kornia
+from .list import val2tuple
+from .network import build_kwargs_from_config, get_same_padding
+
+__all__ = ["val2tuple", "get_same_padding", "build_kwargs_from_config"]
diff --git a/kornia/contrib/models/efficient_vit/utils/list.py b/kornia/contrib/models/efficient_vit/utils/list.py
new file mode 100644
index 000000000..2670372a1
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/utils/list.py
@@ -0,0 +1,22 @@
+# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction
+# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
+# International Conference on Computer Vision (ICCV), 2023
+from __future__ import annotations
+
+from typing import Any, Union
+
+
+def val2list(x: Union[list[Any], tuple[Any, ...], Any], repeat_time: int = 1) -> list[Any]:
+ if isinstance(x, (list, tuple)):
+ return list(x)
+ return [x for _ in range(repeat_time)]
+
+
+def val2tuple(x: Union[list[Any], tuple[Any, ...], Any], min_len: int = 1, idx_repeat: int = -1) -> tuple[Any, ...]:
+ x = val2list(x)
+
+ # repeat elements if necessary
+ if len(x) > 0:
+ x[idx_repeat:idx_repeat] = [x[idx_repeat] for _ in range(min_len - len(x))]
+
+ return tuple(x)
diff --git a/kornia/contrib/models/efficient_vit/utils/network.py b/kornia/contrib/models/efficient_vit/utils/network.py
new file mode 100644
index 000000000..5267fa691
--- /dev/null
+++ b/kornia/contrib/models/efficient_vit/utils/network.py
@@ -0,0 +1,24 @@
+# EfficientViT: Multi-Scale Linear Attention for High-Resolution Dense Prediction
+# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
+# International Conference on Computer Vision (ICCV), 2023
+from __future__ import annotations
+
+from inspect import signature
+from typing import Any, Union
+
+
+def get_same_padding(kernel_size: Union[int, tuple[int, ...]]) -> Union[int, tuple[int, ...]]:
+ if isinstance(kernel_size, (tuple,)):
+ return tuple([get_same_padding(ks) for ks in kernel_size]) # type: ignore
+
+ # assert kernel_size % 2 > 0, "kernel size should be odd number"
+ return kernel_size // 2
+
+
+def build_kwargs_from_config(config: dict[str, Any], target_func: Any) -> dict[str, Any]:
+ valid_keys = list(signature(target_func).parameters)
+ kwargs = {}
+ for key in config:
+ if key in valid_keys:
+ kwargs[key] = config[key]
+ return kwargs
diff --git a/test/contrib/models/test_efficient_vit.py b/test/contrib/models/test_efficient_vit.py
new file mode 100644
index 000000000..6ac37428f
--- /dev/null
+++ b/test/contrib/models/test_efficient_vit.py
@@ -0,0 +1,61 @@
+from pathlib import Path
+
+import pytest
+import torch
+
+from kornia.contrib.models.efficient_vit import EfficientViT, EfficientViTConfig
+from kornia.contrib.models.efficient_vit import backbone as vit
+
+
+class TestEfficientViT:
+ def _test_smoke(self, device, dtype, img_size: int, expected_resolution: int, model_name: str):
+ model = getattr(vit, f"efficientvit_backbone_{model_name}")()
+ model = model.to(device=device, dtype=dtype)
+
+ image = torch.randn(1, 3, img_size, img_size, device=device, dtype=dtype)
+
+ out = model(image)
+
+ assert "input" in out
+ assert out["input"].shape == image.shape
+
+ assert "stage_final" in out
+ assert out["stage_final"].shape[-2:] == torch.Size([expected_resolution, expected_resolution])
+
+ @pytest.mark.parametrize("model_name", ["b0", "b1", "b2", "b3"])
+ @pytest.mark.parametrize("img_size,expected_resolution", [(224, 7), (256, 8), (288, 9)])
+ def test_smoke(self, device, dtype, img_size: int, expected_resolution: int, model_name: str):
+ self._test_smoke(device, dtype, img_size, expected_resolution, model_name)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("model_name", ["l0", "l1", "l2", "l3"])
+ @pytest.mark.parametrize("img_size,expected_resolution", [(224, 7), (256, 8), (288, 9), (320, 10), (384, 12)])
+ def test_smoke_large(self, device, dtype, img_size: int, expected_resolution: int, model_name: str):
+ self._test_smoke(device, dtype, img_size, expected_resolution, model_name)
+
+ def test_onnx(self, device, dtype, tmp_path: Path):
+ model: vit.EfficientViTBackbone = vit.efficientvit_backbone_b0()
+ model = model.to(device=device, dtype=dtype)
+
+ image = torch.randn(1, 3, 224, 224, device=device, dtype=dtype)
+
+ model_path = tmp_path / "efficientvit_backbone_b0.onnx"
+
+ torch.onnx.export(model, image, model_path, opset_version=16)
+
+ assert model_path.is_file()
+
+ def test_load_pretrained(self, device, dtype):
+ model = EfficientViT.from_config(EfficientViTConfig())
+ model = model.to(device=device, dtype=dtype)
+
+ image = torch.randn(1, 3, 224, 224, device=device, dtype=dtype)
+ feats = model(image)
+ assert feats["stage_final"].shape == torch.Size([1, 256, 7, 7])
+
+ @pytest.mark.parametrize("model_type", ["b1", "b2", "b3"])
+ @pytest.mark.parametrize("resolution", [224, 256, 288])
+ def test_config(self, model_type, resolution):
+ config = EfficientViTConfig.from_pretrained(model_type, resolution)
+ assert model_type in config.checkpoint
+ assert str(resolution) in config.checkpoint