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

#875 Feature/sg 761 yolo nas

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

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