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

yolov5.py 22 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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
  1. """
  2. YoloV5 code adapted from https://github.com/ultralytics/yolov5/blob/master/models/yolo.py
  3. """
  4. import math
  5. from typing import Union, Type, List
  6. import torch
  7. import torch.nn as nn
  8. from super_gradients.training.models.detection_models.csp_darknet53 import width_multiplier, Conv, BottleneckCSP, CSPDarknet53
  9. from super_gradients.training.models.sg_module import SgModule
  10. from super_gradients.training.utils.detection_utils import non_max_suppression, scale_img, \
  11. check_anchor_order, check_img_size_divisibilty, matrix_non_max_suppression, NMS_Type, \
  12. DetectionPostPredictionCallback, Anchors
  13. from super_gradients.training.utils.export_utils import ExportableHardswish
  14. from super_gradients.training.utils.utils import HpmStruct, get_param, print_once
  15. import numpy as np
  16. COCO_DETECTION_80_CLASSES_BBOX_ANCHORS = Anchors([[10, 13, 16, 30, 33, 23],
  17. [30, 61, 62, 45, 59, 119],
  18. [116, 90, 156, 198, 373, 326]],
  19. strides=[8, 16, 32]) # output strides of all yolo outputs
  20. DEFAULT_YOLOV5_ARCH_PARAMS = {
  21. 'anchors': COCO_DETECTION_80_CLASSES_BBOX_ANCHORS, # The sizes of the anchors predicted by the model
  22. 'num_classes': 80, # Number of classes to predict
  23. 'depth_mult_factor': 1.0, # depth multiplier for the entire model
  24. 'width_mult_factor': 1.0, # width multiplier for the entire model
  25. 'backbone_struct': [3, 9, 9, 3], # the number of blocks in every stage of the backbone
  26. 'channels_in': 3, # # of classes the model predicts
  27. 'skip_connections_dict': {12: [6], 16: [4], 19: [14], 22: [10], 24: [17, 20]},
  28. # A dictionary defining skip connections. format is 'target: [source1, source2, ...]'. Each item defines a skip
  29. # connection from all sources to the target according to the layer's index (count starts from the backbone)
  30. 'connection_layers_input_channel_size': [1024, 1024, 512],
  31. # default number off channels for the connecting points between the backbone and the head
  32. 'fuse_conv_and_bn': False, # Fuse sequential Conv + B.N layers into a single one
  33. 'add_nms': False, # Add the NMS module to the computational graph
  34. 'nms_conf': 0.25, # When add_nms is True during NMS predictions with confidence lower than this will be discarded
  35. 'nms_iou': 0.45, # When add_nms is True IoU threshold for NMS algorithm
  36. # (with smaller value more boxed will be considered "the same" and removed)
  37. }
  38. class YoloV5PostPredictionCallback(DetectionPostPredictionCallback):
  39. """Non-Maximum Suppression (NMS) module"""
  40. def __init__(self, conf: float = 0.001, iou: float = 0.6, classes: List[int] = None,
  41. nms_type: NMS_Type = NMS_Type.ITERATIVE, max_predictions: int = 300):
  42. """
  43. :param conf: confidence threshold
  44. :param iou: IoU threshold (used in NMS_Type.ITERATIVE)
  45. :param classes: (optional list) filter by class (used in NMS_Type.ITERATIVE)
  46. :param nms_type: the type of nms to use (iterative or matrix)
  47. :param max_predictions: maximum number of boxes to output (used in NMS_Type.MATRIX)
  48. """
  49. super(YoloV5PostPredictionCallback, self).__init__()
  50. self.conf = conf
  51. self.iou = iou
  52. self.classes = classes
  53. self.nms_type = nms_type
  54. self.max_predictions = max_predictions
  55. def forward(self, x, device: str = None):
  56. if self.nms_type == NMS_Type.ITERATIVE:
  57. return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)
  58. else:
  59. return matrix_non_max_suppression(x[0], conf_thres=self.conf, max_num_of_detections=self.max_predictions)
  60. class Concat(nn.Module):
  61. """ CONCATENATE A LIST OF TENSORS ALONG DIMENSION"""
  62. def __init__(self, dimension=1):
  63. super().__init__()
  64. self.dimension = dimension
  65. def forward(self, x):
  66. return torch.cat(x, self.dimension)
  67. class Detect(nn.Module):
  68. def __init__(self, num_classes: int, anchors: Anchors, channels: list = None,
  69. width_mult_factor: float = 1.0):
  70. super().__init__()
  71. # CHANGING THE WIDTH OF EACH OF THE DETECTION LAYERS
  72. channels = [width_multiplier(channel, width_mult_factor) for channel in channels]
  73. self.num_classes = num_classes
  74. self.num_outputs = num_classes + 5
  75. self.detection_layers_num = anchors.detection_layers_num
  76. self.num_anchors = anchors.num_anchors
  77. self.grid = [torch.zeros(1)] * self.detection_layers_num # init grid
  78. self.register_buffer('stride', anchors.stride)
  79. self.register_buffer('anchors', anchors.anchors)
  80. self.register_buffer('anchor_grid', anchors.anchor_grid)
  81. self.m = nn.ModuleList(nn.Conv2d(x, self.num_outputs * self.num_anchors, 1) for x in channels) # output conv
  82. def forward(self, x):
  83. z = [] # inference output
  84. for i in range(self.detection_layers_num):
  85. x[i] = self.m[i](x[i]) # conv
  86. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  87. x[i] = x[i].view(bs, self.num_anchors, self.num_outputs, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  88. if not self.training: # inference
  89. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  90. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  91. y = x[i].sigmoid()
  92. xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy
  93. wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.num_anchors, 1, 1, 2) # wh
  94. y = torch.cat([xy, wh, y[..., 4:]], dim=4)
  95. z.append(y.view(bs, -1, self.num_outputs))
  96. return x if self.training else (torch.cat(z, 1), x)
  97. @staticmethod
  98. def _make_grid(nx=20, ny=20):
  99. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  100. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  101. class AbstractYoLoV5Backbone:
  102. def __init__(self, arch_params):
  103. # CREATE A LIST CONTAINING THE LAYERS TO EXTRACT FROM THE BACKBONE AND ADD THE FINAL LAYER
  104. self._layer_idx_to_extract = [idx for sub_l in arch_params.skip_connections_dict.values() for idx in sub_l]
  105. self._layer_idx_to_extract.append(len(self._modules_list) - 1)
  106. def forward(self, x):
  107. """:return A list, the length of self._modules_list containing the output of the layer if specified in
  108. self._layers_to_extract and None otherwise"""
  109. extracted_intermediate_layers = []
  110. for layer_idx, layer_module in enumerate(self._modules_list):
  111. # PREDICT THE NEXT LAYER'S OUTPUT
  112. x = layer_module(x)
  113. # IF INDICATED APPEND THE OUTPUT TO extracted_intermediate_layers O.W. APPEND None
  114. extracted_intermediate_layers.append(x) if layer_idx in self._layer_idx_to_extract \
  115. else extracted_intermediate_layers.append(None)
  116. return extracted_intermediate_layers
  117. class YoLoV5DarknetBackbone(AbstractYoLoV5Backbone, CSPDarknet53):
  118. """Implements the CSP_Darknet53 module and inherit the forward pass to extract layers indicated in arch_params"""
  119. def __init__(self, arch_params):
  120. arch_params.backbone_mode = True
  121. CSPDarknet53.__init__(self, arch_params)
  122. AbstractYoLoV5Backbone.__init__(self, arch_params)
  123. def forward(self, x):
  124. return AbstractYoLoV5Backbone.forward(self, x)
  125. class YoLoV5Head(nn.Module):
  126. def __init__(self, arch_params):
  127. super().__init__()
  128. # PARSE arch_params
  129. num_classes = arch_params.num_classes
  130. depth_mult_factor = arch_params.depth_mult_factor
  131. width_mult_factor = arch_params.width_mult_factor
  132. anchors = arch_params.anchors
  133. self._skip_connections_dict = arch_params.skip_connections_dict
  134. # FLATTEN THE SOURCE LIST INTO A LIST OF INDICES
  135. self._layer_idx_to_extract = [idx for sub_l in self._skip_connections_dict.values() for idx in sub_l]
  136. # GET THREE CONNECTING POINTS CHANNEL INPUT SIZE
  137. connector = arch_params.connection_layers_input_channel_size
  138. width_mult = lambda channels: width_multiplier(channels, arch_params.width_mult_factor)
  139. # THE MODULES LIST IS APPROACHABLE FROM "OUTSIDE THE CLASS - SO WE CAN CHANGE IT'S STRUCTURE"
  140. self._modules_list = nn.ModuleList()
  141. self._modules_list.append(Conv(width_mult(connector[0]), width_mult(512), 1, 1)) # 10
  142. self._modules_list.append(nn.Upsample(None, 2, 'nearest')) # 11
  143. self._modules_list.append(Concat(1)) # 12
  144. self._modules_list.append(BottleneckCSP(connector[1], 512, 3, False, width_mult_factor=width_mult_factor,
  145. depth_mult_factor=depth_mult_factor)) # 13
  146. self._modules_list.append(Conv(width_mult(512), width_mult(256), 1)) # 14
  147. self._modules_list.append(nn.Upsample(None, 2, 'nearest')) # 15
  148. self._modules_list.append(Concat(1)) # 16
  149. self._modules_list.append(BottleneckCSP(connector[2], 256, 3, False, width_mult_factor=width_mult_factor,
  150. depth_mult_factor=depth_mult_factor)) # 17
  151. self._modules_list.append(Conv(width_mult(256), width_mult(256), 3, 2)) # 18
  152. self._modules_list.append(Concat(1)) # 19
  153. self._modules_list.append(BottleneckCSP(512, 512, 3, False, width_mult_factor=width_mult_factor,
  154. depth_mult_factor=depth_mult_factor)) # 20
  155. self._modules_list.append(Conv(width_mult(512), width_mult(512), 3, 2)) # 21
  156. self._modules_list.append(Concat(1)) # 22
  157. self._modules_list.append(BottleneckCSP(1024, 1024, 3, False, width_mult_factor=width_mult_factor,
  158. depth_mult_factor=depth_mult_factor)) # 23
  159. self._modules_list.append(Detect(num_classes, anchors, channels=[256, 512, 1024],
  160. width_mult_factor=width_mult_factor)) # 24
  161. def forward(self, intermediate_output):
  162. """
  163. :param intermediate_output: A list of the intermediate prediction of layers specified in the
  164. self._inter_layer_idx_to_extract from the Backbone
  165. """
  166. # COUNT THE NUMBER OF LAYERS IN THE BACKBONE TO CONTINUE THE COUNTER
  167. num_layers_in_backbone = len(intermediate_output)
  168. # INPUT TO HEAD IS THE LAST ELEMENT OF THE BACKBONE'S OUTPUT
  169. out = intermediate_output[-1]
  170. # RUN OVER THE MODULE LIST WITHOUT THE FINAL LAYER & START COUNTER FROM THE END OF THE BACKBONE
  171. for layer_idx, layer_module in enumerate(self._modules_list[:-1], start=num_layers_in_backbone):
  172. # IF THE LAYER APPEARS IN THE KEYS IT INSERT THE PRECIOUS OUTPUT AND THE INDICATED SKIP CONNECTIONS
  173. out = layer_module([out, intermediate_output[self._skip_connections_dict[layer_idx][0]]]) \
  174. if layer_idx in self._skip_connections_dict.keys() else layer_module(out)
  175. # IF INDICATED APPEND THE OUTPUT TO inter_layer_idx_to_extract O.W. APPEND None
  176. intermediate_output.append(out) if layer_idx in self._layer_idx_to_extract \
  177. else intermediate_output.append(None)
  178. # INSERT THE REMAINING LAYERS INTO THE Detect LAYER
  179. last_idx = len(self._modules_list) + num_layers_in_backbone - 1
  180. return self._modules_list[-1]([intermediate_output[self._skip_connections_dict[last_idx][0]],
  181. intermediate_output[self._skip_connections_dict[last_idx][1]],
  182. out])
  183. class YoLoV5Base(SgModule):
  184. def __init__(self, backbone: Type[nn.Module], arch_params: HpmStruct, initialize_module: bool = True):
  185. super().__init__()
  186. # DEFAULT PARAMETERS TO BE OVERWRITTEN BY DUPLICATES THAT APPEAR IN arch_params
  187. self.arch_params = HpmStruct(**DEFAULT_YOLOV5_ARCH_PARAMS)
  188. self.arch_params.override(**arch_params.to_dict())
  189. self.num_classes = self.arch_params.num_classes
  190. # THE MODEL'S MODULES
  191. self._backbone = backbone(arch_params=self.arch_params)
  192. self._nms = nn.Identity()
  193. # A FLAG TO DEFINE augment_forward IN INFERENCE
  194. self.augmented_inference = False
  195. # RUN SPECIFIC INITIALIZATION OF YOLO-V5
  196. if initialize_module:
  197. self._head = YoLoV5Head(self.arch_params)
  198. self._initialize_module()
  199. def forward(self, x):
  200. return self._augment_forward(x) if self.augmented_inference else self._forward_once(x)
  201. def _forward_once(self, x):
  202. out = self._backbone(x)
  203. out = self._head(out)
  204. # THIS HAS NO EFFECT IF add_nms() WAS NOT DONE
  205. out = self._nms(out)
  206. return out
  207. def _augment_forward(self, x):
  208. """Multi-scale forward pass"""
  209. img_size = x.shape[-2:] # height, width
  210. s = [1, 0.83, 0.67] # scales
  211. f = [None, 3, None] # flips (2-ud, 3-lr)
  212. y = [] # outputs
  213. for si, fi in zip(s, f):
  214. xi = scale_img(x.flip(fi) if fi else x, si)
  215. yi = self._forward_once(xi)[0] # forward
  216. yi[..., :4] /= si # de-scale
  217. if fi == 2:
  218. yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
  219. elif fi == 3:
  220. yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
  221. y.append(yi)
  222. return torch.cat(y, 1), None # augmented inference, train
  223. def load_state_dict(self, state_dict, strict=True):
  224. try:
  225. super().load_state_dict(state_dict, strict)
  226. except RuntimeError as e:
  227. raise RuntimeError(f"Got exception {e}, if a mismatch between expected and given state_dict keys exist, "
  228. f"checkpoint may have been saved after fusing conv and bn. use fuse_conv_bn before loading.")
  229. def _initialize_module(self):
  230. self._check_strides_and_anchors()
  231. self._initialize_biases()
  232. self._initialize_weights()
  233. if self.arch_params.add_nms:
  234. nms_conf = self.arch_params.nms_conf
  235. nms_iou = self.arch_params.nms_iou
  236. self._nms = YoloV5PostPredictionCallback(nms_conf, nms_iou)
  237. def update_param_groups(self, param_groups: list, lr: float, epoch: int, iter: int,
  238. training_params: HpmStruct, total_batch: int) -> list:
  239. lr_warmup_epochs = get_param(training_params, 'lr_warmup_epochs', 0)
  240. if epoch < lr_warmup_epochs and iter is not None:
  241. # OVERRIDE THE lr FROM DeciModelBase WITH initial_lr, SINCE DeciModelBase MANIPULATE THE ORIGINAL VALUE
  242. print_once('Using Yolo v5 warm-up lr (overriding ModelBase lr function)')
  243. lr = training_params.initial_lr
  244. momentum = get_param(training_params.optimizer_params, 'momentum')
  245. warmup_momentum = get_param(training_params, 'warmup_momentum', momentum)
  246. warmup_bias_lr = get_param(training_params, 'warmup_bias_lr', lr)
  247. nw = lr_warmup_epochs * total_batch
  248. ni = epoch * total_batch + iter
  249. xi = [0, nw] # x interp
  250. for x in param_groups:
  251. # BIAS LR FALLS FROM 0.1 TO LR0, ALL OTHER LRS RISE FROM 0.0 TO LR0
  252. x['lr'] = np.interp(ni, xi, [warmup_bias_lr if x['name'] == 'bias' else 0.0, lr])
  253. if 'momentum' in x:
  254. x['momentum'] = np.interp(ni, xi, [warmup_momentum, momentum])
  255. return param_groups
  256. else:
  257. return super().update_param_groups(param_groups, lr, epoch, iter, training_params, total_batch)
  258. def _check_strides_and_anchors(self):
  259. m = self._head._modules_list[-1] # Detect()
  260. # Do inference in train mode on a dummy image to get output stride of each head output layer
  261. s = 128 # twice the minimum acceptable image size
  262. dummy_input = torch.zeros(1, self.arch_params.channels_in, s, s)
  263. stride = torch.tensor([s / x.shape[-2] for x in self._forward_once(dummy_input)])
  264. if not torch.equal(m.stride, stride):
  265. raise RuntimeError('Provided anchor strides do not match the model strides')
  266. check_anchor_order(m)
  267. self.register_buffer('stride', m.stride) # USED ONLY FOR CONVERSION
  268. def _initialize_biases(self, cf=None):
  269. """initialize biases into Detect(), cf is class frequency"""
  270. # TODO: UNDERSTAND WHAT IS THIS cf AND IF WE NEED IT
  271. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  272. m = self._head._modules_list[-1] # Detect() module
  273. for mi, s in zip(m.m, m.stride): # from
  274. b = mi.bias.view(m.num_anchors, -1) # conv.bias(255) to (3,85)
  275. with torch.no_grad():
  276. b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  277. b[:, 5:] += math.log(0.6 / (m.num_classes - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
  278. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  279. def _initialize_weights(self):
  280. for m in self.modules():
  281. t = type(m)
  282. if t is nn.Conv2d:
  283. pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  284. elif t is nn.BatchNorm2d:
  285. m.eps = 1e-3
  286. m.momentum = 0.03
  287. elif t in [nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.Hardswish]:
  288. m.inplace = True
  289. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  290. """
  291. initialize_optimizer_for_model_param_groups - Initializes the weights of the optimizer
  292. adds weight decay *Only* to the Conv2D layers
  293. :param optimizer_cls: The nn.optim (optimizer class) to initialize
  294. :param lr: lr to set for the optimizer
  295. :param training_params:
  296. :return: The optimizer, initialized with the relevant param groups
  297. """
  298. optimizer_params = get_param(training_params, 'optimizer_params')
  299. # OPTIMIZER PARAMETER GROUPS
  300. default_param_group, weight_decay_param_group, biases_param_group = [], [], []
  301. for name, m in self.named_modules():
  302. if hasattr(m, 'bias') and isinstance(m.bias, nn.Parameter): # bias
  303. biases_param_group.append((name, m.bias))
  304. if isinstance(m, nn.BatchNorm2d): # weight (no decay)
  305. default_param_group.append((name, m.weight))
  306. elif hasattr(m, 'weight') and isinstance(m.weight, nn.Parameter): # weight (with decay)
  307. weight_decay_param_group.append((name, m.weight))
  308. # EXTRACT weight_decay FROM THE optimizer_params IN ORDER TO ASSIGN THEM MANUALLY
  309. weight_decay = optimizer_params.pop('weight_decay') if 'weight_decay' in optimizer_params.keys() else 0
  310. param_groups = [{'named_params': default_param_group, 'lr': lr, **optimizer_params, 'name': 'default'},
  311. {'named_params': weight_decay_param_group, 'weight_decay': weight_decay, 'name': 'wd'},
  312. {'named_params': biases_param_group, 'name': 'bias'}]
  313. # Assert that all parameters were added to optimizer param groups
  314. params_total = sum(p.numel() for p in self.parameters())
  315. optimizer_params_total = sum(p.numel() for g in param_groups for _, p in g['named_params'])
  316. assert params_total == optimizer_params_total, \
  317. f"Parameters {[n for n, _ in self.named_parameters() if 'weight' not in n and 'bias' not in n]} " \
  318. f"weren't added to optimizer param groups"
  319. return param_groups
  320. def prep_model_for_conversion(self, input_size: Union[tuple, list] = None, **kwargs):
  321. """
  322. A method for preparing the YoloV5 model for conversion to other frameworks (ONNX, CoreML etc)
  323. :param input_size: expected input size
  324. :return:
  325. """
  326. assert not self.training, 'model has to be in eval mode to be converted'
  327. # Verify dummy_input from converter is of multiple of the grid size
  328. max_stride = int(max(self.stride))
  329. # Validate the image size
  330. image_dims = input_size[-2:] # assume torch uses channels first layout
  331. for dim in image_dims:
  332. res_flag, suggestion = check_img_size_divisibilty(dim, max_stride)
  333. if not res_flag:
  334. raise ValueError(f'Invalid input size: {input_size}. The input size must be multiple of max stride: '
  335. f'{max_stride}. The closest suggestions are: {suggestion[0]}x{suggestion[0]} or '
  336. f'{suggestion[1]}x{suggestion[1]}')
  337. # Update the model with exportable operators
  338. for k, m in self.named_modules():
  339. if isinstance(m, Conv) and isinstance(m.act, nn.Hardswish):
  340. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  341. m.act = ExportableHardswish() # assign activation
  342. def get_include_attributes(self) -> list:
  343. return ["grid", "anchors", "anchors_grid"]
  344. class Custom_YoLoV5(YoLoV5Base):
  345. def __init__(self, arch_params: HpmStruct):
  346. backbone = get_param(arch_params, 'backbone', YoLoV5DarknetBackbone)
  347. super().__init__(backbone=backbone, arch_params=arch_params)
  348. class YoLoV5S(YoLoV5Base):
  349. def __init__(self, arch_params: HpmStruct):
  350. arch_params.depth_mult_factor = 0.33
  351. arch_params.width_mult_factor = 0.50
  352. super().__init__(backbone=YoLoV5DarknetBackbone, arch_params=arch_params)
  353. class YoLoV5M(YoLoV5Base):
  354. def __init__(self, arch_params: HpmStruct):
  355. arch_params.depth_mult_factor = 0.67
  356. arch_params.width_mult_factor = 0.75
  357. super().__init__(backbone=YoLoV5DarknetBackbone, arch_params=arch_params)
  358. class YoLoV5L(YoLoV5Base):
  359. def __init__(self, arch_params: HpmStruct):
  360. arch_params.depth_mult_factor = 1.0
  361. arch_params.width_mult_factor = 1.0
  362. super().__init__(backbone=YoLoV5DarknetBackbone, arch_params=arch_params)
  363. class YoLoV5X(YoLoV5Base):
  364. def __init__(self, arch_params: HpmStruct):
  365. arch_params.depth_mult_factor = 1.33
  366. arch_params.width_mult_factor = 1.25
  367. super().__init__(backbone=YoLoV5DarknetBackbone, arch_params=arch_params)
Tip!

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

Comments

Loading...