-
Notifications
You must be signed in to change notification settings - Fork 0
/
vision_transformer.py
52 lines (34 loc) · 2.1 KB
/
vision_transformer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import torch
from torch import nn
from patch_embedding import PatchEmbedding
from kan import KANLinear
class VisionTransformer(nn.Module):
def __init__(self, num_patches, img_size, num_classes, patch_size, embed_dim, num_encoders, num_heads, hidden_dim, dropout, activation, in_channels):
super().__init__()
self.embeddings_block = PatchEmbedding(embed_dim, patch_size, num_patches, dropout, in_channels)
encoder_layer = nn.TransformerEncoderLayer(d_model = embed_dim, nhead = num_heads, dropout = dropout, activation = activation, batch_first = True, norm_first = True)
self.encoder_blocks = nn.TransformerEncoder(encoder_layer, num_layers = num_encoders)
self.mlp_head = nn.Sequential(
nn.LayerNorm(normalized_shape = embed_dim),
nn.Linear(in_features = embed_dim, out_features = num_classes)
)
def forward(self, x):
x = self.embeddings_block(x)
x = self.encoder_blocks(x)
x = self.mlp_head(x[:, 0, :]) # taking only cls_token
return x
class VisionTransformerKAN(nn.Module):
def __init__(self, num_patches, img_size, num_classes, patch_size, embed_dim, num_encoders, num_heads, hidden_dim, dropout, activation, in_channels):
super().__init__()
self.embeddings_block = PatchEmbedding(embed_dim, patch_size, num_patches, dropout, in_channels)
encoder_layer = nn.TransformerEncoderLayer(d_model = embed_dim, nhead = num_heads, dropout = dropout, activation = activation, batch_first = True, norm_first = True)
self.encoder_blocks = nn.TransformerEncoder(encoder_layer, num_layers = num_encoders)
self.kan_head = nn.Sequential(
nn.LayerNorm(normalized_shape = embed_dim),
KANLinear(in_features = embed_dim, out_features = num_classes)
)
def forward(self, x):
x = self.embeddings_block(x)
x = self.encoder_blocks(x)
x = self.kan_head(x[:, 0, :]) # taking only cls_token
return x