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

yolo_base.py 27 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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
  1. import math
  2. from typing import Union, Type, List
  3. import torch
  4. import torch.nn as nn
  5. from super_gradients.training.models.detection_models.csp_darknet53 import Conv, GroupedConvBlock, \
  6. CSPDarknet53, get_yolo_type_params
  7. from super_gradients.training.models.sg_module import SgModule
  8. from super_gradients.training.utils.detection_utils import non_max_suppression, scale_img, \
  9. check_anchor_order, matrix_non_max_suppression, NMS_Type, DetectionPostPredictionCallback, Anchors
  10. from super_gradients.training.utils.utils import HpmStruct, check_img_size_divisibility, get_param
  11. COCO_DETECTION_80_CLASSES_BBOX_ANCHORS = Anchors([[10, 13, 16, 30, 33, 23],
  12. [30, 61, 62, 45, 59, 119],
  13. [116, 90, 156, 198, 373, 326]],
  14. strides=[8, 16, 32]) # output strides of all yolo outputs
  15. ANCHORSLESS_DUMMY_ANCHORS = Anchors([[0, 0], [0, 0], [0, 0]], strides=[8, 16, 32])
  16. DEFAULT_YOLO_ARCH_PARAMS = {
  17. 'num_classes': 80, # Number of classes to predict
  18. 'depth_mult_factor': 1.0, # depth multiplier for the entire model
  19. 'width_mult_factor': 1.0, # width multiplier for the entire model
  20. 'channels_in': 3, # Number of channels in the input image
  21. 'skip_connections_list': [(12, [6]), (16, [4]), (19, [14]), (22, [10]), (24, [17, 20])],
  22. # A list defining skip connections. format is '[target: [source1, source2, ...]]'. Each item defines a skip
  23. # connection from all sources to the target according to the layer's index (count starts from the backbone)
  24. 'backbone_connection_channels': [1024, 512, 256], # width of backbone channels that are concatenated with the head
  25. # True if width_mult_factor is applied to the backbone (is the case with the default backbones)
  26. # which means that backbone_connection_channels should be used with a width_mult_factor
  27. # False if backbone_connection_channels should be used as is
  28. 'scaled_backbone_width': True,
  29. 'fuse_conv_and_bn': False, # Fuse sequential Conv + B.N layers into a single one
  30. 'add_nms': False, # Add the NMS module to the computational graph
  31. 'nms_conf': 0.25, # When add_nms is True during NMS predictions with confidence lower than this will be discarded
  32. 'nms_iou': 0.45, # When add_nms is True IoU threshold for NMS algorithm
  33. # (with smaller value more boxed will be considered "the same" and removed)
  34. 'yolo_type': 'yoloX', # Type of yolo to build: 'yoloX' is only supported currently
  35. 'stem_type': None, # 'focus' and '6x6' are supported, by default is defined by yolo_type and yolo_version
  36. 'depthwise': False, # use depthwise separable convolutions all over the model
  37. 'xhead_inter_channels': None, # (has an impact only if yolo_type is yoloX)
  38. # Channels in classification and regression branches of the detecting blocks;
  39. # if is None the first of input channels will be used by default
  40. 'xhead_groups': None, # (has an impact only if yolo_type is yoloX)
  41. # Num groups in convs in classification and regression branches of the detecting blocks;
  42. # if None default groups will be used according to conv type
  43. # (1 for Conv and depthwise for GroupedConvBlock)
  44. }
  45. class YoloPostPredictionCallback(DetectionPostPredictionCallback):
  46. """Non-Maximum Suppression (NMS) module"""
  47. def __init__(self, conf: float = 0.001, iou: float = 0.6, classes: List[int] = None,
  48. nms_type: NMS_Type = NMS_Type.ITERATIVE, max_predictions: int = 300,
  49. with_confidence: bool = True):
  50. """
  51. :param conf: confidence threshold
  52. :param iou: IoU threshold (used in NMS_Type.ITERATIVE)
  53. :param classes: (optional list) filter by class (used in NMS_Type.ITERATIVE)
  54. :param nms_type: the type of nms to use (iterative or matrix)
  55. :param max_predictions: maximum number of boxes to output (used in NMS_Type.MATRIX)
  56. :param with_confidence: in NMS, whether to multiply objectness (used in NMS_Type.ITERATIVE)
  57. score with class score
  58. """
  59. super(YoloPostPredictionCallback, self).__init__()
  60. self.conf = conf
  61. self.iou = iou
  62. self.classes = classes
  63. self.nms_type = nms_type
  64. self.max_pred = max_predictions
  65. self.with_confidence = with_confidence
  66. def forward(self, x, device: str = None):
  67. if self.nms_type == NMS_Type.ITERATIVE:
  68. nms_result = non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou,
  69. with_confidence=self.with_confidence)
  70. else:
  71. nms_result = matrix_non_max_suppression(x[0], conf_thres=self.conf,
  72. max_num_of_detections=self.max_pred)
  73. return self._filter_max_predictions(nms_result)
  74. def _filter_max_predictions(self, res: List) -> List:
  75. res[:] = [im[:self.max_pred] if (im is not None and im.shape[0] > self.max_pred) else im for im in res]
  76. return res
  77. class Concat(nn.Module):
  78. """ CONCATENATE A LIST OF TENSORS ALONG DIMENSION"""
  79. def __init__(self, dimension=1):
  80. super().__init__()
  81. self.dimension = dimension
  82. def forward(self, x):
  83. return torch.cat(x, self.dimension)
  84. class Detect(nn.Module):
  85. def __init__(self, num_classes: int, anchors: Anchors, channels: list = None):
  86. super().__init__()
  87. self.num_classes = num_classes
  88. self.num_outputs = num_classes + 5
  89. self.detection_layers_num = anchors.detection_layers_num
  90. self.num_anchors = anchors.num_anchors
  91. self.grid = [torch.zeros(1)] * self.detection_layers_num # init grid
  92. self.register_buffer('stride', anchors.stride)
  93. self.register_buffer('anchors', anchors.anchors)
  94. self.register_buffer('anchor_grid', anchors.anchor_grid)
  95. self.output_convs = nn.ModuleList(nn.Conv2d(x, self.num_outputs * self.num_anchors, 1) for x in channels)
  96. def forward(self, x):
  97. z = [] # inference output
  98. for i in range(self.detection_layers_num):
  99. x[i] = self.output_convs[i](x[i]) # conv
  100. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  101. x[i] = x[i].view(bs, self.num_anchors, self.num_outputs, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  102. if not self.training: # inference
  103. if self.grid[i].shape[2:4] != x[i].shape[2:4]:
  104. self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
  105. y = x[i].sigmoid()
  106. xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy
  107. wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.num_anchors, 1, 1, 2) # wh
  108. y = torch.cat([xy, wh, y[..., 4:]], dim=4)
  109. z.append(y.view(bs, -1, self.num_outputs))
  110. return x if self.training else (torch.cat(z, 1), x)
  111. @staticmethod
  112. def _make_grid(nx=20, ny=20):
  113. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  114. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  115. class DetectX(nn.Module):
  116. def __init__(self, num_classes: int, stride: torch.Tensor, activation_func_type: type, channels: list,
  117. depthwise=False, groups: int = None, inter_channels: Union[int, List] = None):
  118. """
  119. :param stride: strides of each predicting level
  120. :param channels: input channels into all detecting layers
  121. (from all neck layers that will be used for predicting)
  122. :param depthwise: defines conv type in classification and regression branches (Conv or GroupedConvBlock)
  123. depthwise is False by default in favor of a usual Conv
  124. :param groups: num groups in convs in classification and regression branches;
  125. if None default groups will be used according to conv type
  126. (1 for Conv and depthwise for GroupedConvBlock)
  127. :param inter_channels: channels in classification and regression branches;
  128. if None channels[0] will be used by default
  129. """
  130. super().__init__()
  131. self.num_classes = num_classes
  132. self.detection_layers_num = len(channels)
  133. self.n_anchors = 1
  134. self.grid = [torch.zeros(1)] * self.detection_layers_num # init grid
  135. self.register_buffer('stride', stride)
  136. self.cls_convs = nn.ModuleList()
  137. self.reg_convs = nn.ModuleList()
  138. self.cls_preds = nn.ModuleList()
  139. self.reg_preds = nn.ModuleList()
  140. self.obj_preds = nn.ModuleList()
  141. self.stems = nn.ModuleList()
  142. ConvBlock = GroupedConvBlock if depthwise else Conv
  143. inter_channels = inter_channels or channels[0]
  144. inter_channels = inter_channels if isinstance(inter_channels, list) \
  145. else [inter_channels] * self.detection_layers_num
  146. for i in range(self.detection_layers_num):
  147. self.stems.append(Conv(channels[i], inter_channels[i], 1, 1, activation_func_type))
  148. self.cls_convs.append(
  149. nn.Sequential(*[ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type,
  150. groups=groups),
  151. ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type,
  152. groups=groups)]))
  153. self.reg_convs.append(
  154. nn.Sequential(*[ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type,
  155. groups=groups),
  156. ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type,
  157. groups=groups)]))
  158. self.cls_preds.append(nn.Conv2d(inter_channels[i], self.n_anchors * self.num_classes, 1, 1, 0))
  159. self.reg_preds.append(nn.Conv2d(inter_channels[i], 4, 1, 1, 0))
  160. self.obj_preds.append(nn.Conv2d(inter_channels[i], self.n_anchors * 1, 1, 1, 0))
  161. def forward(self, inputs):
  162. outputs = []
  163. outputs_logits = []
  164. for i in range(self.detection_layers_num):
  165. x = self.stems[i](inputs[i])
  166. cls_feat = self.cls_convs[i](x)
  167. cls_output = self.cls_preds[i](cls_feat)
  168. reg_feat = self.reg_convs[i](x)
  169. reg_output = self.reg_preds[i](reg_feat)
  170. obj_output = self.obj_preds[i](reg_feat)
  171. bs, _, ny, nx = reg_feat.shape
  172. output = torch.cat([reg_output, obj_output, cls_output], 1)
  173. output = output.view(bs, self.n_anchors, -1, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  174. if not self.training:
  175. outputs_logits.append(output.clone())
  176. if self.grid[i].shape[2:4] != output.shape[2:4]:
  177. self.grid[i] = self._make_grid(nx, ny).to(output.device)
  178. xy = (output[..., :2] + self.grid[i].to(output.device)) * self.stride[i]
  179. wh = torch.exp(output[..., 2:4]) * self.stride[i]
  180. output = torch.cat([xy, wh, output[..., 4:].sigmoid()], dim=4)
  181. output = output.view(bs, -1, output.shape[-1])
  182. outputs.append(output)
  183. return outputs if self.training else (torch.cat(outputs, 1), outputs_logits)
  184. @staticmethod
  185. def _make_grid(nx=20, ny=20):
  186. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  187. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  188. class AbstractYoLoBackbone:
  189. def __init__(self, arch_params):
  190. # CREATE A LIST CONTAINING THE LAYERS TO EXTRACT FROM THE BACKBONE AND ADD THE FINAL LAYER
  191. self._layer_idx_to_extract = [idx for sub_l in arch_params.skip_connections_dict.values() for idx in sub_l]
  192. self._layer_idx_to_extract.append(len(self._modules_list) - 1)
  193. def forward(self, x):
  194. """:return A list, the length of self._modules_list containing the output of the layer if specified in
  195. self._layers_to_extract and None otherwise"""
  196. extracted_intermediate_layers = []
  197. for layer_idx, layer_module in enumerate(self._modules_list):
  198. # PREDICT THE NEXT LAYER'S OUTPUT
  199. x = layer_module(x)
  200. # IF INDICATED APPEND THE OUTPUT TO extracted_intermediate_layers O.W. APPEND None
  201. extracted_intermediate_layers.append(x) if layer_idx in self._layer_idx_to_extract \
  202. else extracted_intermediate_layers.append(None)
  203. return extracted_intermediate_layers
  204. class YoLoDarknetBackbone(AbstractYoLoBackbone, CSPDarknet53):
  205. """Implements the CSP_Darknet53 module and inherit the forward pass to extract layers indicated in arch_params"""
  206. def __init__(self, arch_params):
  207. arch_params.backbone_mode = True
  208. CSPDarknet53.__init__(self, arch_params)
  209. AbstractYoLoBackbone.__init__(self, arch_params)
  210. def forward(self, x):
  211. return AbstractYoLoBackbone.forward(self, x)
  212. class YoLoHead(nn.Module):
  213. def __init__(self, arch_params):
  214. super().__init__()
  215. # PARSE arch_params
  216. num_classes = arch_params.num_classes
  217. anchors = arch_params.anchors
  218. depthwise = arch_params.depthwise
  219. xhead_groups = arch_params.xhead_groups
  220. xhead_inter_channels = arch_params.xhead_inter_channels
  221. self._skip_connections_dict = arch_params.skip_connections_dict
  222. # FLATTEN THE SOURCE LIST INTO A LIST OF INDICES
  223. self._layer_idx_to_extract = [idx for sub_l in self._skip_connections_dict.values() for idx in sub_l]
  224. _, block, activation_type, width_mult, depth_mult = get_yolo_type_params(arch_params.yolo_type,
  225. arch_params.width_mult_factor,
  226. arch_params.depth_mult_factor)
  227. backbone_connector = [width_mult(c) if arch_params.scaled_backbone_width else c
  228. for c in arch_params.backbone_connection_channels]
  229. DownConv = GroupedConvBlock if depthwise else Conv
  230. self._modules_list = nn.ModuleList()
  231. self._modules_list.append(Conv(backbone_connector[0], width_mult(512), 1, 1, activation_type)) # 10
  232. self._modules_list.append(nn.Upsample(None, 2, 'nearest')) # 11
  233. self._modules_list.append(Concat(1)) # 12
  234. self._modules_list.append(
  235. block(backbone_connector[1] + width_mult(512), width_mult(512), depth_mult(3), activation_type, False,
  236. depthwise)) # 13
  237. self._modules_list.append(Conv(width_mult(512), width_mult(256), 1, 1, activation_type)) # 14
  238. self._modules_list.append(nn.Upsample(None, 2, 'nearest')) # 15
  239. self._modules_list.append(Concat(1)) # 16
  240. self._modules_list.append(
  241. block(backbone_connector[2] + width_mult(256), width_mult(256), depth_mult(3), activation_type, False,
  242. depthwise)) # 17
  243. self._modules_list.append(DownConv(width_mult(256), width_mult(256), 3, 2, activation_type)) # 18
  244. self._modules_list.append(Concat(1)) # 19
  245. self._modules_list.append(
  246. block(2 * width_mult(256), width_mult(512), depth_mult(3), activation_type, False, depthwise)) # 20
  247. self._modules_list.append(DownConv(width_mult(512), width_mult(512), 3, 2, activation_type)) # 21
  248. self._modules_list.append(Concat(1)) # 22
  249. self._modules_list.append(
  250. block(2 * width_mult(512), width_mult(1024), depth_mult(3), activation_type, False, depthwise)) # 23
  251. detect_input_channels = [width_mult(v) for v in (256, 512, 1024)]
  252. strides = anchors.stride
  253. self._modules_list.append(
  254. DetectX(num_classes, strides, activation_type, channels=detect_input_channels, depthwise=depthwise,
  255. groups=xhead_groups, inter_channels=xhead_inter_channels)) # 24
  256. self.anchors = anchors
  257. self.width_mult = width_mult
  258. def forward(self, intermediate_output):
  259. """
  260. :param intermediate_output: A list of the intermediate prediction of layers specified in the
  261. self._inter_layer_idx_to_extract from the Backbone
  262. """
  263. # COUNT THE NUMBER OF LAYERS IN THE BACKBONE TO CONTINUE THE COUNTER
  264. num_layers_in_backbone = len(intermediate_output)
  265. # INPUT TO HEAD IS THE LAST ELEMENT OF THE BACKBONE'S OUTPUT
  266. out = intermediate_output[-1]
  267. # RUN OVER THE MODULE LIST WITHOUT THE FINAL LAYER & START COUNTER FROM THE END OF THE BACKBONE
  268. for layer_idx, layer_module in enumerate(self._modules_list[:-1], start=num_layers_in_backbone):
  269. # IF THE LAYER APPEARS IN THE KEYS IT INSERT THE PRECIOUS OUTPUT AND THE INDICATED SKIP CONNECTIONS
  270. out = layer_module([out, intermediate_output[self._skip_connections_dict[layer_idx][0]]]) \
  271. if layer_idx in self._skip_connections_dict.keys() else layer_module(out)
  272. # IF INDICATED APPEND THE OUTPUT TO inter_layer_idx_to_extract O.W. APPEND None
  273. intermediate_output.append(out) if layer_idx in self._layer_idx_to_extract \
  274. else intermediate_output.append(None)
  275. # INSERT THE REMAINING LAYERS INTO THE Detect LAYER
  276. last_idx = len(self._modules_list) + num_layers_in_backbone - 1
  277. return self._modules_list[-1]([intermediate_output[self._skip_connections_dict[last_idx][0]],
  278. intermediate_output[self._skip_connections_dict[last_idx][1]],
  279. out])
  280. class YoLoBase(SgModule):
  281. def __init__(self, backbone: Type[nn.Module], arch_params: HpmStruct, initialize_module: bool = True):
  282. super().__init__()
  283. # DEFAULT PARAMETERS TO BE OVERWRITTEN BY DUPLICATES THAT APPEAR IN arch_params
  284. self.arch_params = HpmStruct(**DEFAULT_YOLO_ARCH_PARAMS)
  285. # FIXME: REMOVE anchors ATTRIBUTE, WHICH HAS NO MEANING OTHER THAN COMPATIBILITY.
  286. self.arch_params.anchors = COCO_DETECTION_80_CLASSES_BBOX_ANCHORS
  287. self.arch_params.override(**arch_params.to_dict())
  288. self.arch_params.skip_connections_dict = {k: v for k, v in self.arch_params.skip_connections_list}
  289. self.num_classes = self.arch_params.num_classes
  290. # THE MODEL'S MODULES
  291. self._backbone = backbone(arch_params=self.arch_params)
  292. self._nms = nn.Identity()
  293. # A FLAG TO DEFINE augment_forward IN INFERENCE
  294. self.augmented_inference = False
  295. if initialize_module:
  296. self._head = YoLoHead(self.arch_params)
  297. self._initialize_module()
  298. def forward(self, x):
  299. return self._augment_forward(x) if self.augmented_inference else self._forward_once(x)
  300. def _forward_once(self, x):
  301. out = self._backbone(x)
  302. out = self._head(out)
  303. # THIS HAS NO EFFECT IF add_nms() WAS NOT DONE
  304. out = self._nms(out)
  305. return out
  306. def _augment_forward(self, x):
  307. """Multi-scale forward pass"""
  308. img_size = x.shape[-2:] # height, width
  309. s = [1, 0.83, 0.67] # scales
  310. f = [None, 3, None] # flips (2-ud, 3-lr)
  311. y = [] # outputs
  312. for si, fi in zip(s, f):
  313. xi = scale_img(x.flip(fi) if fi else x, si)
  314. yi = self._forward_once(xi)[0] # forward
  315. yi[..., :4] /= si # de-scale
  316. if fi == 2:
  317. yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
  318. elif fi == 3:
  319. yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
  320. y.append(yi)
  321. return torch.cat(y, 1), None # augmented inference, train
  322. def load_state_dict(self, state_dict, strict=True):
  323. try:
  324. super().load_state_dict(state_dict, strict)
  325. except RuntimeError as e:
  326. raise RuntimeError(f"Got exception {e}, if a mismatch between expected and given state_dict keys exist, "
  327. f"checkpoint may have been saved after fusing conv and bn. use fuse_conv_bn before loading.")
  328. def _initialize_module(self):
  329. self._check_strides_and_anchors()
  330. self._initialize_biases()
  331. self._initialize_weights()
  332. if self.arch_params.add_nms:
  333. nms_conf = self.arch_params.nms_conf
  334. nms_iou = self.arch_params.nms_iou
  335. self._nms = YoloPostPredictionCallback(nms_conf, nms_iou)
  336. def update_param_groups(self, param_groups: list, lr: float, epoch: int, iter: int,
  337. training_params: HpmStruct, total_batch: int) -> list:
  338. lr_warmup_epochs = get_param(training_params, 'lr_warmup_epochs', 0)
  339. if epoch >= lr_warmup_epochs:
  340. return super().update_param_groups(param_groups, lr, epoch, iter, training_params, total_batch)
  341. else:
  342. return param_groups
  343. def _check_strides_and_anchors(self):
  344. m = self._head._modules_list[-1] # Detect()
  345. # Do inference in train mode on a dummy image to get output stride of each head output layer
  346. s = 128 # twice the minimum acceptable image size
  347. dummy_input = torch.zeros(1, self.arch_params.channels_in, s, s)
  348. dummy_input = dummy_input.to(next(self._backbone.parameters()).device)
  349. stride = torch.tensor([s / x.shape[-2] for x in self._forward_once(dummy_input)])
  350. stride = stride.to(m.stride.device)
  351. if not torch.equal(m.stride, stride):
  352. raise RuntimeError('Provided anchor strides do not match the model strides')
  353. if isinstance(m, Detect):
  354. check_anchor_order(m)
  355. self.register_buffer('stride', m.stride) # USED ONLY FOR CONVERSION
  356. def _initialize_biases(self, cf=None):
  357. """initialize biases into Detect(), cf is class frequency"""
  358. detect_module = self._head._modules_list[-1] # Detect() module
  359. if isinstance(detect_module, Detect):
  360. for pred_conv, s in zip(detect_module.output_convs, detect_module.stride): # from
  361. bias = pred_conv.bias.view(detect_module.num_anchors, -1) # conv.bias(255) to (3,85)
  362. with torch.no_grad():
  363. bias[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  364. bias[:, 5:] += math.log(0.6 / (detect_module.num_classes - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
  365. pred_conv.bias = torch.nn.Parameter(bias.view(-1), requires_grad=True)
  366. elif isinstance(detect_module, DetectX):
  367. prior_prob = 1e-2
  368. for conv in detect_module.cls_preds:
  369. bias = conv.bias.view(detect_module.n_anchors, -1)
  370. bias.data.fill_(-math.log((1 - prior_prob) / prior_prob))
  371. conv.bias = torch.nn.Parameter(bias.view(-1), requires_grad=True)
  372. for conv in detect_module.obj_preds:
  373. bias = conv.bias.view(detect_module.n_anchors, -1)
  374. bias.data.fill_(-math.log((1 - prior_prob) / prior_prob))
  375. conv.bias = torch.nn.Parameter(bias.view(-1), requires_grad=True)
  376. def _initialize_weights(self):
  377. for m in self.modules():
  378. if isinstance(m, nn.BatchNorm2d):
  379. m.eps = 1e-3
  380. m.momentum = 0.03
  381. elif isinstance(m, (nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.Hardswish, nn.SiLU)):
  382. m.inplace = True
  383. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  384. """
  385. initialize_optimizer_for_model_param_groups - Initializes the weights of the optimizer
  386. adds weight decay *Only* to the Conv2D layers
  387. :param optimizer_cls: The nn.optim (optimizer class) to initialize
  388. :param lr: lr to set for the optimizer
  389. :param training_params:
  390. :return: The optimizer, initialized with the relevant param groups
  391. """
  392. optimizer_params = get_param(training_params, 'optimizer_params')
  393. # OPTIMIZER PARAMETER GROUPS
  394. default_param_group, weight_decay_param_group, biases_param_group = [], [], []
  395. deprecated_params_total = 0
  396. for name, m in self.named_modules():
  397. if hasattr(m, 'bias') and isinstance(m.bias, nn.Parameter): # bias
  398. biases_param_group.append((name, m.bias))
  399. if isinstance(m, nn.BatchNorm2d): # weight (no decay)
  400. default_param_group.append((name, m.weight))
  401. elif hasattr(m, 'weight') and isinstance(m.weight, nn.Parameter): # weight (with decay)
  402. weight_decay_param_group.append((name, m.weight))
  403. elif name == '_head.anchors':
  404. deprecated_params_total += m.stride.numel() + m._anchors.numel() + m._anchor_grid.numel()
  405. # EXTRACT weight_decay FROM THE optimizer_params IN ORDER TO ASSIGN THEM MANUALLY
  406. weight_decay = optimizer_params.pop('weight_decay') if 'weight_decay' in optimizer_params.keys() else 0
  407. param_groups = [{'named_params': default_param_group, 'lr': lr, **optimizer_params, 'name': 'default'},
  408. {'named_params': weight_decay_param_group, 'weight_decay': weight_decay, 'name': 'wd'},
  409. {'named_params': biases_param_group, 'name': 'bias'}]
  410. # Assert that all parameters were added to optimizer param groups
  411. params_total = sum(p.numel() for p in self.parameters())
  412. optimizer_params_total = sum(p.numel() for g in param_groups for _, p in g['named_params'])
  413. assert params_total == optimizer_params_total + deprecated_params_total, \
  414. f"Parameters {[n for n, _ in self.named_parameters() if 'weight' not in n and 'bias' not in n]} " \
  415. f"weren't added to optimizer param groups"
  416. return param_groups
  417. def prep_model_for_conversion(self, input_size: Union[tuple, list] = None, **kwargs):
  418. """
  419. A method for preparing the Yolo model for conversion to other frameworks (ONNX, CoreML etc)
  420. :param input_size: expected input size
  421. :return:
  422. """
  423. assert not self.training, 'model has to be in eval mode to be converted'
  424. # Verify dummy_input from converter is of multiple of the grid size
  425. max_stride = int(max(self.stride))
  426. # Validate the image size
  427. image_dims = input_size[-2:] # assume torch uses channels first layout
  428. for dim in image_dims:
  429. res_flag, suggestion = check_img_size_divisibility(dim, max_stride)
  430. if not res_flag:
  431. raise ValueError(f'Invalid input size: {input_size}. The input size must be multiple of max stride: '
  432. f'{max_stride}. The closest suggestions are: {suggestion[0]}x{suggestion[0]} or '
  433. f'{suggestion[1]}x{suggestion[1]}')
  434. def get_include_attributes(self) -> list:
  435. return ["grid", "anchors", "anchors_grid"]
  436. def replace_head(self, new_num_classes=None, new_head=None):
  437. if new_num_classes is None and new_head is None:
  438. raise ValueError("At least one of new_num_classes, new_head must be given to replace output layer.")
  439. if new_head is not None:
  440. self._head = new_head
  441. else:
  442. self.arch_params.num_classes = new_num_classes
  443. new_last_layer = Detect(new_num_classes, self._head.anchors, channels=[self._head.width_mult(v) for v in (256, 512, 1024)])
  444. new_last_layer = new_last_layer.to(next(self.parameters()).device)
  445. self._head._modules_list[-1] = new_last_layer
  446. self._check_strides_and_anchors()
  447. self._initialize_biases()
  448. self._initialize_weights()
Tip!

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

Comments

Loading...