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

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
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
  1. import math
  2. from typing import Union, Type, List, Tuple
  3. import torch
  4. import torch.nn as nn
  5. from super_gradients.modules import CrossModelSkipConnection
  6. from super_gradients.training.models.classification_models.regnet import AnyNetX, Stage
  7. from super_gradients.training.models.detection_models.csp_darknet53 import Conv, GroupedConvBlock, CSPDarknet53, get_yolo_type_params, SPP
  8. from super_gradients.training.models.sg_module import SgModule
  9. from super_gradients.training.utils import torch_version_is_greater_or_equal
  10. from super_gradients.training.utils.detection_utils import non_max_suppression, matrix_non_max_suppression, NMS_Type, DetectionPostPredictionCallback, Anchors
  11. from super_gradients.training.utils.utils import HpmStruct, check_img_size_divisibility, get_param
  12. COCO_DETECTION_80_CLASSES_BBOX_ANCHORS = Anchors(
  13. [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], strides=[8, 16, 32]
  14. ) # 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__(
  48. self,
  49. conf: float = 0.001,
  50. iou: float = 0.6,
  51. classes: List[int] = None,
  52. nms_type: NMS_Type = NMS_Type.ITERATIVE,
  53. max_predictions: int = 300,
  54. with_confidence: bool = True,
  55. ):
  56. """
  57. :param conf: confidence threshold
  58. :param iou: IoU threshold (used in NMS_Type.ITERATIVE)
  59. :param classes: (optional list) filter by class (used in NMS_Type.ITERATIVE)
  60. :param nms_type: the type of nms to use (iterative or matrix)
  61. :param max_predictions: maximum number of boxes to output (used in NMS_Type.MATRIX)
  62. :param with_confidence: in NMS, whether to multiply objectness (used in NMS_Type.ITERATIVE)
  63. score with class score
  64. """
  65. super(YoloPostPredictionCallback, self).__init__()
  66. self.conf = conf
  67. self.iou = iou
  68. self.classes = classes
  69. self.nms_type = nms_type
  70. self.max_pred = max_predictions
  71. self.with_confidence = with_confidence
  72. def forward(self, x, device: str = None):
  73. if self.nms_type == NMS_Type.ITERATIVE:
  74. nms_result = non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, with_confidence=self.with_confidence)
  75. else:
  76. nms_result = matrix_non_max_suppression(x[0], conf_thres=self.conf, max_num_of_detections=self.max_pred)
  77. return self._filter_max_predictions(nms_result)
  78. def _filter_max_predictions(self, res: List) -> List:
  79. res[:] = [im[: self.max_pred] if (im is not None and im.shape[0] > self.max_pred) else im for im in res]
  80. return res
  81. class Concat(nn.Module):
  82. """CONCATENATE A LIST OF TENSORS ALONG DIMENSION"""
  83. def __init__(self, dimension=1):
  84. super().__init__()
  85. self.dimension = dimension
  86. def forward(self, x):
  87. return torch.cat(x, self.dimension)
  88. class DetectX(nn.Module):
  89. def __init__(
  90. self,
  91. num_classes: int,
  92. stride: torch.Tensor,
  93. activation_func_type: type,
  94. channels: list,
  95. depthwise=False,
  96. groups: int = None,
  97. inter_channels: Union[int, List] = None,
  98. ):
  99. """
  100. :param stride: strides of each predicting level
  101. :param channels: input channels into all detecting layers
  102. (from all neck layers that will be used for predicting)
  103. :param depthwise: defines conv type in classification and regression branches (Conv or GroupedConvBlock)
  104. depthwise is False by default in favor of a usual Conv
  105. :param groups: num groups in convs in classification and regression branches;
  106. if None default groups will be used according to conv type
  107. (1 for Conv and depthwise for GroupedConvBlock)
  108. :param inter_channels: channels in classification and regression branches;
  109. if None channels[0] will be used by default
  110. """
  111. super().__init__()
  112. self.num_classes = num_classes
  113. self.detection_layers_num = len(channels)
  114. self.n_anchors = 1
  115. self.grid = [torch.zeros(1)] * self.detection_layers_num # init grid
  116. self.register_buffer("stride", stride)
  117. self.cls_convs = nn.ModuleList()
  118. self.reg_convs = nn.ModuleList()
  119. self.cls_preds = nn.ModuleList()
  120. self.reg_preds = nn.ModuleList()
  121. self.obj_preds = nn.ModuleList()
  122. self.stems = nn.ModuleList()
  123. ConvBlock = GroupedConvBlock if depthwise else Conv
  124. inter_channels = inter_channels or channels[0]
  125. inter_channels = inter_channels if isinstance(inter_channels, list) else [inter_channels] * self.detection_layers_num
  126. for i in range(self.detection_layers_num):
  127. self.stems.append(Conv(channels[i], inter_channels[i], 1, 1, activation_func_type))
  128. self.cls_convs.append(
  129. nn.Sequential(
  130. *[
  131. ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type, groups=groups),
  132. ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type, groups=groups),
  133. ]
  134. )
  135. )
  136. self.reg_convs.append(
  137. nn.Sequential(
  138. *[
  139. ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type, groups=groups),
  140. ConvBlock(inter_channels[i], inter_channels[i], 3, 1, activation_func_type, groups=groups),
  141. ]
  142. )
  143. )
  144. self.cls_preds.append(nn.Conv2d(inter_channels[i], self.n_anchors * self.num_classes, 1, 1, 0))
  145. self.reg_preds.append(nn.Conv2d(inter_channels[i], 4, 1, 1, 0))
  146. self.obj_preds.append(nn.Conv2d(inter_channels[i], self.n_anchors * 1, 1, 1, 0))
  147. def forward(self, inputs):
  148. outputs = []
  149. outputs_logits = []
  150. for i in range(self.detection_layers_num):
  151. x = self.stems[i](inputs[i])
  152. cls_feat = self.cls_convs[i](x)
  153. cls_output = self.cls_preds[i](cls_feat)
  154. reg_feat = self.reg_convs[i](x)
  155. reg_output = self.reg_preds[i](reg_feat)
  156. obj_output = self.obj_preds[i](reg_feat)
  157. bs, _, ny, nx = reg_feat.shape
  158. output = torch.cat([reg_output, obj_output, cls_output], 1)
  159. output = output.view(bs, self.n_anchors, -1, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  160. if not self.training:
  161. outputs_logits.append(output.clone())
  162. if self.grid[i].shape[2:4] != output.shape[2:4]:
  163. self.grid[i] = self._make_grid(nx, ny).to(output.device)
  164. xy = (output[..., :2] + self.grid[i].to(output.device)) * self.stride[i]
  165. wh = torch.exp(output[..., 2:4]) * self.stride[i]
  166. output = torch.cat([xy, wh, output[..., 4:].sigmoid()], dim=4)
  167. output = output.view(bs, -1, output.shape[-1])
  168. outputs.append(output)
  169. return outputs if self.training else (torch.cat(outputs, 1), outputs_logits)
  170. @staticmethod
  171. def _make_grid(nx=20, ny=20):
  172. if torch_version_is_greater_or_equal(1, 10):
  173. # https://github.com/pytorch/pytorch/issues/50276
  174. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)], indexing="ij")
  175. else:
  176. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  177. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  178. class AbstractYoloBackbone:
  179. def __init__(self, arch_params):
  180. # CREATE A LIST CONTAINING THE LAYERS TO EXTRACT FROM THE BACKBONE AND ADD THE FINAL LAYER
  181. self._layer_idx_to_extract = [idx for sub_l in arch_params.skip_connections_dict.values() for idx in sub_l]
  182. self._layer_idx_to_extract.append(len(self._modules_list) - 1)
  183. def forward(self, x):
  184. """:return A list, the length of self._modules_list containing the output of the layer if specified in
  185. self._layers_to_extract and None otherwise"""
  186. extracted_intermediate_layers = []
  187. for layer_idx, layer_module in enumerate(self._modules_list):
  188. # PREDICT THE NEXT LAYER'S OUTPUT
  189. x = layer_module(x)
  190. # IF INDICATED APPEND THE OUTPUT TO extracted_intermediate_layers O.W. APPEND None
  191. if layer_idx in self._layer_idx_to_extract:
  192. extracted_intermediate_layers.append(x)
  193. else:
  194. extracted_intermediate_layers.append(None)
  195. return extracted_intermediate_layers
  196. class YoloDarknetBackbone(AbstractYoloBackbone, CSPDarknet53):
  197. """Implements the CSP_Darknet53 module and inherit the forward pass to extract layers indicated in arch_params"""
  198. def __init__(self, arch_params):
  199. arch_params.backbone_mode = True
  200. CSPDarknet53.__init__(self, arch_params)
  201. AbstractYoloBackbone.__init__(self, arch_params)
  202. def forward(self, x):
  203. return AbstractYoloBackbone.forward(self, x)
  204. class YoloRegnetBackbone(AbstractYoloBackbone, AnyNetX):
  205. """Implements the Regnet module and inherits the forward pass to extract layers indicated in arch_params"""
  206. def __init__(self, arch_params):
  207. backbone_params = {**arch_params.backbone_params, "backbone_mode": True, "num_classes": None}
  208. backbone_params.pop("spp_kernels", None)
  209. AnyNetX.__init__(self, **backbone_params)
  210. # LAST ANYNETX STAGE -> STAGE + SPP IF SPP_KERNELS IS GIVEN
  211. spp_kernels = get_param(arch_params.backbone_params, "spp_kernels", None)
  212. if spp_kernels:
  213. activation_type = nn.SiLU if arch_params.yolo_type == "yoloX" else nn.Hardswish
  214. self.net.stage_3 = self.add_spp_to_stage(self.net.stage_3, spp_kernels, activation_type=activation_type)
  215. self.initialize_weight()
  216. # CREATE A LIST CONTAINING THE LAYERS TO EXTRACT FROM THE BACKBONE AND ADD THE FINAL LAYER
  217. self._modules_list = nn.ModuleList()
  218. for layer in self.net:
  219. self._modules_list.append(layer)
  220. AbstractYoloBackbone.__init__(self, arch_params)
  221. # WE KEEP A LIST OF THE OUTPUTS WIDTHS (NUM FEATURES) TO BE CONNECTED TO THE HEAD
  222. self.backbone_connection_channels = arch_params.backbone_params["ls_block_width"][1:][::-1]
  223. @staticmethod
  224. def add_spp_to_stage(anynetx_stage: Stage, spp_kernels: Tuple[int], activation_type):
  225. """
  226. Add SPP in the end of an AnyNetX Stage
  227. """
  228. # Last block in a Stage -> conv_block_3 -> Conv2d -> out_channels
  229. out_channels = anynetx_stage.blocks[-1].conv_block_3[0].out_channels
  230. anynetx_stage.blocks.add_module("spp_block", SPP(out_channels, out_channels, spp_kernels, activation_type=activation_type))
  231. return anynetx_stage
  232. def forward(self, x):
  233. return AbstractYoloBackbone.forward(self, x)
  234. class YoloHead(nn.Module):
  235. def __init__(self, arch_params):
  236. super().__init__()
  237. # PARSE arch_params
  238. num_classes = arch_params.num_classes
  239. anchors = arch_params.anchors
  240. depthwise = arch_params.depthwise
  241. xhead_groups = arch_params.xhead_groups
  242. xhead_inter_channels = arch_params.xhead_inter_channels
  243. self._skip_connections_dict = arch_params.skip_connections_dict
  244. # FLATTEN THE SOURCE LIST INTO A LIST OF INDICES
  245. self._layer_idx_to_extract = [idx for sub_l in self._skip_connections_dict.values() for idx in sub_l]
  246. _, block, activation_type, width_mult, depth_mult = get_yolo_type_params(
  247. arch_params.yolo_type, arch_params.width_mult_factor, arch_params.depth_mult_factor
  248. )
  249. backbone_connector = [width_mult(c) if arch_params.scaled_backbone_width else c for c in arch_params.backbone_connection_channels]
  250. DownConv = GroupedConvBlock if depthwise else Conv
  251. self._modules_list = nn.ModuleList()
  252. self._modules_list.append(Conv(backbone_connector[0], width_mult(512), 1, 1, activation_type)) # 10
  253. self._modules_list.append(nn.Upsample(None, 2, "nearest")) # 11
  254. self._modules_list.append(Concat(1)) # 12
  255. self._modules_list.append(block(backbone_connector[1] + width_mult(512), width_mult(512), depth_mult(3), activation_type, False, depthwise)) # 13
  256. self._modules_list.append(Conv(width_mult(512), width_mult(256), 1, 1, activation_type)) # 14
  257. self._modules_list.append(nn.Upsample(None, 2, "nearest")) # 15
  258. self._modules_list.append(Concat(1)) # 16
  259. self._modules_list.append(block(backbone_connector[2] + width_mult(256), width_mult(256), depth_mult(3), activation_type, False, depthwise)) # 17
  260. self._modules_list.append(DownConv(width_mult(256), width_mult(256), 3, 2, activation_type)) # 18
  261. self._modules_list.append(Concat(1)) # 19
  262. self._modules_list.append(block(2 * width_mult(256), width_mult(512), depth_mult(3), activation_type, False, depthwise)) # 20
  263. self._modules_list.append(DownConv(width_mult(512), width_mult(512), 3, 2, activation_type)) # 21
  264. self._modules_list.append(Concat(1)) # 22
  265. self._modules_list.append(block(2 * width_mult(512), width_mult(1024), depth_mult(3), activation_type, False, depthwise)) # 23
  266. detect_input_channels = [width_mult(v) for v in (256, 512, 1024)]
  267. strides = anchors.stride
  268. self._modules_list.append(
  269. DetectX(
  270. num_classes,
  271. strides,
  272. activation_type,
  273. channels=detect_input_channels,
  274. depthwise=depthwise,
  275. groups=xhead_groups,
  276. inter_channels=xhead_inter_channels,
  277. )
  278. ) # 24
  279. self._shortcuts = nn.ModuleList([CrossModelSkipConnection() for _ in range(len(self._skip_connections_dict.keys()) - 1)])
  280. self.anchors = anchors
  281. self.width_mult = width_mult
  282. def forward(self, intermediate_output):
  283. """
  284. :param intermediate_output: A list of the intermediate prediction of layers specified in the
  285. self._inter_layer_idx_to_extract from the Backbone
  286. """
  287. # COUNT THE NUMBER OF LAYERS IN THE BACKBONE TO CONTINUE THE COUNTER
  288. num_layers_in_backbone = len(intermediate_output)
  289. # INPUT TO HEAD IS THE LAST ELEMENT OF THE BACKBONE'S OUTPUT
  290. out = intermediate_output[-1]
  291. # RUN OVER THE MODULE LIST WITHOUT THE FINAL LAYER & START COUNTER FROM THE END OF THE BACKBONE
  292. i = 0
  293. for layer_idx, layer_module in enumerate(self._modules_list[:-1], start=num_layers_in_backbone):
  294. # IF THE LAYER APPEARS IN THE KEYS IT INSERT THE PRECIOUS OUTPUT AND THE INDICATED SKIP CONNECTIONS
  295. if layer_idx in self._skip_connections_dict.keys():
  296. out = layer_module([out, self._shortcuts[i](intermediate_output[self._skip_connections_dict[layer_idx][0]])])
  297. i += 1
  298. else:
  299. out = layer_module(out)
  300. # IF INDICATED APPEND THE OUTPUT TO inter_layer_idx_to_extract O.W. APPEND None
  301. if layer_idx in self._layer_idx_to_extract:
  302. intermediate_output.append(out)
  303. else:
  304. intermediate_output.append(None)
  305. # INSERT THE REMAINING LAYERS INTO THE Detect LAYER
  306. last_idx = len(self._modules_list) + num_layers_in_backbone - 1
  307. return self._modules_list[-1](
  308. [
  309. intermediate_output[self._skip_connections_dict[last_idx][0]],
  310. intermediate_output[self._skip_connections_dict[last_idx][1]],
  311. out,
  312. ]
  313. )
  314. class YoloBase(SgModule):
  315. def __init__(self, backbone: Type[nn.Module], arch_params: HpmStruct, initialize_module: bool = True):
  316. super().__init__()
  317. # DEFAULT PARAMETERS TO BE OVERWRITTEN BY DUPLICATES THAT APPEAR IN arch_params
  318. self.arch_params = HpmStruct(**DEFAULT_YOLO_ARCH_PARAMS)
  319. # FIXME: REMOVE anchors ATTRIBUTE, WHICH HAS NO MEANING OTHER THAN COMPATIBILITY.
  320. self.arch_params.anchors = COCO_DETECTION_80_CLASSES_BBOX_ANCHORS
  321. self.arch_params.override(**arch_params.to_dict())
  322. self.arch_params.skip_connections_dict = {k: v for k, v in self.arch_params.skip_connections_list}
  323. self.num_classes = self.arch_params.num_classes
  324. # THE MODEL'S MODULES
  325. self._backbone = backbone(arch_params=self.arch_params)
  326. if hasattr(self._backbone, "backbone_connection_channels"):
  327. self.arch_params.scaled_backbone_width = False
  328. self.arch_params.backbone_connection_channels = self._backbone.backbone_connection_channels
  329. self._nms = nn.Identity()
  330. # A FLAG TO DEFINE augment_forward IN INFERENCE
  331. self.augmented_inference = False
  332. if initialize_module:
  333. self._head = YoloHead(self.arch_params)
  334. self._initialize_module()
  335. def forward(self, x):
  336. out = self._backbone(x)
  337. out = self._head(out)
  338. # THIS HAS NO EFFECT IF add_nms() WAS NOT DONE
  339. out = self._nms(out)
  340. return out
  341. def load_state_dict(self, state_dict, strict=True):
  342. try:
  343. super().load_state_dict(state_dict, strict)
  344. except RuntimeError as e:
  345. raise RuntimeError(
  346. f"Got exception {e}, if a mismatch between expected and given state_dict keys exist, "
  347. f"checkpoint may have been saved after fusing conv and bn. use fuse_conv_bn before loading."
  348. )
  349. def _initialize_module(self):
  350. self._check_strides()
  351. self._initialize_biases()
  352. self._initialize_weights()
  353. if self.arch_params.add_nms:
  354. nms_conf = self.arch_params.nms_conf
  355. nms_iou = self.arch_params.nms_iou
  356. self._nms = YoloPostPredictionCallback(nms_conf, nms_iou)
  357. def _check_strides(self):
  358. m = self._head._modules_list[-1] # DetectX()
  359. # Do inference in train mode on a dummy image to get output stride of each head output layer
  360. s = 128 # twice the minimum acceptable image size
  361. dummy_input = torch.zeros(1, self.arch_params.channels_in, s, s)
  362. dummy_input = dummy_input.to(next(self._backbone.parameters()).device)
  363. stride = torch.tensor([s / x.shape[-2] for x in self.forward(dummy_input)])
  364. stride = stride.to(m.stride.device)
  365. if not torch.equal(m.stride, stride):
  366. raise RuntimeError("Provided anchor strides do not match the model strides")
  367. self.register_buffer("stride", m.stride) # USED ONLY FOR CONVERSION
  368. def _initialize_biases(self):
  369. """initialize biases into DetectX()"""
  370. detect_module = self._head._modules_list[-1] # DetectX() module
  371. prior_prob = 1e-2
  372. for conv in detect_module.cls_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. for conv in detect_module.obj_preds:
  377. bias = conv.bias.view(detect_module.n_anchors, -1)
  378. bias.data.fill_(-math.log((1 - prior_prob) / prior_prob))
  379. conv.bias = torch.nn.Parameter(bias.view(-1), requires_grad=True)
  380. def _initialize_weights(self):
  381. for m in self.modules():
  382. if isinstance(m, nn.BatchNorm2d):
  383. m.eps = 1e-3
  384. m.momentum = 0.03
  385. elif isinstance(m, (nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.Hardswish, nn.SiLU)):
  386. m.inplace = True
  387. def prep_model_for_conversion(self, input_size: Union[tuple, list] = None, **kwargs):
  388. """
  389. A method for preparing the Yolo model for conversion to other frameworks (ONNX, CoreML etc)
  390. :param input_size: expected input size
  391. :return:
  392. """
  393. assert not self.training, "model has to be in eval mode to be converted"
  394. # Verify dummy_input from converter is of multiple of the grid size
  395. max_stride = int(max(self.stride))
  396. # Validate the image size
  397. image_dims = input_size[-2:] # assume torch uses channels first layout
  398. for dim in image_dims:
  399. res_flag, suggestion = check_img_size_divisibility(dim, max_stride)
  400. if not res_flag:
  401. raise ValueError(
  402. f"Invalid input size: {input_size}. The input size must be multiple of max stride: "
  403. f"{max_stride}. The closest suggestions are: {suggestion[0]}x{suggestion[0]} or "
  404. f"{suggestion[1]}x{suggestion[1]}"
  405. )
  406. def get_include_attributes(self) -> list:
  407. return ["grid", "anchors", "anchors_grid"]
  408. def replace_head(self, new_num_classes=None, new_head=None):
  409. if new_num_classes is None and new_head is None:
  410. raise ValueError("At least one of new_num_classes, new_head must be given to replace output layer.")
  411. if new_head is not None:
  412. self._head = new_head
  413. else:
  414. self.arch_params.num_classes = new_num_classes
  415. self.num_classes = new_num_classes
  416. old_detectx = self._head._modules_list[-1]
  417. _, block, activation_type, width_mult, depth_mult = get_yolo_type_params(
  418. self.arch_params.yolo_type, self.arch_params.width_mult_factor, self.arch_params.depth_mult_factor
  419. )
  420. new_last_layer = DetectX(
  421. num_classes=new_num_classes,
  422. stride=self._head.anchors.stride,
  423. activation_func_type=activation_type,
  424. channels=[width_mult(v) for v in (256, 512, 1024)],
  425. depthwise=isinstance(old_detectx.cls_convs[0][0], GroupedConvBlock),
  426. groups=self.arch_params.xhead_groups,
  427. inter_channels=self.arch_params.xhead_inter_channels,
  428. )
  429. new_last_layer = new_last_layer.to(next(self.parameters()).device)
  430. self._head._modules_list[-1] = new_last_layer
  431. self._check_strides()
  432. self._initialize_biases()
  433. self._initialize_weights()
Discard
Tip!

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