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

yolov3.py 26 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
  1. """
  2. Yolov3 code adapted from https://github.com/ultralytics/yolov3
  3. """
  4. from typing import Union
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.functional as F
  8. import numpy as np
  9. from super_gradients.training.models import SgModule
  10. from super_gradients.training.models.detection_models.darknet53 import Darknet53, DarkResidualBlock, create_conv_module
  11. from super_gradients.training.utils import HpmStruct, get_param
  12. class SPPLayer(nn.Module):
  13. def __init__(self):
  14. super(SPPLayer, self).__init__()
  15. def forward(self, x):
  16. x_1 = x
  17. x_2 = F.max_pool2d(x, 5, stride=1, padding=2)
  18. x_3 = F.max_pool2d(x, 9, stride=1, padding=4)
  19. x_4 = F.max_pool2d(x, 13, stride=1, padding=6)
  20. out = torch.cat((x_1, x_2, x_3, x_4), dim=1)
  21. return out
  22. class Upsample(nn.Module):
  23. def __init__(self, scale_factor, mode="nearest"):
  24. super(Upsample, self).__init__()
  25. self.scale_factor = scale_factor
  26. self.mode = mode
  27. def forward(self, x):
  28. x = F.interpolate(x, scale_factor=self.scale_factor, mode=self.mode)
  29. return x
  30. class YOLOLayer(nn.Module):
  31. def __init__(self, anchors_mask: list, classes_num: int, anchors: list, image_size: int, onnx_stride: int,
  32. onnx_export_mode: bool = False):
  33. """
  34. YOLOLayer
  35. :param anchors_mask:
  36. :param classes_num:
  37. :param anchors:
  38. :param image_size:
  39. :param onnx_stride:
  40. :param onnx_export_mode:
  41. """
  42. super(YOLOLayer, self).__init__()
  43. self.anchors = anchors
  44. self.onnx_export_mode = onnx_export_mode
  45. masked_anchors = [self.anchors[i] for i in anchors_mask]
  46. anchors = np.array(masked_anchors)
  47. self.anchors_mask = torch.Tensor(anchors)
  48. self.anchors_num = len(anchors_mask)
  49. self.classes_num = classes_num
  50. self.x_grid_points_num = 0
  51. self.y_grid_points_num = 0
  52. self.onnx_stride = onnx_stride
  53. def forward(self, img, img_size):
  54. if self.onnx_export_mode:
  55. # ALL OF THE GRIDS WERE CALCULATED IN init
  56. batch_size = 1
  57. else:
  58. batch_size, _, y_grid_points_num, x_grid_points_num = img.shape
  59. if (self.x_grid_points_num, self.y_grid_points_num) != (x_grid_points_num, y_grid_points_num):
  60. self.create_grids(img_size, (x_grid_points_num, y_grid_points_num), img.device, img.dtype)
  61. # PREDICTION
  62. # IMG.VIEW(BATCH_SIZE, PRE_YOLO_LAYER_SIZE(DEFAULT IS 255), 13, 13) --> (BATCH_SIZE, 3, 13, 13, NUM_CLASSES + 5)
  63. # (BS, ANCHORS_NUM, GRID, GRID, CLASSES + XYWH + OBJECTNESS)
  64. prediction = img.view(batch_size, self.anchors_num, self.classes_num + 5, self.y_grid_points_num,
  65. self.x_grid_points_num).permute(0, 1, 3, 4, 2).contiguous()
  66. if self.training:
  67. return prediction
  68. # INFERENCE - ONNX
  69. elif self.onnx_export_mode:
  70. # CONSTANTS CAN NOT BE BROADCASTED
  71. m = self.anchors_num * self.x_grid_points_num * self.y_grid_points_num
  72. ngu = self.grid_size.repeat((1, m, 1))
  73. grid_xy = self.grid_xy.repeat((1, self.anchors_num, 1, 1, 1)).view(1, m, 2)
  74. anchor_wh = self.anchor_wh.repeat((1, 1, self.x_grid_points_num, self.y_grid_points_num, 1)).view(1, m,
  75. 2) / ngu
  76. # MOVE THE TENSORS TO SAME DEVICE AS prediction TO APPLY TENSOR CALCULATION
  77. ngu = ngu.to(prediction.device)
  78. grid_xy = grid_xy.to(prediction.device)
  79. anchor_wh = anchor_wh.to(prediction.device)
  80. prediction = prediction.view(m, 5 + self.classes_num)
  81. xy = torch.sigmoid(prediction[..., 0:2]) + grid_xy[0] # x, y
  82. wh = torch.exp(prediction[..., 2:4]) * anchor_wh[0] # width, height
  83. prediction_confidence = torch.sigmoid(prediction[:, 4:5])
  84. # CHANGE THE RESULTS TO BE A VECTOR OF CLASS CONF * OBJECTNESS CONF FOR EACH OF THE CLASSES (like SSD)
  85. cls_prediction = F.softmax(prediction[:, 5:5 + self.classes_num], 1) * prediction_confidence
  86. return torch.cat((xy / ngu[0], wh, prediction_confidence, cls_prediction), 1).t()
  87. # INFERENCE
  88. else:
  89. inference_out = prediction.clone()
  90. inference_out[..., 0:2] = torch.sigmoid(inference_out[..., 0:2]) + self.grid_xy
  91. inference_out[..., 2:4] = torch.exp(inference_out[..., 2:4]) * self.anchor_wh
  92. inference_out[..., :4] *= self.stride
  93. torch.sigmoid_(inference_out[..., 4:])
  94. if self.classes_num == 1:
  95. # IGNORE cls FOR SINGLE CLASS DATA SETS
  96. inference_out[..., 5] = 1
  97. # RESHAPE FROM [1, 3, 13, 13, NUM_CLASSES + 5] TO [1, 507, NUM_CLASSES + 5]
  98. return inference_out.view(batch_size, -1, 5 + self.classes_num), prediction
  99. def create_grids(self, img_size=(416, 416), grid_size=(13, 13), device='cpu', data_type=torch.float32):
  100. """
  101. create_grids - Creates the grids for image sizes that are different than the model's defualt image size
  102. :param img_size:
  103. :param grid_size:
  104. :param device:
  105. :param data_type:
  106. """
  107. nx, ny = grid_size
  108. self.img_size = max(img_size)
  109. self.stride = self.img_size / max(grid_size)
  110. # build xy offsets
  111. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  112. self.grid_xy = torch.stack((xv, yv), 2).to(device).type(data_type).view((1, 1, ny, nx, 2))
  113. # build wh gains
  114. self.anchor_vec = self.anchors_mask.to(device) / self.stride
  115. self.anchor_wh = self.anchor_vec.view(1, self.anchors_num, 1, 1, 2).to(device).type(data_type)
  116. self.grid_size = torch.Tensor(grid_size).to(device)
  117. self.x_grid_points_num = nx
  118. self.y_grid_points_num = ny
  119. class YoloV3(SgModule):
  120. """
  121. YoloV3
  122. """
  123. def __init__(self, num_classes: int = 80, image_size: int = 416,
  124. arch_params: HpmStruct = None,
  125. iou_t: float = 0.225, yolo_v3_anchors: list = None, onnx_export_mode=False):
  126. super(YoloV3, self).__init__()
  127. if arch_params:
  128. arch_params_dict = arch_params.to_dict()
  129. self.num_classes = arch_params.num_classes if 'num_classes' in arch_params_dict else num_classes
  130. self.image_size = arch_params.image_size if 'image_size' in arch_params_dict else image_size
  131. self.iou_t = arch_params.iou_t if 'iou_t' in arch_params_dict else iou_t
  132. self.onnx_export_mode = arch_params.onnx_export_mode if \
  133. 'onnx_export_mode' in arch_params_dict else onnx_export_mode
  134. yolo_v3_anchors = arch_params.yolo_v3_anchors if 'yolo_v3_anchors' in arch_params_dict else yolo_v3_anchors
  135. else:
  136. self.image_size = image_size
  137. self.num_classes = num_classes
  138. self.iou_t = iou_t
  139. self.onnx_export_mode = onnx_export_mode
  140. # THIS IS THE LAYER SIZE THAT FEEDS THE YOLO LAYER
  141. self.pre_yolo_layer_size = (self.num_classes + 5) * 3
  142. if yolo_v3_anchors is None:
  143. # USE DEFAULT COCO DATA SET ANCHORS FOR YOLO V3
  144. yolo_v3_anchors = [
  145. (10., 13.), (16., 30.), (33., 23.),
  146. (30., 61.), (62., 45.), (59., 119.),
  147. (116., 90.), (156., 198.), (373., 326.)]
  148. self.yolo_v3_anchors = yolo_v3_anchors
  149. self.module_list = self.create_modules_list(num_classes=self.num_classes)
  150. self.yolo_layers_indices = self.get_yolo_layers_indices()
  151. if self.onnx_export_mode:
  152. self.prep_model_for_conversion([self.image_size, self.image_size])
  153. def forward(self, x, var=None):
  154. img_size = x.shape[-2:]
  155. yolo_output = []
  156. route_layers = []
  157. for i, module in enumerate(self.module_list):
  158. if isinstance(module, YOLOLayer):
  159. y = module(x, img_size=img_size)
  160. yolo_output.append(y)
  161. else:
  162. x = module(x)
  163. # CONCATENATE THE OUTPUTS OF PREVIOUS LAYERS
  164. x, route_layers = self.concatenate_layer_output(x, i, route_layers)
  165. if self.training:
  166. return yolo_output
  167. elif self.onnx_export_mode:
  168. # CAT 3 LAYERS (NUM_CLASSES + 5) X (507, 2028, 8112) TO (NUM_CLASSES + 5) X 10647
  169. output = torch.cat(yolo_output, 1)
  170. # ONNX SCORES, bboxes
  171. return output[5:5 + self.num_classes].t(), output[0:4].t()
  172. else:
  173. # INFERENCE
  174. inference_output, training_output = list(zip(*yolo_output))
  175. return torch.cat(inference_output, 1), training_output
  176. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  177. """
  178. initialize_optimizer_for_model_param_groups - Initializes the optimizer group params,
  179. adds weight decay *Only* to the Conv2D layers
  180. :param lr: lr to set for the optimizer
  181. :param training_params:
  182. :return: A dictionary with named params and optimizer attributes
  183. """
  184. optimizer_params = get_param(training_params, 'optimizer_params')
  185. # OPTIMIZER PARAMETER GROUPS
  186. default_param_group, weight_decay_param_group, biases_param_group = [], [], []
  187. for k, v in dict(self.named_parameters()).items():
  188. if '.bias' in k:
  189. biases_param_group += [[k, v]]
  190. elif 'Conv2d.weight' in k:
  191. weight_decay_param_group += [[k, v]]
  192. else:
  193. default_param_group += [[k, v]]
  194. # DEFAULT USAGE FOR YOLO TRAINING IS WITH NESTEROV
  195. nesterov = True if 'nesterov' not in optimizer_params.keys() else optimizer_params['nesterov']
  196. default_param_group_optimizer_format = {'named_params': default_param_group,
  197. 'lr': lr,
  198. 'nesterov': nesterov,
  199. 'momentum': optimizer_params['momentum']}
  200. weight_decay_param_group_optimizer_format = {'named_params': weight_decay_param_group,
  201. 'weight_decay': optimizer_params['weight_decay']}
  202. biases_param_group_optimizer_format = {'named_params': biases_param_group}
  203. return [default_param_group_optimizer_format,
  204. weight_decay_param_group_optimizer_format,
  205. biases_param_group_optimizer_format]
  206. @staticmethod
  207. def concatenate_layer_output(x, layer_index: int, route_layers: list) -> tuple:
  208. """
  209. concatenate_layer_output
  210. :param x: input for the layer
  211. :param layer_index: the layer index to decide how to concatenate to
  212. :param route_layers: the route layers list with previous data
  213. :return: tuple of x, route_layers
  214. """
  215. # CONCATENATE THE OUTPUTS OF PREVIOUS LAYERS
  216. if layer_index in [6, 8, 16, 26]:
  217. route_layers.append(x)
  218. if layer_index == 19:
  219. x = route_layers[2]
  220. if layer_index == 29:
  221. x = route_layers[3]
  222. if layer_index == 21:
  223. x = torch.cat((x, route_layers[1]), 1)
  224. if layer_index == 31:
  225. x = torch.cat((x, route_layers[0]), 1)
  226. return x, route_layers
  227. def get_yolo_layers_indices(self):
  228. return [i for i, module in enumerate(self.module_list) if isinstance(module, YOLOLayer)]
  229. @staticmethod
  230. def add_yolo_layer_to_modules_list(modules_list: nn.ModuleList, image_size: int, yolo_v3_anchors: list,
  231. anchors_mask: list, num_classes: int, onnx_stride: int,
  232. onnx_export_mode: bool = False) -> nn.ModuleList:
  233. """
  234. add_yolo_layer_to_modules_list - Adds a YoLo Head Layer to the nn.ModuleList
  235. :param modules_list: The Modules List
  236. :param image_size: The YoLo Model Image Size
  237. :param yolo_v3_anchors: The Anchors (K-Means) List for the YoLo Layer Initialization
  238. :param anchors_mask: the mask to get the relevant anchors
  239. :param num_classes: The number of different classes in the data
  240. :param onnx_stride: The stride of the layer for ONNX grid points calculation in YoLo Layer init
  241. :param onnx_export_mode: Alter the model YoLo Layer for ONNX Export
  242. :return: The nn.ModuleList with the Added Yolo layer, and a Bias Initialization
  243. """
  244. mask = [yolo_v3_anchors[i] for i in anchors_mask]
  245. b = [-5.5, -5.0]
  246. bias = modules_list[-1][0].bias.view(len(mask), -1) # PRE-YOLO-LAYER to 3x(NUM_CLASSES + 5)
  247. with torch.no_grad():
  248. bias[:, 4] += b[0] - bias[:, 4].mean() # OBJECTNESS
  249. bias[:, 5:] += b[1] - bias[:, 5:].mean() # CLASSIFICATION
  250. modules_list[-1][0].bias = torch.nn.Parameter(bias.view(-1))
  251. modules_list.append(YOLOLayer(anchors_mask=anchors_mask, classes_num=num_classes, anchors=yolo_v3_anchors,
  252. image_size=image_size, onnx_stride=onnx_stride,
  253. onnx_export_mode=onnx_export_mode))
  254. return modules_list
  255. @staticmethod
  256. def named_sequential_module(module_name, module) -> nn.Sequential:
  257. """
  258. create_named_nn_sequential_module
  259. :param module_name:
  260. :param module:
  261. :return: nn.Sequential() with the added relevant names
  262. """
  263. named_sequential_module = nn.Sequential()
  264. named_sequential_module.add_module(module_name, module)
  265. return named_sequential_module
  266. def create_modules_list(self, num_classes: int):
  267. """
  268. create_modules_list
  269. :param num_classes:
  270. :return:
  271. """
  272. # DARKNET BACKBONE ARCHITECTURE
  273. darknet_53 = Darknet53(backbone_mode=True)
  274. yolo_modules_list = darknet_53.get_modules_list()
  275. # YOLO V3 ARCHITECTURE
  276. yolo_modules_list.append(DarkResidualBlock(in_channels=1024, shortcut=False)) # 11
  277. yolo_modules_list.append(create_conv_module(in_channels=1024, out_channels=512, kernel_size=1, stride=1)) # 12
  278. yolo_modules_list.append(SPPLayer()) # 13
  279. yolo_modules_list.append(create_conv_module(in_channels=2048, out_channels=512, kernel_size=1, stride=1)) # 14
  280. yolo_modules_list.append(create_conv_module(in_channels=512, out_channels=1024, kernel_size=3, stride=1)) # 15
  281. yolo_modules_list.append(create_conv_module(in_channels=1024, out_channels=512, kernel_size=1, stride=1)) # 16
  282. yolo_modules_list.append(create_conv_module(in_channels=512, out_channels=1024, kernel_size=3, stride=1)) # 17
  283. yolo_modules_list.append(self.named_sequential_module('Conv2d',
  284. nn.Conv2d(in_channels=1024,
  285. out_channels=self.pre_yolo_layer_size,
  286. kernel_size=1, stride=1))) # 18
  287. yolo_modules_list = self.add_yolo_layer_to_modules_list(modules_list=yolo_modules_list, # 19
  288. image_size=self.image_size,
  289. yolo_v3_anchors=self.yolo_v3_anchors,
  290. anchors_mask=[6, 7, 8], num_classes=num_classes,
  291. onnx_stride=32, onnx_export_mode=self.onnx_export_mode)
  292. yolo_modules_list.append(create_conv_module(in_channels=512, out_channels=256, kernel_size=1, stride=1)) # 20
  293. yolo_modules_list.append(Upsample(scale_factor=2, mode='nearest')) # 21
  294. yolo_modules_list.append(create_conv_module(in_channels=768, out_channels=256, kernel_size=1, stride=1)) # 22
  295. yolo_modules_list.append(create_conv_module(in_channels=256, out_channels=512, kernel_size=3, stride=1)) # 23
  296. yolo_modules_list.append(create_conv_module(in_channels=512, out_channels=256, kernel_size=1, stride=1)) # 24
  297. yolo_modules_list.append(create_conv_module(in_channels=256, out_channels=512, kernel_size=3, stride=1)) # 25
  298. yolo_modules_list.append(create_conv_module(in_channels=512, out_channels=256, kernel_size=1, stride=1)) # 26
  299. yolo_modules_list.append(create_conv_module(in_channels=256, out_channels=512, kernel_size=3, stride=1)) # 27
  300. yolo_modules_list.append(self.named_sequential_module('Conv2d',
  301. nn.Conv2d(in_channels=512,
  302. out_channels=self.pre_yolo_layer_size,
  303. kernel_size=1, stride=1))) # 28
  304. yolo_modules_list = self.add_yolo_layer_to_modules_list(modules_list=yolo_modules_list, # 29
  305. image_size=self.image_size,
  306. yolo_v3_anchors=self.yolo_v3_anchors,
  307. anchors_mask=[3, 4, 5], num_classes=num_classes,
  308. onnx_stride=16, onnx_export_mode=self.onnx_export_mode)
  309. yolo_modules_list.append(create_conv_module(in_channels=256, out_channels=128, kernel_size=1, stride=1)) # 30
  310. yolo_modules_list.append(Upsample(scale_factor=2, mode='nearest')) # 31
  311. yolo_modules_list.append(create_conv_module(in_channels=384, out_channels=128, kernel_size=1, stride=1)) # 32
  312. yolo_modules_list.append(create_conv_module(in_channels=128, out_channels=256, kernel_size=3, stride=1)) # 33
  313. yolo_modules_list.append(create_conv_module(in_channels=256, out_channels=128, kernel_size=1, stride=1)) # 34
  314. yolo_modules_list.append(create_conv_module(in_channels=128, out_channels=256, kernel_size=3, stride=1)) # 35
  315. yolo_modules_list.append(create_conv_module(in_channels=256, out_channels=128, kernel_size=1, stride=1)) # 36
  316. yolo_modules_list.append(create_conv_module(in_channels=128, out_channels=256, kernel_size=3, stride=1)) # 37
  317. yolo_modules_list.append(self.named_sequential_module('Conv2d',
  318. nn.Conv2d(in_channels=256,
  319. out_channels=self.pre_yolo_layer_size,
  320. kernel_size=1, stride=1))) # 38
  321. yolo_modules_list = self.add_yolo_layer_to_modules_list(modules_list=yolo_modules_list, # 39
  322. image_size=self.image_size,
  323. yolo_v3_anchors=self.yolo_v3_anchors,
  324. anchors_mask=[0, 1, 2], num_classes=num_classes,
  325. onnx_stride=8, onnx_export_mode=self.onnx_export_mode)
  326. return yolo_modules_list
  327. def prep_model_for_conversion(self, input_size: Union[tuple, list] = None, **kwargs):
  328. """
  329. Method for preparing the Yolov3 and TinyYolov3 for conversion (ONNX, TRT, CoreML etc).
  330. :param input_size: used for calculating the grid points.
  331. """
  332. self.onnx_export_mode = True
  333. # ONNX EXPORT REQUIRES GRIDS TO BE CALCULATED IN init of YOLOLayer SO WE RE-RUN THE CALC METHOD
  334. for module in self.module_list:
  335. if isinstance(module, YOLOLayer):
  336. module.onnx_export_mode = True
  337. x_grid_points_num = int(input_size / module.onnx_stride)
  338. y_grid_points_num = int(input_size / module.onnx_stride)
  339. module.create_grids((input_size, input_size), (x_grid_points_num, y_grid_points_num))
  340. class TinyYoloV3(YoloV3):
  341. """
  342. TinyYoloV3 - Inherits from YoLoV3 class and overloads the relevant methods and members
  343. """
  344. def __init__(self, num_classes: int = 80, image_size: int = 416,
  345. arch_params: dict = None,
  346. iou_t: float = 0.225, yolo_v3_anchors: list = None):
  347. if arch_params:
  348. yolo_v3_anchors = arch_params.yolo_v3_anchors if 'yolo_v3_anchors' in arch_params.to_dict() else yolo_v3_anchors
  349. if yolo_v3_anchors is None:
  350. # DEFAULT ANCHORS FOR TINY YOLO V3
  351. yolo_v3_anchors = [(10., 14.), (23., 27.), (37., 58.),
  352. (81., 82.), (135., 169.), (344., 319.)]
  353. super(TinyYoloV3, self).__init__(num_classes=num_classes, image_size=image_size,
  354. arch_params=arch_params, iou_t=iou_t, yolo_v3_anchors=yolo_v3_anchors)
  355. @staticmethod
  356. def concatenate_layer_output(x, layer_index: int, route_layers: list) -> tuple:
  357. """
  358. concatenate_layer_output
  359. :param x: input for the layer
  360. :param layer_index: the layer index to decide how to concatenate to
  361. :param route_layers: the route layers list with previous data
  362. :return: tuple of x, route_layers
  363. """
  364. # CONCATENATE THE OUTPUTS OF PREVIOUS LAYERS
  365. if layer_index in [8, 14]:
  366. route_layers.append(x)
  367. if layer_index == 17:
  368. x = route_layers[1]
  369. if layer_index == 19:
  370. x = torch.cat((x, route_layers[0]), 1)
  371. return x, route_layers
  372. def create_modules_list(self, num_classes: int):
  373. """
  374. create_tiny_modules_list
  375. :param num_classes: The Number of different Classes
  376. :return: nn.ModuleList with the Tiny-Yolo-V3 Architecture
  377. """
  378. yolo_modules_list = nn.ModuleList()
  379. yolo_modules_list.append(create_conv_module(3, 16)) # 0
  380. yolo_modules_list.append(self.named_sequential_module('MaxPool2d', nn.MaxPool2d(stride=2, kernel_size=2))) # 1
  381. yolo_modules_list.append(create_conv_module(16, 32)) # 2
  382. yolo_modules_list.append(self.named_sequential_module('MaxPool2d', nn.MaxPool2d(stride=2, kernel_size=2))) # 3
  383. yolo_modules_list.append(create_conv_module(32, 64)) # 4
  384. yolo_modules_list.append(self.named_sequential_module('MaxPool2d', nn.MaxPool2d(stride=2, kernel_size=2))) # 5
  385. yolo_modules_list.append(create_conv_module(64, 128)) # 6
  386. yolo_modules_list.append(self.named_sequential_module('MaxPool2d', nn.MaxPool2d(stride=2, kernel_size=2))) # 7
  387. yolo_modules_list.append(create_conv_module(128, 256)) # 8
  388. yolo_modules_list.append(self.named_sequential_module('MaxPool2d', nn.MaxPool2d(stride=2, kernel_size=2))) # 9
  389. yolo_modules_list.append(create_conv_module(256, 512)) # 10
  390. yolo_modules_list.append(self.named_sequential_module('ZeroPad2d', nn.ZeroPad2d((0, 1, 0, 1)))) # 11
  391. yolo_modules_list.append(self.named_sequential_module('MaxPool2d', nn.MaxPool2d(stride=1, kernel_size=2))) # 12
  392. yolo_modules_list.append(create_conv_module(512, 1024)) # 13
  393. yolo_modules_list.append(create_conv_module(1024, 256, kernel_size=1)) # 14
  394. yolo_modules_list.append(create_conv_module(256, 512)) # 15
  395. yolo_modules_list.append(self.named_sequential_module('Conv2d',
  396. nn.Conv2d(in_channels=512,
  397. out_channels=self.pre_yolo_layer_size,
  398. kernel_size=1, stride=1))) # 16
  399. yolo_modules_list = self.add_yolo_layer_to_modules_list(modules_list=yolo_modules_list, # 17
  400. image_size=self.image_size,
  401. yolo_v3_anchors=self.yolo_v3_anchors,
  402. anchors_mask=[3, 4, 5], num_classes=num_classes,
  403. onnx_stride=32, onnx_export_mode=self.onnx_export_mode)
  404. yolo_modules_list.append(create_conv_module(256, 128, kernel_size=1)) # 18
  405. yolo_modules_list.append(Upsample(scale_factor=2, mode='nearest')) # 19
  406. yolo_modules_list.append(create_conv_module(384, 256)) # 20
  407. yolo_modules_list.append(self.named_sequential_module('Conv2d',
  408. nn.Conv2d(in_channels=256,
  409. out_channels=self.pre_yolo_layer_size,
  410. kernel_size=1, stride=1))) # 21
  411. # THE [1, 2, 3] IN THE MASK IS NOT A BUG, BUT A FEATURE :)
  412. yolo_modules_list = self.add_yolo_layer_to_modules_list(modules_list=yolo_modules_list, # 22
  413. image_size=self.image_size,
  414. yolo_v3_anchors=self.yolo_v3_anchors,
  415. anchors_mask=[1, 2, 3], num_classes=num_classes,
  416. onnx_stride=16, onnx_export_mode=self.onnx_export_mode)
  417. return yolo_modules_list
Tip!

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

Comments

Loading...