Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Make TinyViT available as a standalone image classifier (#2455)

Thien Tran96baebf45362
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 45a96d45d..109d7bcba 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -121,6 +121,8 @@ Image Classification
.. autoclass:: VisionTransformer
.. autoclass:: MobileViT
+.. autoclass:: TinyViT
+ :members:
.. autoclass:: ClassificationHead
Image Stitching
diff --git a/docs/source/index.rst b/docs/source/index.rst
index ed9703903..002aa0153 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -96,6 +96,7 @@ Join the community
models/yunet
models/vit
models/vit_mobile
+ models/tiny_vit
models/loftr
models/defmo
models/hardnet
diff --git a/docs/source/models/tiny_vit.rst b/docs/source/models/tiny_vit.rst
new file mode 100644
index 000000000..82f5fd286
--- /dev/null
+++ b/docs/source/models/tiny_vit.rst
@@ -0,0 +1,36 @@
+.. _kornia_tiny_vit:
+
+TinyViT
+.........
+
+.. card::
+ :link: https://arxiv.org/abs/2110.02178
+
+ **TinyViT: Fast Pretraining Distillation for Small Vision Transformers**
+ ^^^
+ **Abstract:** Vision transformer (ViT) recently has drawn great attention in computer vision due to its remarkable model capability. However, most prevailing ViT models suffer from huge number of parameters, restricting their applicability on devices with limited resources. To alleviate this issue, we propose TinyViT, a new family of tiny and efficient small vision transformers pretrained on large-scale datasets with our proposed fast distillation framework. The central idea is to transfer knowledge from large pretrained models to small ones, while enabling small models to get the dividends of massive pretraining data. More specifically, we apply distillation during pretraining for knowledge transfer. The logits of large teacher models are sparsified and stored in disk in advance to save the memory cost and computation overheads. The tiny student transformers are automatically scaled down from a large pretrained model with computation and parameter constraints. Comprehensive experiments demonstrate the efficacy of TinyViT. It achieves a top-1 accuracy of 84.8% on ImageNet-1k with only 21M parameters, being comparable to Swin-B pretrained on ImageNet-21k while using 4.2 times fewer parameters. Moreover, increasing image resolutions, TinyViT can reach 86.5% accuracy, being slightly better than Swin-L while using only 11% parameters. Last but not the least, we demonstrate a good transfer ability of TinyViT on various downstream tasks. Code and models are available at https://github.com/microsoft/Cream/tree/main/TinyViT.
+
+ **Tasks:** Image Classification, Object Detection
+
+ **Datasets:** ImageNet, MS-COCO
+
+ +++
+ **Authors:** Kan Wu, Jinnian Zhang, Houwen Peng, Mengchen Liu, Bin Xiao, Jianlong Fu, Lu Yuan
+
+.. image:: https://github.com/microsoft/Cream/blob/main/TinyViT/.figure/framework.png?raw=true
+ :align: center
+
+Usage
+~~~~~
+
+You can use TinyViT models as follows.
+
+.. code:: python
+
+ import torch
+ from kornia.contrib.models.tiny_vit import TinyViT
+
+ model = TinyViT.from_config("5m", pretrained=True) # ImageNet-1k pre-trained
+
+ img = torch.rand(1, 3, 224, 224)
+ out = classifier(img) # 1x1000
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 69a62a9b9..9d257b84b 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -14,6 +14,7 @@ from .face_detection import *
from .histogram_matching import histogram_matching, interp
from .image_stitching import ImageStitcher
from .lambda_module import Lambda
+from .models.tiny_vit import TinyViT
from .object_detection import ObjectDetector
from .vit import VisionTransformer
from .vit_mobile import MobileViT
@@ -29,6 +30,7 @@ __all__ = [
"interp",
"VisionTransformer",
"MobileViT",
+ "TinyViT",
"ClassificationHead",
"Lambda",
"ImageStitcher",
diff --git a/kornia/contrib/models/common.py b/kornia/contrib/models/common.py
index 22024dd0c..7ad86d54c 100644
--- a/kornia/contrib/models/common.py
+++ b/kornia/contrib/models/common.py
@@ -4,7 +4,7 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core import Module, Tensor
+from kornia.core import Module, Tensor, pad
class ConvNormAct(nn.Sequential):
@@ -84,3 +84,50 @@ class LayerNorm2d(Module):
x = (x - u) / (s + self.eps).sqrt()
x = self.weight[:, None, None] * x + self.bias[:, None, None]
return x
+
+
+def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, int]]:
+ """Partition into non-overlapping windows with padding if needed.
+
+ Args:
+ x: input tokens with [B, H, W, C].
+ window_size: window size.
+
+ Returns:
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
+ (Hp, Wp): padded height and width before partition
+ """
+ B, H, W, C = x.shape
+
+ pad_h = (window_size - H % window_size) % window_size
+ pad_w = (window_size - W % window_size) % window_size
+ if pad_h > 0 or pad_w > 0:
+ x = pad(x, (0, 0, 0, pad_w, 0, pad_h))
+ Hp, Wp = H + pad_h, W + pad_w
+
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
+ return windows, (Hp, Wp)
+
+
+def window_unpartition(windows: Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int]) -> Tensor:
+ """Window unpartition into original sequences and removing padding.
+
+ Args:
+ x: input tokens with [B * num_windows, window_size, window_size, C].
+ window_size: window size.
+ pad_hw: padded height and width (Hp, Wp).
+ hw: original height and width (H, W) before padding.
+
+ Returns:
+ x: unpartitioned sequences with [B, H, W, C].
+ """
+ Hp, Wp = pad_hw
+ H, W = hw
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
+
+ if Hp > H or Wp > W:
+ x = x[:, :H, :W, :].contiguous()
+ return x
diff --git a/kornia/contrib/models/sam/architecture/image_encoder.py b/kornia/contrib/models/sam/architecture/image_encoder.py
index b279259a9..714c8d869 100644
--- a/kornia/contrib/models/sam/architecture/image_encoder.py
+++ b/kornia/contrib/models/sam/architecture/image_encoder.py
@@ -9,9 +9,9 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.contrib.models.common import LayerNorm2d
+from kornia.contrib.models.common import LayerNorm2d, window_partition, window_unpartition
from kornia.contrib.models.sam.architecture.common import MLPBlock
-from kornia.core import Module, Tensor, pad, zeros
+from kornia.core import Module, Tensor, zeros
# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
@@ -223,53 +223,6 @@ class Attention(Module):
return x
-def window_partition(x: Tensor, window_size: int) -> tuple[Tensor, tuple[int, int]]:
- """Partition into non-overlapping windows with padding if needed.
-
- Args:
- x: input tokens with [B, H, W, C].
- window_size: window size.
-
- Returns:
- windows: windows after partition with [B * num_windows, window_size, window_size, C].
- (Hp, Wp): padded height and width before partition
- """
- B, H, W, C = x.shape
-
- pad_h = (window_size - H % window_size) % window_size
- pad_w = (window_size - W % window_size) % window_size
- if pad_h > 0 or pad_w > 0:
- x = pad(x, (0, 0, 0, pad_w, 0, pad_h))
- Hp, Wp = H + pad_h, W + pad_w
-
- x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
- windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
- return windows, (Hp, Wp)
-
-
-def window_unpartition(windows: Tensor, window_size: int, pad_hw: tuple[int, int], hw: tuple[int, int]) -> Tensor:
- """Window unpartition into original sequences and removing padding.
-
- Args:
- x: input tokens with [B * num_windows, window_size, window_size, C].
- window_size: window size.
- pad_hw: padded height and width (Hp, Wp).
- hw: original height and width (H, W) before padding.
-
- Returns:
- x: unpartitioned sequences with [B, H, W, C].
- """
- Hp, Wp = pad_hw
- H, W = hw
- B = windows.shape[0] // (Hp * Wp // window_size // window_size)
- x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
- x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
-
- if Hp > H or Wp > W:
- x = x[:, :H, :W, :].contiguous()
- return x
-
-
def get_rel_pos(q_size: int, k_size: int, rel_pos: Tensor) -> Tensor:
"""Get relative positional embeddings according to the relative positions of query and key sizes.
diff --git a/kornia/contrib/models/sam/model.py b/kornia/contrib/models/sam/model.py
index a9ce78e1b..84a1455d0 100644
--- a/kornia/contrib/models/sam/model.py
+++ b/kornia/contrib/models/sam/model.py
@@ -20,8 +20,8 @@ from kornia.contrib.models.sam.architecture.common import LayerNorm
from kornia.contrib.models.sam.architecture.image_encoder import ImageEncoderViT
from kornia.contrib.models.sam.architecture.mask_decoder import MaskDecoder
from kornia.contrib.models.sam.architecture.prompt_encoder import PromptEncoder
-from kornia.contrib.models.sam.architecture.tiny_vit import TinyViT, tiny_vit_5m
from kornia.contrib.models.sam.architecture.transformer import TwoWayTransformer
+from kornia.contrib.models.tiny_vit import TinyViT
from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
@@ -138,7 +138,7 @@ class Sam(ModelBase[SamConfig]):
image_embedding_size = image_size // vit_patch_size
model = Sam(
- image_encoder=tiny_vit_5m(image_size, mobile_sam=True),
+ image_encoder=TinyViT.from_config("5m", img_size=image_size, mobile_sam=True),
prompt_encoder=PromptEncoder(
embed_dim=prompt_embed_dim,
image_embedding_size=(image_embedding_size, image_embedding_size),
diff --git a/kornia/contrib/models/sam/architecture/tiny_vit.py b/kornia/contrib/models/tiny_vit.py
similarity index 70%
rename from kornia/contrib/models/sam/architecture/tiny_vit.py
rename to kornia/contrib/models/tiny_vit.py
index fb11a6102..0fbf50786 100644
--- a/kornia/contrib/models/sam/architecture/tiny_vit.py
+++ b/kornia/contrib/models/tiny_vit.py
@@ -1,18 +1,18 @@
# https://github.com/microsoft/Cream/blob/8dc38822b99fff8c262c585a32a4f09ac504d693/TinyViT/models/tiny_vit.py
# https://github.com/ChaoningZhang/MobileSAM/blob/01ea8d0f5590082f0c1ceb0a3e2272593f20154b/mobile_sam/modeling/tiny_vit_sam.py
-# NOTE: make this available as an image classifier?
from __future__ import annotations
import itertools
+import warnings
from typing import Any
import torch
+import torch.nn.functional as F
from torch import nn
from torch.utils import checkpoint
-from kornia.contrib.models.common import DropPath, LayerNorm2d
-from kornia.contrib.models.sam.architecture.image_encoder import window_partition, window_unpartition
+from kornia.contrib.models.common import DropPath, LayerNorm2d, window_partition, window_unpartition
from kornia.core import Module, Tensor
from kornia.core.check import KORNIA_CHECK
@@ -58,9 +58,7 @@ class MBConv(Module):
super().__init__()
hidden_channels = int(in_channels * expansion_ratio)
self.conv1 = ConvBN(in_channels, hidden_channels, 1, activation=activation) # point-wise
- self.conv2 = ConvBN(
- hidden_channels, hidden_channels, 3, 1, 1, hidden_channels, activation=activation
- ) # depth-wise
+ self.conv2 = ConvBN(hidden_channels, hidden_channels, 3, 1, 1, hidden_channels, activation) # depth-wise
self.conv3 = ConvBN(hidden_channels, out_channels, 1)
self.drop_path = DropPath(drop_path)
self.act = activation()
@@ -228,20 +226,6 @@ class TinyViTBlock(Module):
local_conv_size: int = 3,
activation: type[Module] = nn.GELU,
) -> None:
- """Create TinyViT Block.
-
- Args:
- dim (int): Number of input channels.
- input_resolution (tuple[int, int]): Input resolution.
- num_heads (int): Number of attention heads.
- window_size (int): Window size.
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
- drop (float, optional): Dropout rate. Default: 0.0
- drop_path (float, optional): Stochastic depth rate. Default: 0.0
- local_conv_size (int): the kernel size of the convolution between
- Attention and MLP. Default: 3
- activation: the activation function. Default: nn.GELU
- """
KORNIA_CHECK(dim % num_heads == 0, "dim must be divislbe by num_heads")
super().__init__()
self.input_resolution = _make_pair(input_resolution)
@@ -291,22 +275,6 @@ class BasicLayer(Module):
local_conv_size: int = 3,
activation: type[Module] = nn.GELU,
) -> None:
- """A basic TinyViT layer for one stage.
-
- Args:
- dim (int): Number of input channels.
- input_resolution (tuple[int]): Input resolution.
- depth (int): Number of blocks.
- num_heads (int): Number of attention heads.
- window_size (int): Local window size.
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
- drop (float, optional): Dropout rate. Default: 0.0
- drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
- downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
- use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
- local_conv_size: the kernel size of the depthwise convolution between attention and MLP. Default: 3
- activation: the activation function. Default: nn.GELU
- """
super().__init__()
self.use_checkpoint = use_checkpoint
@@ -339,6 +307,26 @@ class BasicLayer(Module):
class TinyViT(Module):
+ """TinyViT model, as described in https://arxiv.org/abs/2207.10666
+
+ Args:
+ img_size: Size of input image.
+ in_chans: Number of input image's channels.
+ num_classes: Number of output classes.
+ embed_dims: List of embedding dimensions.
+ depths: List of block count for each downsampling stage
+ num_heads: List of attention heads used in self-attention for each downsampling stage.
+ window_sizes: List of self-attention's window size for each downsampling stage.
+ mlp_ratio: Ratio of MLP dimension to embedding dimension in self-attention.
+ drop_rate: Dropout rate.
+ drop_path_rate: Stochastic depth rate.
+ use_checkpoint: Whether to use activation checkpointing to trade compute for memory.
+ mbconv_expand_ratio: Expansion ratio used in MBConv block.
+ local_conv_size: Kernel size of convolution used in TinyViTBlock
+ activation: activation function.
+ mobile_same: Whether to use modifications for MobileSAM.
+ """
+
def __init__(
self,
img_size: int = 224,
@@ -356,7 +344,7 @@ class TinyViT(Module):
local_conv_size: int = 3,
# layer_lr_decay: float = 1.0,
activation: type[Module] = nn.GELU,
- mobile_sam: bool = True,
+ mobile_sam: bool = False,
) -> None:
super().__init__()
self.img_size = img_size
@@ -364,7 +352,7 @@ class TinyViT(Module):
self.neck: Module | None
if mobile_sam:
# MobileSAM adjusts the stride to match the total stride of other ViT backbones
- # used in original SAM (stride 16)
+ # used in the original SAM (stride 16)
strides = [2, 2, 1, 1]
self.neck = nn.Sequential(
nn.Conv2d(embed_dims[-1], 256, 1, bias=False),
@@ -422,12 +410,14 @@ class TinyViT(Module):
self.feat_size = input_resolution # final feature map size
# Classifier head
- # NOTE: needs this to load pre-trained weights with strict=True
+ # NOTE: this is redundant for MobileSAM, but we still need it
+ # to load pre-trained weights with strict=True
# TODO: enable strict=False, or host our own weights
self.norm_head = nn.LayerNorm(embed_dims[-1])
self.head = nn.Linear(embed_dims[-1], num_classes)
def forward(self, x: Tensor) -> Tensor:
+ """Classify images if ``mobile_sam=False``, produce feature maps if ``mobile_sam=True``."""
x = self.patch_embed(x)
x = self.layers(x)
@@ -441,10 +431,60 @@ class TinyViT(Module):
x = self.head(self.norm_head(x))
return x
+ @staticmethod
+ def from_config(variant: str, pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
+ """Create a TinyViT model from pre-defined variants.
+
+ Args:
+ variant: TinyViT variant. Possible values: ``'5m'``, ``'11m'``, ``'21m'``.
+ pretrained: whether to use pre-trained weights. Possible values: ``False``, ``True``, ``'in22k'``,
+ ``'in1k'``. For TinyViT-21M (``variant='21m'``), ``'in1k_384'``, ``'in1k_512'`` are also available.
+ **kwargs: other keyword arguments that will be passed to :class:`TinyViT`.
+
+ .. note::
+ When ``img_size`` is different from the pre-trained size, bicubic interpolation will be performed on
+ attention biases. When using ``pretrained=True``, ImageNet-1k checkpoint (``'in1k'``) is used.
+ For feature extraction or fine-tuning, ImageNet-22k checkpoint (``'in22k'``) is preferred.
+ """
+ KORNIA_CHECK(variant in ("5m", "11m", "21m"), "Only variant 5m, 11m, and 21m are supported")
+ return {"5m": _tiny_vit_5m, "11m": _tiny_vit_11m, "21m": _tiny_vit_21m}[variant](pretrained, **kwargs)
+
+
+def _load_pretrained(model: TinyViT, url: str) -> TinyViT:
+ model_state_dict = model.state_dict()
+ state_dict = torch.hub.load_state_dict_from_url(url)
-def tiny_vit_5m(img_size: int, **kwargs: Any) -> TinyViT:
- return TinyViT(
- img_size=img_size,
+ # official checkpoint has "model" key
+ if "model" in state_dict:
+ state_dict = state_dict["model"]
+
+ # https://github.com/microsoft/Cream/blob/8dc38822b99fff8c262c585a32a4f09ac504d693/TinyViT/utils.py#L163
+ # bicubic interpolate attention biases
+ ab_keys = [k for k in state_dict.keys() if "attention_biases" in k]
+ for k in ab_keys:
+ n_heads1, L1 = state_dict[k].shape
+ n_heads2, L2 = model_state_dict[k].shape
+ KORNIA_CHECK(n_heads1 == n_heads2, f"Fail to load {k}. Pre-trained checkpoint should have num_heads={n_heads1}")
+
+ if L1 != L2:
+ S1 = int(L1**0.5)
+ S2 = int(L2**0.5)
+ attention_biases = state_dict[k].view(1, n_heads1, S1, S1)
+ attention_biases = F.interpolate(attention_biases, size=(S2, S2), mode='bicubic')
+ state_dict[k] = attention_biases.view(n_heads2, L2)
+
+ if state_dict["head.weight"].shape[0] != model.head.out_features:
+ msg = "Number of classes does not match pre-trained checkpoint's. Resetting classification head to zeros"
+ warnings.warn(msg)
+ state_dict["head.weight"] = torch.zeros_like(model.head.weight)
+ state_dict["head.bias"] = torch.zeros_like(model.head.bias)
+
+ model.load_state_dict(state_dict)
+ return model
+
+
+def _tiny_vit_5m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
+ model = TinyViT(
embed_dims=[64, 128, 160, 320],
depths=[2, 2, 6, 2],
num_heads=[2, 4, 5, 10],
@@ -453,10 +493,21 @@ def tiny_vit_5m(img_size: int, **kwargs: Any) -> TinyViT:
**kwargs,
)
+ if pretrained:
+ if pretrained is True:
+ pretrained = "in1k"
+
+ url = {
+ "in22k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.pth",
+ "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22kto1k_distill.pth",
+ }[pretrained]
+ model = _load_pretrained(model, url)
-def tiny_vit_11m(img_size: int, **kwargs: Any) -> TinyViT:
- return TinyViT(
- img_size=img_size,
+ return model
+
+
+def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
+ model = TinyViT(
embed_dims=[64, 128, 256, 448],
depths=[2, 2, 6, 2],
num_heads=[2, 4, 8, 14],
@@ -465,10 +516,21 @@ def tiny_vit_11m(img_size: int, **kwargs: Any) -> TinyViT:
**kwargs,
)
+ if pretrained:
+ if pretrained is True:
+ pretrained = "in1k"
+
+ url = {
+ "in22k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.pth",
+ "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22kto1k_distill.pth",
+ }[pretrained]
+ model = _load_pretrained(model, url)
-def tiny_vit_21m(img_size: int, **kwargs: Any) -> TinyViT:
- return TinyViT(
- img_size=img_size,
+ return model
+
+
+def _tiny_vit_21m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
+ model = TinyViT(
embed_dims=[96, 192, 384, 576],
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 18],
@@ -476,3 +538,22 @@ def tiny_vit_21m(img_size: int, **kwargs: Any) -> TinyViT:
drop_path_rate=0.2,
**kwargs,
)
+
+ if pretrained:
+ if pretrained is True:
+ pretrained = "in1k"
+ img_size = kwargs.get("img_size", 224)
+ if img_size >= 384:
+ pretrained = "in1k_384"
+ if img_size >= 512:
+ pretrained = "in1k_512"
+
+ url = {
+ "in22k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.pth",
+ "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_distill.pth",
+ "in1k_384": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_384_distill.pth",
+ "in1k_512": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_512_distill.pth",
+ }[pretrained]
+ model = _load_pretrained(model, url)
+
+ return model
diff --git a/test/contrib/models/test_tiny_vit.py b/test/contrib/models/test_tiny_vit.py
new file mode 100644
index 000000000..7a0a01b3b
--- /dev/null
+++ b/test/contrib/models/test_tiny_vit.py
@@ -0,0 +1,62 @@
+import pytest
+import torch
+
+from kornia.contrib.models.tiny_vit import TinyViT
+from kornia.core import Tensor
+from kornia.testing import BaseTester
+
+
+class TestTinyViT(BaseTester):
+ @pytest.mark.parametrize("img_size", [224, 256])
+ def test_smoke(self, device, dtype, img_size):
+ model = TinyViT(img_size=img_size).to(device=device, dtype=dtype)
+ inpt = torch.randn(1, 3, img_size, img_size, device=device, dtype=dtype)
+
+ out = model(inpt)
+ assert isinstance(out, Tensor)
+
+ @pytest.mark.parametrize('num_classes', [10, 100])
+ @pytest.mark.parametrize('batch_size', [1, 3])
+ def test_cardinality(self, device, dtype, batch_size, num_classes):
+ model = TinyViT(num_classes=num_classes).to(device=device, dtype=dtype)
+ inpt = torch.rand(batch_size, 3, model.img_size, model.img_size, device=device, dtype=dtype)
+
+ out = model(inpt)
+ assert out.shape == (batch_size, num_classes)
+
+ def test_exception(self):
+ ...
+
+ def test_gradcheck(self):
+ ...
+
+ def test_module(self):
+ ...
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ op = TinyViT().to(device=device, dtype=dtype)
+ img = torch.rand(1, 3, op.img_size, op.img_size, device=device, dtype=dtype)
+
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img), op_optimized(img))
+
+ @pytest.mark.parametrize("pretrained", [False, True])
+ @pytest.mark.parametrize("variant", ["5m", "11m", "21m"])
+ def test_from_config(self, variant, pretrained):
+ model = TinyViT.from_config(variant, pretrained=pretrained)
+ assert isinstance(model, TinyViT)
+
+ @pytest.mark.parametrize('num_classes', [1000, 8])
+ @pytest.mark.parametrize("img_size", [224, 256])
+ def test_pretrained(self, img_size, num_classes):
+ model = TinyViT.from_config("5m", img_size=img_size, num_classes=num_classes, pretrained=True)
+ assert isinstance(model, TinyViT)
+
+ def test_mobile_sam_backbone(self, device, dtype):
+ img_size = 1024
+ batch_size = 1
+ model = TinyViT.from_config("5m", img_size=img_size, mobile_sam=True).to(device=device, dtype=dtype)
+ inpt = torch.randn(batch_size, 3, img_size, img_size, device=device, dtype=dtype)
+
+ out = model(inpt)
+ assert out.shape == (batch_size, 256, img_size // 16, img_size // 16)