Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
  1. """Vision Transformer in PyTorch.
  2. Reference:
  3. [1] Dosovitskiy, Alexey, et al. "An image is worth 16x16 words: Transformers for image recognition at scale."
  4. arXiv preprint arXiv:2010.11929 (2020)
  5. Code adapted from https://github.com/lucidrains/vit-pytorch/blob/main/vit_pytorch/vit.py
  6. """
  7. import torch
  8. from torch import nn
  9. from super_gradients.training.models import SgModule
  10. from super_gradients.training.utils import get_param
  11. from einops import repeat
  12. class PatchEmbed(nn.Module):
  13. """
  14. 2D Image to Patch Embedding Using Conv layers (Faster than rearranging + Linear)
  15. """
  16. def __init__(self, img_size: tuple, patch_size: tuple, in_channels=3, hidden_dim=768, norm_layer=None, flatten=True):
  17. super().__init__()
  18. self.img_size = img_size
  19. self.patch_size = patch_size
  20. self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
  21. self.num_patches = self.grid_size[0] * self.grid_size[1]
  22. self.flatten = flatten
  23. self.proj = nn.Conv2d(in_channels, hidden_dim, kernel_size=patch_size, stride=patch_size)
  24. self.norm = norm_layer(hidden_dim) if norm_layer else nn.Identity()
  25. def forward(self, x):
  26. x = self.proj(x)
  27. if self.flatten:
  28. x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
  29. x = self.norm(x)
  30. return x
  31. class FeedForward(nn.Module):
  32. '''
  33. feed forward block with residual connection
  34. '''
  35. def __init__(self, hidden_dim, mlp_dim, dropout=0.):
  36. super().__init__()
  37. self.fc1 = nn.Linear(hidden_dim, mlp_dim)
  38. self.act = nn.GELU()
  39. self.dropout = nn.Dropout(dropout)
  40. self.fc2 = nn.Linear(mlp_dim, hidden_dim)
  41. def forward(self, x):
  42. out = self.fc1(x)
  43. out = self.act(out)
  44. out = self.dropout(out)
  45. out = self.fc2(out)
  46. out = self.dropout(out)
  47. return out
  48. class Attention(nn.Module):
  49. '''
  50. self attention layer with residual connection
  51. '''
  52. def __init__(self, hidden_dim, heads=8):
  53. super().__init__()
  54. dim_head = hidden_dim // heads
  55. inner_dim = dim_head * heads
  56. self.heads = heads
  57. self.scale = dim_head ** -0.5
  58. self.attend = nn.Softmax(dim=-1)
  59. self.to_qkv = nn.Linear(hidden_dim, inner_dim * 3, bias=True) # Qx, Kx, Vx are calculated at once
  60. self.proj = nn.Linear(hidden_dim, hidden_dim)
  61. def forward(self, x):
  62. B, N, C = x.shape
  63. # computing query, key and value matrices at once
  64. qkv = self.to_qkv(x).reshape(B, N, 3, self.heads, C // self.heads).permute(2, 0, 3, 1, 4)
  65. q, k, v = qkv[0], qkv[1], qkv[2]
  66. attn = (q @ k.transpose(-2, -1)) * self.scale
  67. attn = attn.softmax(dim=-1)
  68. out = (attn @ v).transpose(1, 2).reshape(B, N, C)
  69. out = self.proj(out)
  70. return out
  71. class TransformerBlock(nn.Module):
  72. def __init__(self, hidden_dim, heads, mlp_dim, dropout_prob=0.):
  73. super().__init__()
  74. self.layers = nn.ModuleList([])
  75. self.norm1 = nn.LayerNorm(hidden_dim, eps=1e-6)
  76. self.attn = Attention(hidden_dim, heads=heads)
  77. self.norm2 = nn.LayerNorm(hidden_dim, eps=1e-6)
  78. self.mlp = FeedForward(hidden_dim, mlp_dim, dropout=dropout_prob)
  79. def forward(self, x):
  80. x = self.attn(self.norm1(x)) + x
  81. x = self.mlp(self.norm2(x)) + x
  82. return x
  83. class Transformer(nn.Module):
  84. def __init__(self, hidden_dim, depth, heads, mlp_dim, dropout_prob=0.):
  85. super().__init__()
  86. self.blocks = nn.ModuleList([])
  87. for _ in range(depth):
  88. self.blocks.append(TransformerBlock(hidden_dim, heads, mlp_dim, dropout_prob=dropout_prob))
  89. def forward(self, x):
  90. for block in self.blocks:
  91. x = block(x)
  92. return x
  93. class ViT(SgModule):
  94. def __init__(self, image_size: tuple, patch_size: tuple, num_classes: int, hidden_dim: int, depth: int, heads: int,
  95. mlp_dim: int, in_channels=3, dropout_prob=0., emb_dropout_prob=0., backbone_mode=False):
  96. '''
  97. :param image_size: Image size tuple for data processing into patches done within the model.
  98. :param patch_size: Patch size tuple for data processing into patches done within the model.
  99. :param num_classes: Number of classes for the classification head.
  100. :param hidden_dim: Output dimension of each transformer block.
  101. :param depth: Number of transformer blocks
  102. :param heads: Number of attention heads
  103. :param mlp_dim: Intermediate dimension of the transformer block's feed forward
  104. :param in_channels: input channels
  105. :param dropout: Dropout ratio between the feed forward layers.
  106. :param emb_dropout: Dropout ratio between after the embedding layer
  107. :param backbone_mode: If True output after pooling layer
  108. '''
  109. super().__init__()
  110. image_height, image_width = image_size
  111. patch_height, patch_width = patch_size
  112. assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'
  113. assert hidden_dim % heads == 0, 'Hidden dimension must be divisible by the number of heads.'
  114. num_patches = (image_height // patch_height) * (image_width // patch_width)
  115. self.patch_embedding = PatchEmbed(image_size, patch_size, in_channels=in_channels, hidden_dim=hidden_dim)
  116. self.cls_token = nn.Parameter(torch.randn(1, 1, hidden_dim))
  117. self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, hidden_dim))
  118. self.dropout = nn.Dropout(emb_dropout_prob)
  119. self.transformer = Transformer(hidden_dim, depth, heads, mlp_dim, dropout_prob)
  120. self.backbone_mode = backbone_mode
  121. self.pre_head_norm = nn.LayerNorm(hidden_dim, eps=1e-6)
  122. self.head = nn.Linear(hidden_dim, num_classes)
  123. def forward(self, img):
  124. x = self.patch_embedding(img) # Convert image to patches and embed
  125. b, n, _ = x.shape
  126. cls_tokens = repeat(self.cls_token, '() n d -> b n d', b=b)
  127. x = torch.cat((cls_tokens, x), dim=1)
  128. x += self.pos_embedding[:, :(n + 1)]
  129. x = self.dropout(x)
  130. x = self.transformer(x)
  131. x = self.pre_head_norm(x)
  132. x = x[:, 0]
  133. if self.backbone_mode:
  134. return x
  135. else:
  136. return self.head(x)
  137. def replace_head(self, new_num_classes=None, new_head=None):
  138. if new_num_classes is None and new_head is None:
  139. raise ValueError("At least one of new_num_classes, new_head must be given to replace output layer.")
  140. if new_head is not None:
  141. self.head = new_head
  142. else:
  143. self.head = nn.Linear(self.head.in_features, new_num_classes)
  144. class ViTBase(ViT):
  145. def __init__(self, arch_params, num_classes=None, backbone_mode=None):
  146. super(ViTBase, self).__init__(image_size=get_param(arch_params, "image_size", (224, 224)),
  147. patch_size=get_param(arch_params, "patch_size", (16, 16)),
  148. num_classes=num_classes or arch_params.num_classes,
  149. hidden_dim=768, depth=12, heads=12, mlp_dim=3072,
  150. in_channels=get_param(arch_params, 'in_channels', 3),
  151. dropout_prob=get_param(arch_params, "dropout_prob", 0),
  152. emb_dropout_prob=get_param(arch_params, "emb_dropout_prob", 0),
  153. backbone_mode=backbone_mode)
  154. class ViTLarge(ViT):
  155. def __init__(self, arch_params, num_classes=None, backbone_mode=None):
  156. super(ViTLarge, self).__init__(image_size=get_param(arch_params, "image_size", (224, 224)),
  157. patch_size=get_param(arch_params, "patch_size", (16, 16)),
  158. num_classes=num_classes or arch_params.num_classes,
  159. hidden_dim=1024, depth=24, heads=16, mlp_dim=4096,
  160. in_channels=get_param(arch_params, 'in_channels', 3),
  161. dropout_prob=get_param(arch_params, "dropout_prob", 0),
  162. emb_dropout_prob=get_param(arch_params, "emb_dropout_prob", 0),
  163. backbone_mode=backbone_mode)
  164. class ViTHuge(ViT):
  165. def __init__(self, arch_params, num_classes=None, backbone_mode=None):
  166. super(ViTHuge, self).__init__(image_size=get_param(arch_params, "image_size", (224, 224)),
  167. patch_size=get_param(arch_params, "patch_size", (16, 16)),
  168. num_classes=num_classes or arch_params.num_classes,
  169. hidden_dim=1280, depth=32, heads=16, mlp_dim=5120,
  170. in_channels=get_param(arch_params, 'in_channels', 3),
  171. dropout_prob=get_param(arch_params, "dropout_prob", 0),
  172. emb_dropout_prob=get_param(arch_params, "emb_dropout_prob", 0),
  173. backbone_mode=backbone_mode)
Discard
Tip!

Press p or to see the previous file or, n or to see the next file