π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add vision transformer (vit) (#1296)
Edgar Ribac14078f7437a
diff --git a/docs/source/conf.py b/docs/source/conf.pyindex b9f1c0f59..6efe032f6 100644--- a/docs/source/conf.py+++ b/docs/source/conf.py@@ -118,7 +118,7 @@ html_theme_options = {'dark_logo': 'img/kornia_logo_only_dark.svg',"sidebar_hide_name": True,"navigation_with_keys": True,- 'display_version': False,+# "announcement": """# <a style=\"text-decoration: none; color: white;\"# href=\"https://github.com/kornia/kornia\">diff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex b63c9975d..7de546470 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -6,6 +6,12 @@ kornia.contrib.. autofunction:: connected_components.. autofunction:: extract_tensor_patches+Image Classification+--------------------++.. autoclass:: VisionTransformer+.. autoclass:: ClassificationHead+Module------diff --git a/docs/source/geometry.linalg.rst b/docs/source/geometry.linalg.rstindex c0612f69d..950ea6022 100644--- a/docs/source/geometry.linalg.rst+++ b/docs/source/geometry.linalg.rst@@ -8,5 +8,4 @@ kornia.geometry.linalg.. autofunction:: compose_transformations.. autofunction:: inverse_transformation.. autofunction:: transform_points-.. autofunction:: transform_boxes.. autofunction:: perspective_transform_lafsdiff --git a/docs/source/index.rst b/docs/source/index.rstindex c6db29c2f..93b030ef9 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -53,6 +53,7 @@ Join the community:caption: KORNIA MODELS:hidden:+ models/vitmodels/loftrmodels/defmomodels/hardnetdiff --git a/docs/source/models/affnet.rst b/docs/source/models/affnet.rstindex 3659ed35b..3ef5dc663 100644--- a/docs/source/models/affnet.rst+++ b/docs/source/models/affnet.rst@@ -1,5 +1,5 @@-Affnet-......+Affnet (detection)+.................... card:::link: https://paperswithcode.com/paper/repeatability-is-not-enough-learning-affinediff --git a/docs/source/models/defmo.rst b/docs/source/models/defmo.rstindex 5b86a1883..a0862e221 100644--- a/docs/source/models/defmo.rst+++ b/docs/source/models/defmo.rst@@ -1,5 +1,5 @@-DeFMO-.....+DeFMO (video)+............... card:::link: https://paperswithcode.com/paper/defmo-deblurring-and-shape-recovery-of-fastdiff --git a/docs/source/models/hardnet.rst b/docs/source/models/hardnet.rstindex 98afdaa36..5855efce4 100644--- a/docs/source/models/hardnet.rst+++ b/docs/source/models/hardnet.rst@@ -1,5 +1,5 @@-Hardnet-.......+Hardnet (descriptor)+...................... card:::link: https://paperswithcode.com/paper/working-hard-to-know-your-neighbors-marginsdiff --git a/docs/source/models/loftr.rst b/docs/source/models/loftr.rstindex bfa3c4f46..c3960468a 100644--- a/docs/source/models/loftr.rst+++ b/docs/source/models/loftr.rst@@ -1,5 +1,5 @@-LoFTR-.....+LoFTR (matching)+.................. card:::link: https://paperswithcode.com/paper/loftr-detector-free-local-feature-matchingdiff --git a/docs/source/models/vit.rst b/docs/source/models/vit.rstnew file mode 100644index 000000000..cdc4cb303--- /dev/null+++ b/docs/source/models/vit.rst@@ -0,0 +1,57 @@+Vision Transformer (ViT)+.........................++.. card::+ :link: https://paperswithcode.com/paper/an-image-is-worth-16x16-words-transformers-1++ **ViT: An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale**+ ^^^+ **Abstract:** While the Transformer architecture has become the de-facto standard for natural language processing tasks, its applications to computer vision remain limited. In vision, attention is either applied in conjunction with convolutional networks, or used to replace certain components of convolutional networks while keeping their overall structure in place. We show that this reliance on CNNs is not necessary and a pure transformer applied directly to sequences of image patches can perform very well on image classification tasks. When pre-trained on large amounts of data and transferred to multiple mid-sized or small image recognition benchmarks (ImageNet, CIFAR-100, VTAB, etc. ), Vision Transformer (ViT) attains excellent results compared to state-of-the-art convolutional networks while requiring substantially fewer computational resources to train.++ **Tasks:** Image Classification, Fine-Grained Image Classification, Document Image Classification++ **Datasets:** CIFAR-10, ImageNet, CIFAR-100++ **Conference:** ICLR 2021++ **Licence:** Apache-2.0++ ++++ **Authors:** Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby++.. image:: https://github.com/google-research/vision_transformer/raw/main/vit_figure.png+ :align: center+++Kornia-ViT+----------++We provide the operator :py:class:`~kornia.contrib.VisionTransformer` that is meant to be used across tasks.+One can use the *ViT* in Kornia as follows:++.. code:: python++ img = torch.rand(1, 3, 224, 224)+ vit = VisionTransformer(image_size=224, patch_size=16)+ out = vit(img)++``kornia-vit`` does not include any classification head.+For this reason, we provide an :py:class:`~kornia.contrib.ClassificationHead` which can be easily combined+with a `nn.Sequential` in order to easily build a custom image classification pipeline.++.. code:: python++ import torch.nn as nn+ import kornia.contrib as K++ classifier = nn.Sequential(+ K.VisionTransformer(image_size=224, patch_size=16),+ K.ClassficationHead(num_classes=1000)+ )++ img = torch.rand(1, 3, 224, 224)+ out = classifier(img) # BxN+ scores = out.argmax(-1) # B++.. tip::+ More examples and trained models soon !!diff --git a/docs/source/references.bib b/docs/source/references.bibindex d6294c850..eca3f300f 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -1,4 +1,11 @@+@article{dosovitskiy2020vit,+ title={An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale},+ author={Dosovitskiy, Alexey and Beyer, Lucas and Kolesnikov, Alexander and Weissenborn, Dirk and Zhai, Xiaohua and Unterthiner, Thomas and Dehghani, Mostafa and Minderer, Matthias and Heigold, Georg and Gelly, Sylvain and Uszkoreit, Jakob and Houlsby, Neil},+ journal={ICLR},+ year={2021}+}+@inproceedings{DeFMO2021,title={DeFMO: Deblurring and Shape Recovery of Fast Moving Objects},author={Rozumnyi, Denys and Oswald, Martin R. and Ferrari, Vittorio and Matas, Jiri and Pollefeys, Marc},diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex 6100d0eb3..8bd95a55f 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -1,4 +1,6 @@+from kornia.contrib.classification import ClassificationHeadfrom kornia.contrib.connected_components import connected_componentsfrom kornia.contrib.extract_patches import extract_tensor_patches, ExtractTensorPatches+from kornia.contrib.vit import VisionTransformer__all__ = ["connected_components", "extract_tensor_patches", "ExtractTensorPatches"]diff --git a/kornia/contrib/classification.py b/kornia/contrib/classification.pynew file mode 100644index 000000000..81270299f--- /dev/null+++ b/kornia/contrib/classification.py@@ -0,0 +1,26 @@+"""Module containing utilities for classification."""+import torch+from torch import nn+++class ClassificationHead(nn.Module):+ """Module to be used as a classification head.++ Args:+ embed_size: the logits tensor coming from the networks.+ num_classes: an integer representing the numbers of classes to classify.++ Example:+ >>> feat = torch.rand(1, 256, 256)+ >>> head = ClassificationHead(256, 10)+ >>> head(feat).shape+ torch.Size([1, 10])+ """+ def __init__(self, embed_size: int = 768, num_classes: int = 10) -> None:+ super().__init__()+ self.norm = nn.LayerNorm(embed_size)+ self.linear = nn.Linear(embed_size, num_classes)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ out = x.mean(-2)+ return self.linear(self.norm(out))diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.pynew file mode 100644index 000000000..d689a1eaf--- /dev/null+++ b/kornia/contrib/vit.py@@ -0,0 +1,230 @@+"""Module that implement Vision Transformer (ViT).++Paper: https://paperswithcode.com/paper/an-image-is-worth-16x16-words-transformers-1++Based on: https://towardsdatascience.com/implementing-visualttransformer-in-pytorch-184f9f16f632+Added some tricks from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py+"""+from typing import List, Optional, Tuple++import torch+from torch import nn++__all__ = [+ "VisionTransformer"+]+++class ResidualAdd(nn.Module):+ def __init__(self, fn) -> None:+ super().__init__()+ self.fn = fn++ def forward(self, x, **kwargs) -> None:+ res = x+ x = self.fn(x, **kwargs)+ x += res+ return x+++class FeedForward(nn.Sequential):+ def __init__(self,+ in_features: int,+ hidden_features: int,+ out_features: int,+ dropout_rate: float = 0.) -> None:+ super().__init__(+ nn.Linear(in_features, hidden_features),+ nn.GELU(),+ nn.Dropout(dropout_rate),+ nn.Linear(hidden_features, out_features),+ nn.Dropout(dropout_rate) # added one extra as in timm+ )+++class MultiHeadAttention(nn.Module):+ def __init__(self, emb_size: int, num_heads: int, att_drop: float, proj_drop: float) -> None:+ super().__init__()+ self.emb_size = emb_size+ self.num_heads = num_heads+ head_size = emb_size // num_heads # fom timm+ self.scale = head_size ** -0.5 # from timm++ # fuse the queries, keys and values in one matrix+ self.qkv = nn.Linear(emb_size, emb_size * 3, bias=False)+ self.att_drop = nn.Dropout(att_drop)+ self.projection = nn.Linear(emb_size, emb_size)+ self.projection_drop = nn.Dropout(proj_drop) # added timm trick++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ B, N, C = x.shape+ # split keys, queries and values in num_heads+ # NOTE: the line below differs from timm+ # timm: qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)+ qkv = self.qkv(x).reshape(B, N, 3, -1, C).permute(2, 0, 3, 1, 4)+ q, k, v = qkv[0], qkv[1], qkv[2]++ # sum up over the last axis+ att = torch.einsum('bhqd, bhkd -> bhqk', q, k) * self.scale+ att = att.softmax(dim=-1)+ att = self.att_drop(att)++ # sum up over the third axis+ out = torch.einsum('bhal, bhlv -> bhav ', att, v)+ out = out.permute(0, 2, 1, 3).contiguous().view(B, N, -1)+ out = self.projection(out)+ out = self.projection_drop(out)+ return out+++class TransformerEncoderBlock(nn.Sequential):+ def __init__(self,+ embed_dim: int,+ num_heads: int,+ dropout_rate: float,+ dropout_attn: float) -> None:+ super().__init__(+ ResidualAdd(nn.Sequential(+ nn.LayerNorm(embed_dim),+ MultiHeadAttention(embed_dim, num_heads, dropout_attn, dropout_rate),+ nn.Dropout(dropout_rate)+ )),+ ResidualAdd(nn.Sequential(+ nn.LayerNorm(embed_dim),+ FeedForward(embed_dim, embed_dim, embed_dim, dropout_rate=dropout_rate),+ nn.Dropout(dropout_rate)+ )))+++class TransformerEncoder(nn.Module):+ def __init__(+ self,+ embed_dim: int = 768,+ depth: int = 12,+ num_heads: int = 12,+ dropout_rate: float = 0.,+ dropout_attn: float = 0.,+ ) -> None:+ super().__init__()+ self.blocks = nn.Sequential(*(+ TransformerEncoderBlock(embed_dim, num_heads, dropout_rate, dropout_attn)+ for _ in range(depth)+ ))+ self.results: List[torch.Tensor] = []++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ out = x+ for m in self.blocks.children():+ out = m(out)+ self.results.append(out)+ return out+++class PatchEmbedding(nn.Module):+ """Compute the 2d image patch embedding ready to pass to transformer encoder."""+ def __init__(+ self,+ in_channels: int = 3,+ out_channels: int = 768,+ patch_size: int = 16,+ image_size: int = 224,+ backbone: Optional[nn.Module] = None,+ ) -> None:+ super().__init__()+ self.in_channels = in_channels+ self.out_channels = out_channels+ self.patch_size = patch_size++ # logic needed in case a backbone is passed+ self.backbone = backbone or nn.Conv2d(in_channels, out_channels, kernel_size=patch_size, stride=patch_size)+ if backbone is not None:+ out_channels, feat_size = self._compute_feats_dims((in_channels, image_size, image_size))+ self.out_channels = out_channels+ else:+ feat_size = (image_size // patch_size) ** 2++ self.cls_token = nn.Parameter(torch.randn(1, 1, out_channels))+ self.positions = nn.Parameter(torch.randn(feat_size + 1, out_channels))++ def _compute_feats_dims(self, image_size: Tuple[int, int]) -> Tuple[int]:+ out = self.backbone(torch.zeros(1, *image_size)).detach()+ return out.shape[-3], out.shape[-2] * out.shape[-1]++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ x = self.backbone(x)+ B, N, _, _ = x.shape+ x = x.view(B, N, -1).permute(0, 2, 1) # BxNxE+ cls_tokens = self.cls_token.repeat(B, 1, 1) # Bx1xE+ # prepend the cls token to the input+ x = torch.cat([cls_tokens, x], dim=1) # Bx(N+1)xE+ # add position embedding+ x += self.positions+ return x+++class VisionTransformer(nn.Module):+ """Vision transformer (ViT) module.++ The module is expected to be used as operator for different vision tasks.++ The method is inspired from existing implementations of the paper :cite:`dosovitskiy2020vit`.++ .. warning::+ This is an experimental API subject to changes in favor of flexibility.++ Args:+ image_size: the size of the input image.+ patch_size: the size of the patch to compute the embedding.+ in_channels: the number of channels for the input.+ embed_dim: the embedding dimension inside the transformer encoder.+ depth: the depth of the transformer.+ num_heads: the number of attention heads.+ dropout_rate: dropout rate.+ dropout_attn: attention dropout rate.+ backbone: an nn.Module to compute the image patches embeddings.++ Example:+ >>> img = torch.rand(1, 3, 224, 224)+ >>> vit = VisionTransformer(image_size=224, patch_size=16)+ >>> vit(img).shape+ torch.Size([1, 197, 768])+ """+ def __init__(+ self,+ image_size: int = 224,+ patch_size: int = 16,+ in_channels: int = 3,+ embed_dim: int = 768,+ depth: int = 12,+ num_heads: int = 12,+ dropout_rate: float = 0.,+ dropout_attn: float = 0.,+ backbone: Optional[nn.Module] = None,+ ) -> None:+ super().__init__()+ self.image_size = image_size+ self.patch_size = patch_size+ self.in_channels = in_channels+ self.embed_size = embed_dim++ self.patch_embedding = PatchEmbedding(in_channels, embed_dim, patch_size, image_size, backbone)+ hidden_dim = self.patch_embedding.out_channels+ self.encoder = TransformerEncoder(hidden_dim, depth, num_heads, dropout_rate, dropout_attn)++ @property+ def encoder_results(self):+ return self.encoder.results++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ if not isinstance(x, torch.Tensor):+ raise TypeError(f"Input x type is not a torch.Tensor. Got: {type(x)}")++ if self.image_size not in (*x.shape[-2:],) and x.shape[-3] != self.in_channels:+ raise ValueError(+ f"Input image shape must be Bx{self.in_channels}x{self.image_size}x{self.image_size}. "+ f"Got: {x.shape}"+ )++ out = self.patch_embedding(x)+ out = self.encoder(out)+ return outdiff --git a/test/test_contrib.py b/test/test_contrib.pyindex 778ef85b6..d2b82c901 100644--- a/test/test_contrib.py+++ b/test/test_contrib.py@@ -8,6 +8,45 @@ from kornia.testing import assert_closefrom packaging import version+class TestVisionTransformer:+ @pytest.mark.parametrize("B", [1, 2])+ @pytest.mark.parametrize("H", [1, 3, 8])+ @pytest.mark.parametrize("D", [128, 768])+ @pytest.mark.parametrize("image_size", [32, 224])+ def test_smoke(self, device, dtype, B, H, D, image_size):+ patch_size = 16+ T = image_size**2 // patch_size**2 + 1 # tokens size++ img = torch.rand(B, 3, image_size, image_size, device=device, dtype=dtype)+ vit = kornia.contrib.VisionTransformer(+ image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)++ out = vit(img)+ assert isinstance(out, torch.Tensor) and out.shape == (B, T, D)++ feats = vit.encoder_results+ assert isinstance(feats, list) and len(feats) == 12+ for f in feats:+ assert f.shape == (B, T, D)++ def test_backbone(self, device, dtype):+ def backbone_mock(x):+ return torch.ones(1, 128, 14, 14, device=device, dtype=dtype)+ img = torch.rand(1, 3, 32, 32, device=device, dtype=dtype)+ vit = kornia.contrib.VisionTransformer(backbone=backbone_mock).to(device, dtype)+ out = vit(img)+ assert out.shape == (1, 197, 128)+++class TestClassificationHead:+ @pytest.mark.parametrize("B, D, N", [(1, 8, 10), (2, 2, 5)])+ def test_smoke(self, device, dtype, B, D, N):+ feat = torch.rand(B, D, D, device=device, dtype=dtype)+ head = kornia.contrib.ClassificationHead(embed_size=D, num_classes=N).to(device, dtype)+ logits = head(feat)+ assert logits.shape == (B, N)++class TestConnectedComponents:def test_smoke(self, device, dtype):img = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)