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

#274 Remove all elasticsearch references

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

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