Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix of multi head attention implementation (#2589)

Yaroslav Romanus637d1a5f66c9
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index 614c30ac6..69bc06375 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -47,6 +47,13 @@ class MultiHeadAttention(Module):
head_size = emb_size // num_heads # from timm
self.scale = head_size**-0.5 # from timm
+ if self.emb_size % self.num_heads:
+ raise ValueError(
+ f"Size of embedding inside the transformer decoder must be visible by number of heads"
+ f"for correct multi-head attention "
+ f"Got: {self.emb_size} embedding size and {self.num_heads} numbers of heads"
+ )
+
# 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)
@@ -58,7 +65,7 @@ class MultiHeadAttention(Module):
# 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)
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
# sum up over the last axis
diff --git a/test/contrib/test_contrib.py b/test/contrib/test_contrib.py
index a00d06779..782f60e40 100644
--- a/test/contrib/test_contrib.py
+++ b/test/contrib/test_contrib.py
@@ -42,7 +42,7 @@ class TestDiamondSquare:
class TestVisionTransformer:
@pytest.mark.parametrize("B", [1, 2])
@pytest.mark.parametrize("H", [1, 3, 8])
- @pytest.mark.parametrize("D", [128, 768])
+ @pytest.mark.parametrize("D", [240, 768])
@pytest.mark.parametrize("image_size", [32, 224])
def test_smoke(self, device, dtype, B, H, D, image_size):
patch_size = 16
@@ -61,12 +61,19 @@ class TestVisionTransformer:
for f in feats:
assert f.shape == (B, T, D)
+ @pytest.mark.parametrize("H", [3, 8])
+ @pytest.mark.parametrize("D", [245, 1001])
+ @pytest.mark.parametrize("image_size", [32, 224])
+ def test_exception(self, device, dtype, H, D, image_size):
+ with pytest.raises(ValueError):
+ kornia.contrib.VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)
+
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)
+ vit = kornia.contrib.VisionTransformer(backbone=backbone_mock, num_heads=8).to(device, dtype)
out = vit(img)
assert out.shape == (1, 197, 128)