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

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

Comments

Loading...