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

csp_darknet53.py 10 KB

You have to be logged in to leave a comment. Sign In
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
  1. """
  2. CSP Darknet
  3. credits: https://github.com/ultralytics
  4. """
  5. import torch
  6. import torch.nn as nn
  7. from super_gradients.training.utils.utils import get_param, HpmStruct
  8. from super_gradients.training.models.sg_module import SgModule
  9. def autopad(kernel, padding=None):
  10. # PAD TO 'SAME'
  11. if padding is None:
  12. padding = kernel // 2 if isinstance(kernel, int) else [x // 2 for x in kernel]
  13. return padding
  14. def width_multiplier(original, factor):
  15. return int(original * factor)
  16. class NumClassesMissingException(Exception):
  17. pass
  18. class Conv(nn.Module):
  19. # STANDARD CONVOLUTION
  20. def __init__(self, input_channels, output_channels, kernel=1, stride=1, padding=None, groups=1,
  21. activation_func_type: type = nn.Hardswish):
  22. super().__init__()
  23. self.conv = nn.Conv2d(input_channels, output_channels, kernel, stride, autopad(kernel, padding), groups=groups,
  24. bias=False)
  25. self.bn = nn.BatchNorm2d(output_channels)
  26. self.act = activation_func_type()
  27. def forward(self, x):
  28. return self.act(self.bn(self.conv(x)))
  29. def fuseforward(self, x):
  30. return self.act(self.conv(x))
  31. class Bottleneck(nn.Module):
  32. # STANDARD BOTTLENECK
  33. def __init__(self, input_channels, output_channels, shortcut=True, groups=1,
  34. width_mult_factor: float = 1.0,
  35. activation_func_type: type = nn.Hardswish):
  36. super().__init__()
  37. input_channels = width_multiplier(input_channels, width_mult_factor)
  38. output_channels = width_multiplier(output_channels, width_mult_factor)
  39. hidden_channels = output_channels
  40. self.cv1 = Conv(input_channels, hidden_channels, 1, 1, activation_func_type=activation_func_type)
  41. self.cv2 = Conv(hidden_channels, output_channels, 3, 1, groups=groups, activation_func_type=activation_func_type)
  42. self.add = shortcut and input_channels == output_channels
  43. def forward(self, x):
  44. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  45. class C3(nn.Module):
  46. # CSP Bottleneck with 3 convolutions https://github.com/ultralytics/yolov5
  47. def __init__(self, input_channels, output_channels, bottleneck_blocks_num=1, shortcut=True, groups=1, expansion=0.5,
  48. width_mult_factor: float = 1.0, depth_mult_factor: float = 1.0,
  49. activation_func_type: type = nn.SiLU):
  50. super().__init__()
  51. input_channels = width_multiplier(input_channels, width_mult_factor)
  52. output_channels = width_multiplier(output_channels, width_mult_factor)
  53. hidden_channels = int(output_channels * expansion)
  54. bottleneck_blocks_num = max(round(bottleneck_blocks_num * depth_mult_factor),
  55. 1) if bottleneck_blocks_num > 1 else bottleneck_blocks_num
  56. self.cv1 = Conv(input_channels, hidden_channels, 1, 1, activation_func_type=activation_func_type)
  57. self.cv2 = Conv(input_channels, hidden_channels, 1, 1, activation_func_type=activation_func_type)
  58. self.cv3 = Conv(2 * hidden_channels, output_channels, 1, activation_func_type=activation_func_type)
  59. self.m = nn.Sequential(*[Bottleneck(hidden_channels, hidden_channels, shortcut, groups,
  60. activation_func_type=activation_func_type) for _ in
  61. range(bottleneck_blocks_num)])
  62. def forward(self, x):
  63. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
  64. class BottleneckCSP(nn.Module):
  65. # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
  66. def __init__(self, input_channels, output_channels, bottleneck_blocks_num=1, shortcut=True, groups=1, expansion=0.5,
  67. width_mult_factor: float = 1.0, depth_mult_factor: float = 1.0):
  68. super().__init__()
  69. input_channels = width_multiplier(input_channels, width_mult_factor)
  70. output_channels = width_multiplier(output_channels, width_mult_factor)
  71. hidden_channels = int(output_channels * expansion)
  72. bottleneck_blocks_num = max(round(bottleneck_blocks_num * depth_mult_factor),
  73. 1) if bottleneck_blocks_num > 1 else bottleneck_blocks_num
  74. self.cv1 = Conv(input_channels, hidden_channels, 1, 1)
  75. self.cv2 = nn.Conv2d(input_channels, hidden_channels, 1, 1, bias=False)
  76. self.cv3 = nn.Conv2d(hidden_channels, hidden_channels, 1, 1, bias=False)
  77. self.cv4 = Conv(2 * hidden_channels, output_channels, 1, 1)
  78. self.bn = nn.BatchNorm2d(2 * hidden_channels) # APPLIED TO CAT(CV2, CV3)
  79. self.act = nn.LeakyReLU(0.1, inplace=True)
  80. self.m = nn.Sequential(*[Bottleneck(hidden_channels, hidden_channels, shortcut, groups) for _ in
  81. range(bottleneck_blocks_num)])
  82. def forward(self, x):
  83. y1 = self.cv3(self.m(self.cv1(x)))
  84. y2 = self.cv2(x)
  85. return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
  86. class SPP(nn.Module):
  87. # SPATIAL PYRAMID POOLING LAYER USED IN YOLOV3-SPP
  88. def __init__(self, input_channels, output_channels, k=(5, 9, 13), width_mult_factor: float = 1.0):
  89. super().__init__()
  90. input_channels = width_multiplier(input_channels, width_mult_factor)
  91. output_channels = width_multiplier(output_channels, width_mult_factor)
  92. hidden_channels = input_channels // 2
  93. self.cv1 = Conv(input_channels, hidden_channels, 1, 1)
  94. self.cv2 = Conv(hidden_channels * (len(k) + 1), output_channels, 1, 1)
  95. self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
  96. def forward(self, x):
  97. x = self.cv1(x)
  98. return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
  99. class SPPF(nn.Module):
  100. # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher https://github.com/ultralytics/yolov5
  101. # equivalent to SPP(k=(5, 9, 13))
  102. def __init__(self, input_channels, output_channels, k: int = 5, width_mult_factor: float = 1.0,
  103. activation_func_type: type = nn.SiLU):
  104. super().__init__()
  105. input_channels = width_multiplier(input_channels, width_mult_factor)
  106. output_channels = width_multiplier(output_channels, width_mult_factor)
  107. hidden_channels = input_channels // 2 # hidden channels
  108. self.cv1 = Conv(input_channels, hidden_channels, 1, 1, activation_func_type=activation_func_type)
  109. self.cv2 = Conv(hidden_channels * 4, output_channels, 1, 1, activation_func_type=activation_func_type)
  110. self.maxpool = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
  111. def forward(self, x):
  112. x = self.cv1(x)
  113. y1 = self.maxpool(x)
  114. y2 = self.maxpool(y1)
  115. return self.cv2(torch.cat([x, y1, y2, self.maxpool(y2)], 1))
  116. class Focus(nn.Module):
  117. # FOCUS WH INFORMATION INTO C-SPACE
  118. def __init__(self, input_channels, output_channels, kernel=1, stride=1, padding=None, groups=1,
  119. width_mult_factor: float = 1.0):
  120. super().__init__()
  121. output_channels = width_multiplier(output_channels, width_mult_factor)
  122. self.conv = Conv(input_channels * 4, output_channels, kernel, stride, padding, groups)
  123. def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
  124. return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
  125. class ViewModule(nn.Module):
  126. """
  127. Returns a reshaped version of the input, to be used in None-Backbone Mode
  128. """
  129. def __init__(self, features=1024):
  130. super(ViewModule, self).__init__()
  131. self.features = features
  132. def forward(self, x):
  133. return x.view(-1, self.features)
  134. class CSPDarknet53(SgModule):
  135. def __init__(self, arch_params: HpmStruct):
  136. super().__init__()
  137. self.num_classes = arch_params.num_classes
  138. self.backbone_mode = get_param(arch_params, 'backbone_mode', False)
  139. self.depth_mult_factor = get_param(arch_params, 'depth_mult_factor', 1.)
  140. self.width_mult_factor = get_param(arch_params, 'width_mult_factor', 1.)
  141. self.channels_in = get_param(arch_params, 'channels_in', 3)
  142. self.struct = get_param(arch_params, 'backbone_struct', [3, 9, 9, 3])
  143. width_mult = lambda channels: width_multiplier(channels, self.width_mult_factor)
  144. # # THE MODULES LIST IS APPROACHABLE FROM "OUTSIDE THE CLASS - SO WE CAN CHANGE IT'S STRUCTURE"
  145. self._modules_list = nn.ModuleList()
  146. # THE MODULES LIST IS APPROACHABLE FROM "OUTSIDE THE CLASS - SO WE CAN CHANGE IT'S STRUCTURE"
  147. self._modules_list.append(Focus(self.channels_in, 64, 3, width_mult_factor=self.width_mult_factor)) # 0
  148. self._modules_list.append(Conv(width_mult(64), width_mult(128), 3, 2)) # 1
  149. self._modules_list.append(
  150. BottleneckCSP(128, 128, self.struct[0], width_mult_factor=self.width_mult_factor,
  151. depth_mult_factor=self.depth_mult_factor)) # 2
  152. self._modules_list.append(Conv(width_mult(128), width_mult(256), 3, 2)) # 3
  153. self._modules_list.append(
  154. BottleneckCSP(256, 256, self.struct[1], width_mult_factor=self.width_mult_factor,
  155. depth_mult_factor=self.depth_mult_factor)) # 4
  156. self._modules_list.append(Conv(width_mult(256), width_mult(512), 3, 2)) # 5
  157. self._modules_list.append(
  158. BottleneckCSP(512, 512, self.struct[2], width_mult_factor=self.width_mult_factor,
  159. depth_mult_factor=self.depth_mult_factor)) # 6
  160. self._modules_list.append(Conv(width_mult(512), width_mult(1024), 3, 2)) # 7
  161. self._modules_list.append(SPP(1024, 1024, k=(5, 9, 13), width_mult_factor=self.width_mult_factor)) # 8
  162. self._modules_list.append(
  163. BottleneckCSP(1024, 1024, self.struct[3], False, width_mult_factor=self.width_mult_factor,
  164. depth_mult_factor=self.depth_mult_factor)) # 9
  165. if not self.backbone_mode:
  166. # IF NOT USED AS A BACKEND BUT AS A CLASSIFIER WE ADD THE CLASSIFICATION LAYERS
  167. self._modules_list.append(nn.AdaptiveAvgPool2d((1, 1)))
  168. self._modules_list.append(ViewModule(1024))
  169. self._modules_list.append(nn.Linear(1024, self.num_classes))
  170. def forward(self, x):
  171. return self._modules_list(x)
Tip!

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

Comments

Loading...