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

#378 Feature/sg 281 add kd notebook

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-281-add_kd_notebook
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
  1. """
  2. CSP Darknet
  3. """
  4. import math
  5. from typing import Tuple, Type
  6. import torch
  7. import torch.nn as nn
  8. from super_gradients.training.utils.utils import get_param, HpmStruct
  9. from super_gradients.training.models.sg_module import SgModule
  10. def autopad(kernel, padding=None):
  11. # PAD TO 'SAME'
  12. if padding is None:
  13. padding = kernel // 2 if isinstance(kernel, int) else [x // 2 for x in kernel]
  14. return padding
  15. def width_multiplier(original, factor, divisor: int = None):
  16. if divisor is None:
  17. return int(original * factor)
  18. else:
  19. return math.ceil(int(original * factor) / divisor) * divisor
  20. def get_yolo_type_params(yolo_type: str, width_mult_factor: float, depth_mult_factor: float):
  21. if yolo_type == 'yoloX':
  22. struct = (3, 9, 9, 3)
  23. block = CSPLayer
  24. activation_type = nn.SiLU
  25. width_mult = lambda channels: width_multiplier(channels, width_mult_factor)
  26. else:
  27. raise NotImplementedError(f'Yolo yolo_type {yolo_type} is not supported')
  28. depth_mult = lambda blocks: max(round(blocks * depth_mult_factor), 1) if blocks > 1 else blocks
  29. return struct, block, activation_type, width_mult, depth_mult
  30. class NumClassesMissingException(Exception):
  31. pass
  32. class Conv(nn.Module):
  33. # STANDARD CONVOLUTION
  34. def __init__(self, input_channels, output_channels, kernel, stride, activation_type: Type[nn.Module],
  35. padding: int = None, groups: int = None):
  36. super().__init__()
  37. self.conv = nn.Conv2d(input_channels, output_channels, kernel, stride, autopad(kernel, padding),
  38. groups=groups or 1, bias=False)
  39. self.bn = nn.BatchNorm2d(output_channels)
  40. self.act = activation_type()
  41. def forward(self, x):
  42. return self.act(self.bn(self.conv(x)))
  43. def fuseforward(self, x):
  44. return self.act(self.conv(x))
  45. class GroupedConvBlock(nn.Module):
  46. """
  47. Grouped Conv KxK -> usual Conv 1x1
  48. """
  49. def __init__(self, input_channels, output_channels, kernel, stride, activation_type: Type[nn.Module],
  50. padding: int = None, groups: int = None):
  51. """
  52. :param groups: num of groups in the first conv; if None depthwise separable conv will be used
  53. (groups = input channels)
  54. """
  55. super().__init__()
  56. self.dconv = Conv(input_channels, input_channels, kernel, stride, activation_type, padding,
  57. groups=groups or input_channels)
  58. self.conv = Conv(input_channels, output_channels, 1, 1, activation_type)
  59. def forward(self, x):
  60. return self.conv(self.dconv(x))
  61. class Bottleneck(nn.Module):
  62. # STANDARD BOTTLENECK
  63. def __init__(self, input_channels, output_channels, shortcut: bool, activation_type: Type[nn.Module],
  64. depthwise=False):
  65. super().__init__()
  66. ConvBlock = GroupedConvBlock if depthwise else Conv
  67. hidden_channels = output_channels
  68. self.cv1 = Conv(input_channels, hidden_channels, 1, 1, activation_type)
  69. self.cv2 = ConvBlock(hidden_channels, output_channels, 3, 1, activation_type)
  70. self.add = shortcut and input_channels == output_channels
  71. def forward(self, x):
  72. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  73. class CSPLayer(nn.Module):
  74. """
  75. CSP Bottleneck with 3 convolutions
  76. Args:
  77. in_channels: int, input channels.
  78. out_channels: int, output channels.
  79. num_bottlenecks: int, number of bottleneck conv layers.
  80. act: Type[nn.module], activation type.
  81. shortcut: bool, whether to apply shortcut (i.e add input to result) in bottlenecks (default=True).
  82. depthwise: bool, whether to use GroupedConvBlock in last conv in bottlenecks (default=False).
  83. expansion: float, determines the number of hidden channels (default=0.5).
  84. """
  85. def __init__(
  86. self,
  87. in_channels: int,
  88. out_channels: int,
  89. num_bottlenecks: int,
  90. act: Type[nn.Module],
  91. shortcut: bool = True,
  92. depthwise: bool = False,
  93. expansion: float = 0.5,
  94. ):
  95. super().__init__()
  96. hidden_channels = int(out_channels * expansion)
  97. self.conv1 = Conv(in_channels, hidden_channels, 1, stride=1, activation_type=act)
  98. self.conv2 = Conv(in_channels, hidden_channels, 1, stride=1, activation_type=act)
  99. self.conv3 = Conv(2 * hidden_channels, out_channels, 1, stride=1, activation_type=act)
  100. module_list = [
  101. Bottleneck(
  102. hidden_channels, hidden_channels, shortcut, act, depthwise
  103. )
  104. for _ in range(num_bottlenecks)
  105. ]
  106. self.bottlenecks = nn.Sequential(*module_list)
  107. def forward(self, x):
  108. x_1 = self.conv1(x)
  109. x_1 = self.bottlenecks(x_1)
  110. x_2 = self.conv2(x)
  111. x = torch.cat((x_1, x_2), dim=1)
  112. return self.conv3(x)
  113. class BottleneckCSP(nn.Module):
  114. # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
  115. def __init__(self, input_channels, output_channels, bottleneck_blocks_num, activation_type: Type[nn.Module],
  116. shortcut=True, depthwise=False, expansion=0.5):
  117. super().__init__()
  118. hidden_channels = int(output_channels * expansion)
  119. self.cv1 = Conv(input_channels, hidden_channels, 1, 1, activation_type)
  120. self.cv2 = nn.Conv2d(input_channels, hidden_channels, 1, 1, bias=False)
  121. self.cv3 = nn.Conv2d(hidden_channels, hidden_channels, 1, 1, bias=False)
  122. self.cv4 = Conv(2 * hidden_channels, output_channels, 1, 1, activation_type)
  123. self.bn = nn.BatchNorm2d(2 * hidden_channels) # APPLIED TO CAT(CV2, CV3)
  124. self.act = nn.LeakyReLU(0.1, inplace=True)
  125. self.m = nn.Sequential(*[Bottleneck(hidden_channels, hidden_channels, shortcut, activation_type, depthwise)
  126. for _ in range(bottleneck_blocks_num)])
  127. def forward(self, x):
  128. y1 = self.cv3(self.m(self.cv1(x)))
  129. y2 = self.cv2(x)
  130. return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
  131. class SPP(nn.Module):
  132. # SPATIAL PYRAMID POOLING LAYER
  133. def __init__(self, input_channels, output_channels, k: Tuple, activation_type: Type[nn.Module]):
  134. super().__init__()
  135. hidden_channels = input_channels // 2
  136. self.cv1 = Conv(input_channels, hidden_channels, 1, 1, activation_type)
  137. self.cv2 = Conv(hidden_channels * (len(k) + 1), output_channels, 1, 1, activation_type)
  138. self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
  139. def forward(self, x):
  140. x = self.cv1(x)
  141. return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
  142. class ViewModule(nn.Module):
  143. """
  144. Returns a reshaped version of the input, to be used in None-Backbone Mode
  145. """
  146. def __init__(self, features=1024):
  147. super(ViewModule, self).__init__()
  148. self.features = features
  149. def forward(self, x):
  150. return x.view(-1, self.features)
  151. class CSPDarknet53(SgModule):
  152. def __init__(self, arch_params: HpmStruct):
  153. super().__init__()
  154. self.num_classes = arch_params.num_classes
  155. self.backbone_mode = get_param(arch_params, 'backbone_mode', False)
  156. depth_mult_factor = get_param(arch_params, 'depth_mult_factor', 1.)
  157. width_mult_factor = get_param(arch_params, 'width_mult_factor', 1.)
  158. channels_in = get_param(arch_params, 'channels_in', 3)
  159. yolo_type = get_param(arch_params, 'yolo_type', 'yoloX')
  160. depthwise = get_param(arch_params, 'depthwise', False)
  161. struct, block, activation_type, width_mult, depth_mult = get_yolo_type_params(yolo_type,
  162. width_mult_factor,
  163. depth_mult_factor)
  164. ConvBlock = Conv if not depthwise else GroupedConvBlock
  165. struct = [depth_mult(s) for s in struct]
  166. self._modules_list = nn.ModuleList()
  167. if get_param(arch_params, 'stem_type') == '6x6' or yolo_type == 'yoloX':
  168. self._modules_list.append(Conv(channels_in, width_mult(64), 6, 2, activation_type, padding=2)) # 0
  169. else:
  170. raise NotImplementedError(f'Yolo type: {yolo_type} is not supported')
  171. for i, layer_in_ch in enumerate([64, 128, 256, 512]):
  172. self._modules_list.append(
  173. ConvBlock(width_mult(layer_in_ch), width_mult(layer_in_ch * 2), 3, 2, activation_type)) # 1,3,5,7
  174. if i < 3:
  175. self._modules_list.append(
  176. block(width_mult(layer_in_ch * 2), width_mult(layer_in_ch * 2), struct[i], activation_type,
  177. depthwise=depthwise)) # 2,4,6
  178. if yolo_type == 'yoloX':
  179. self._modules_list.append(SPP(width_mult(1024), width_mult(1024), (5, 9, 13), activation_type)) # 8
  180. self._modules_list.append(
  181. block(width_mult(1024), width_mult(1024), struct[3], activation_type, False, depthwise=depthwise)) # 9
  182. else:
  183. raise NotImplementedError(f'Yolo type: {yolo_type} is not supported')
  184. if not self.backbone_mode:
  185. # IF NOT USED AS A BACKEND BUT AS A CLASSIFIER WE ADD THE CLASSIFICATION LAYERS
  186. self._modules_list.append(nn.AdaptiveAvgPool2d((1, 1)))
  187. self._modules_list.append(ViewModule(1024))
  188. self._modules_list.append(nn.Linear(1024, self.num_classes))
  189. def forward(self, x):
  190. return self._modules_list(x)
Discard
Tip!

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