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

#683 Bugfix/INFRA-1707_fixing-docker-publish

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/INFRA-1707_fixing-docker-publish
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
  1. """
  2. Shelfnet
  3. paper: https://arxiv.org/abs/1811.11254
  4. based on: https://github.com/juntang-zhuang/ShelfNet
  5. """
  6. import torch
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. from super_gradients.training.models.sg_module import SgModule
  10. from super_gradients.training.utils import HpmStruct
  11. from super_gradients.training.models.classification_models.resnet import BasicBlock, ResNet, Bottleneck
  12. class FCNHead(nn.Module):
  13. def __init__(self, in_channels, out_channels):
  14. super().__init__()
  15. inter_channels = in_channels // 4
  16. self.fcn = nn.Sequential(
  17. nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),
  18. nn.BatchNorm2d(inter_channels),
  19. nn.ReLU(),
  20. nn.Dropout2d(0.1, False),
  21. nn.Conv2d(inter_channels, out_channels, 1),
  22. )
  23. def forward(self, x):
  24. return self.fcn(x)
  25. class ShelfBlock(nn.Module):
  26. def __init__(self, in_planes: int, planes: int, stride: int = 1, dropout: float = 0.25):
  27. """
  28. S-Block implementation from the ShelfNet paper
  29. :param in_planes: input planes
  30. :param planes: output planes
  31. :param stride: convolution stride
  32. :param dropout: dropout percentage
  33. """
  34. super().__init__()
  35. if in_planes != planes:
  36. self.conv0 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=1, padding=1, bias=True)
  37. self.relu0 = nn.ReLU(inplace=True)
  38. self.in_planes = in_planes
  39. self.planes = planes
  40. self.conv1 = nn.Conv2d(self.planes, self.planes, kernel_size=3, stride=stride, padding=1, bias=True)
  41. self.bn1 = nn.BatchNorm2d(self.planes)
  42. self.relu1 = nn.ReLU(inplace=True)
  43. self.dropout = nn.Dropout2d(p=dropout)
  44. self.bn2 = nn.BatchNorm2d(self.planes)
  45. self.relu2 = nn.ReLU(inplace=True)
  46. def forward(self, x):
  47. if self.in_planes != self.planes:
  48. x = self.conv0(x)
  49. x = self.relu0(x)
  50. out = self.conv1(x)
  51. out = self.bn1(out)
  52. out = self.relu1(out)
  53. out = self.dropout(out)
  54. out = self.conv1(out)
  55. out = self.bn2(out)
  56. out = out + x
  57. return self.relu2(out)
  58. class ShelfResNetBackBone(ResNet):
  59. """
  60. ShelfResNetBackBone - A class that Inherits from the original ResNet class and manipulates the forward pass,
  61. to create a backbone for the ShelfNet architecture
  62. """
  63. def __init__(self, block, num_blocks, num_classes=10, width_mult=1):
  64. super().__init__(block=block, num_blocks=num_blocks, num_classes=num_classes, width_mult=width_mult, backbone_mode=True)
  65. def forward(self, x):
  66. out = F.relu(self.bn1(self.conv1(x)))
  67. out = self.maxpool(out)
  68. feat4 = self.layer1(out) # 1/4
  69. feat8 = self.layer2(feat4) # 1/8
  70. feat16 = self.layer3(feat8) # 1/16
  71. feat32 = self.layer4(feat16) # 1/32
  72. return feat4, feat8, feat16, feat32
  73. class ShelfResNetBackBone18(ShelfResNetBackBone):
  74. def __init__(self, num_classes: int):
  75. super().__init__(BasicBlock, [2, 2, 2, 2], num_classes=num_classes)
  76. class ShelfResNetBackBone34(ShelfResNetBackBone):
  77. def __init__(self, num_classes: int):
  78. super().__init__(BasicBlock, [3, 4, 6, 3], num_classes=num_classes)
  79. class ShelfResNetBackBone503343(ShelfResNetBackBone):
  80. def __init__(self, num_classes: int):
  81. super().__init__(Bottleneck, [3, 3, 4, 3], num_classes=num_classes)
  82. class ShelfResNetBackBone50(ShelfResNetBackBone):
  83. def __init__(self, num_classes: int):
  84. super().__init__(Bottleneck, [3, 4, 6, 3], num_classes=num_classes)
  85. class ShelfResNetBackBone101(ShelfResNetBackBone):
  86. def __init__(self, num_classes: int):
  87. super().__init__(Bottleneck, [3, 4, 23, 3], num_classes=num_classes)
  88. class ShelfNetModuleBase(SgModule):
  89. """
  90. ShelfNetModuleBase - Base class for the different Modules of the ShelfNet Architecture
  91. """
  92. def __init__(self):
  93. super().__init__()
  94. def forward(self, x):
  95. raise NotImplementedError
  96. def get_params(self):
  97. wd_params, nowd_params = [], []
  98. for name, module in self.named_modules():
  99. if isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d):
  100. wd_params.append(module.weight)
  101. if module.bias is not None:
  102. nowd_params.append(module.bias)
  103. elif isinstance(module, nn.BatchNorm2d):
  104. nowd_params += list(module.parameters())
  105. return wd_params, nowd_params
  106. class ConvBNReLU(ShelfNetModuleBase):
  107. def __init__(self, in_chan: int, out_chan: int, ks: int = 3, stride: int = 1, padding: int = 1):
  108. super(ConvBNReLU, self).__init__()
  109. self.conv = nn.Conv2d(in_chan, out_chan, kernel_size=ks, stride=stride, padding=padding, bias=False)
  110. self.bn = nn.BatchNorm2d(out_chan)
  111. self.init_weight()
  112. def forward(self, x):
  113. x = self.conv(x)
  114. x = self.bn(x)
  115. x = F.relu(x)
  116. return x
  117. def init_weight(self):
  118. for ly in self.children():
  119. if isinstance(ly, nn.Conv2d):
  120. nn.init.kaiming_normal_(ly.weight, a=1)
  121. if ly.bias is not None:
  122. nn.init.constant_(ly.bias, 0)
  123. class DecoderBase(ShelfNetModuleBase):
  124. def __init__(self, planes: int, layers: int, kernel: int = 3, block=ShelfBlock):
  125. super().__init__()
  126. self.planes = planes
  127. self.layers = layers
  128. self.kernel = kernel
  129. self.padding = int((kernel - 1) / 2)
  130. self.inconv = block(planes, planes)
  131. # CREATE MODULE FOR BOTTOM BLOCK
  132. self.bottom = block(planes * (2 ** (layers - 1)), planes * (2 ** (layers - 1)))
  133. # CREATE MODULE LIST FOR UP BRANCH
  134. self.up_conv_list = nn.ModuleList()
  135. self.up_dense_list = nn.ModuleList()
  136. def forward(self, x):
  137. raise NotImplementedError
  138. class DecoderHW(DecoderBase):
  139. """
  140. DecoderHW - The Decoder for the Heavy-Weight ShelfNet Architecture
  141. """
  142. def __init__(self, planes, layers, block=ShelfBlock, *args, **kwargs):
  143. super().__init__(planes=planes, layers=layers, block=block, *args, **kwargs)
  144. for i in range(0, layers - 1):
  145. self.up_conv_list.append(
  146. nn.ConvTranspose2d(
  147. planes * 2 ** (layers - 1 - i), planes * 2 ** max(0, layers - i - 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=True
  148. )
  149. )
  150. self.up_dense_list.append(block(planes * 2 ** max(0, layers - i - 2), planes * 2 ** max(0, layers - i - 2)))
  151. def forward(self, x):
  152. # BOTTOM BRANCH
  153. out = self.bottom(x[-1])
  154. bottom = out
  155. # UP BRANCH
  156. up_out = []
  157. up_out.append(bottom)
  158. for j in range(0, self.layers - 1):
  159. out = self.up_conv_list[j](out) + x[self.layers - j - 2]
  160. out = self.up_dense_list[j](out)
  161. up_out.append(out)
  162. return up_out
  163. class DecoderLW(DecoderBase):
  164. """
  165. DecoderLW - The Decoder for the Light-Weight ShelfNet Architecture
  166. """
  167. def __init__(self, planes, layers, block=ShelfBlock, *args, **kwargs):
  168. super().__init__(planes=planes, layers=layers, block=block, *args, **kwargs)
  169. for i in range(0, layers - 1):
  170. self.up_conv_list.append(AttentionRefinementModule(planes * 2 ** (layers - 1 - i), planes * 2 ** max(0, layers - i - 2)))
  171. self.up_dense_list.append(ConvBNReLU(in_chan=planes * 2 ** max(0, layers - i - 2), out_chan=planes * 2 ** max(0, layers - i - 2), ks=3, stride=1))
  172. def forward(self, x):
  173. # BOTTOM BRANCH
  174. out = self.bottom(x[-1])
  175. bottom = out
  176. # UP BRANCH
  177. up_out = []
  178. up_out.append(bottom)
  179. for j in range(0, self.layers - 1):
  180. out = self.up_conv_list[j](out)
  181. out_interpolate = F.interpolate(out, (out.size(2) * 2, out.size(3) * 2), mode="nearest")
  182. out = out_interpolate + x[self.layers - j - 2]
  183. out = self.up_dense_list[j](out)
  184. up_out.append(out)
  185. return up_out
  186. class AttentionRefinementModule(nn.Module):
  187. def __init__(self, in_chan, out_chan):
  188. super().__init__()
  189. self.conv = ConvBNReLU(in_chan, out_chan, ks=3, stride=1, padding=1)
  190. self.conv_atten = nn.Conv2d(out_chan, out_chan, kernel_size=1, bias=False)
  191. self.bn_atten = nn.BatchNorm2d(out_chan)
  192. self.sigmoid_atten = nn.Sigmoid()
  193. self.init_weight()
  194. def forward(self, x):
  195. feat = self.conv(x)
  196. atten = F.avg_pool2d(feat, feat.size()[2:])
  197. atten = self.conv_atten(atten)
  198. atten = self.bn_atten(atten)
  199. atten = self.sigmoid_atten(atten)
  200. out = torch.mul(feat, atten)
  201. return out
  202. def init_weight(self):
  203. for ly in self.children():
  204. if isinstance(ly, nn.Conv2d):
  205. nn.init.kaiming_normal_(ly.weight, a=1)
  206. if ly.bias is not None:
  207. nn.init.constant_(ly.bias, 0)
  208. class LadderBlockBase(ShelfNetModuleBase):
  209. def __init__(self, planes: int, layers: int, kernel: int = 3, block=ShelfBlock):
  210. super().__init__()
  211. self.planes = planes
  212. self.layers = layers
  213. self.kernel = kernel
  214. self.padding = int((kernel - 1) / 2)
  215. self.inconv = block(planes, planes)
  216. # CREATE MODULE LIST FOR DOWN BRANCH
  217. self.down_module_list = nn.ModuleList()
  218. for i in range(0, layers - 1):
  219. self.down_module_list.append(block(planes * (2**i), planes * (2**i)))
  220. # USE STRIDED CONV INSTEAD OF POOLING
  221. self.down_conv_list = nn.ModuleList()
  222. for i in range(0, layers - 1):
  223. self.down_conv_list.append(nn.Conv2d(planes * 2**i, planes * 2 ** (i + 1), stride=2, kernel_size=kernel, padding=self.padding))
  224. # CREATE MODULE FOR BOTTOM BLOCK
  225. self.bottom = block(planes * (2 ** (layers - 1)), planes * (2 ** (layers - 1)))
  226. # CREATE MODULE LIST FOR UP BRANCH
  227. self.up_conv_list = nn.ModuleList()
  228. self.up_dense_list = nn.ModuleList()
  229. def forward(self, x):
  230. raise NotImplementedError
  231. class LadderBlockHW(LadderBlockBase):
  232. """
  233. LadderBlockHW - LadderBlock for the Heavy-Weight ShelfNet Architecture
  234. """
  235. def __init__(self, planes, layers, block=ShelfBlock, *args, **kwargs):
  236. super().__init__(planes=planes, layers=layers, block=block, *args, **kwargs)
  237. for i in range(0, layers - 1):
  238. self.up_conv_list.append(
  239. nn.ConvTranspose2d(
  240. planes * 2 ** (layers - i - 1), planes * 2 ** max(0, layers - i - 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=True
  241. )
  242. )
  243. self.up_dense_list.append(block(planes * 2 ** max(0, layers - i - 2), planes * 2 ** max(0, layers - i - 2)))
  244. def forward(self, x):
  245. out = self.inconv(x[-1])
  246. down_out = []
  247. # down branch
  248. for i in range(0, self.layers - 1):
  249. out = out + x[-i - 1]
  250. out = self.down_module_list[i](out)
  251. down_out.append(out)
  252. out = self.down_conv_list[i](out)
  253. out = F.relu(out)
  254. # bottom branch
  255. out = self.bottom(out)
  256. bottom = out
  257. # up branch
  258. up_out = []
  259. up_out.append(bottom)
  260. for j in range(0, self.layers - 1):
  261. out = self.up_conv_list[j](out) + down_out[self.layers - j - 2]
  262. out = self.up_dense_list[j](out)
  263. up_out.append(out)
  264. return up_out
  265. class LadderBlockLW(LadderBlockBase):
  266. """
  267. LadderBlockLW - LadderBlock for the Light-Weight ShelfNet Architecture
  268. """
  269. def __init__(self, planes, layers, block=ShelfBlock, *args, **kwargs):
  270. super().__init__(planes=planes, layers=layers, block=block, *args, **kwargs)
  271. for i in range(0, layers - 1):
  272. self.up_conv_list.append(AttentionRefinementModule(planes * 2 ** (layers - 1 - i), planes * 2 ** max(0, layers - i - 2)))
  273. self.up_dense_list.append(ConvBNReLU(in_chan=planes * 2 ** max(0, layers - i - 2), out_chan=planes * 2 ** max(0, layers - i - 2), ks=3, stride=1))
  274. def forward(self, x):
  275. out = self.inconv(x[-1])
  276. down_out = []
  277. # DOWN BRANCH
  278. for i in range(0, self.layers - 1):
  279. out = out + x[-i - 1]
  280. out = self.down_module_list[i](out)
  281. down_out.append(out)
  282. out = self.down_conv_list[i](out)
  283. out = F.relu(out)
  284. # BOTTOM BRANCH
  285. out = self.bottom(out)
  286. bottom = out
  287. # UP BRANCH
  288. up_out = []
  289. up_out.append(bottom)
  290. for j in range(0, self.layers - 1):
  291. out = self.up_conv_list[j](out)
  292. out = F.interpolate(out, (out.size(2) * 2, out.size(3) * 2), mode="nearest") + down_out[self.layers - j - 2]
  293. out = self.up_dense_list[j](out)
  294. up_out.append(out)
  295. return up_out
  296. class NetOutput(ShelfNetModuleBase):
  297. def __init__(self, in_chan: int, mid_chan: int, num_classes: int):
  298. super(NetOutput, self).__init__()
  299. self.conv = ConvBNReLU(in_chan, mid_chan, ks=3, stride=1, padding=1)
  300. self.conv_out = nn.Conv2d(mid_chan, num_classes, kernel_size=3, bias=False, padding=1)
  301. self.init_weight()
  302. def forward(self, x):
  303. x = self.conv(x)
  304. x = self.conv_out(x)
  305. return x
  306. def init_weight(self):
  307. for ly in self.children():
  308. if isinstance(ly, nn.Conv2d):
  309. nn.init.kaiming_normal_(ly.weight, a=1)
  310. if ly.bias is not None:
  311. nn.init.constant_(ly.bias, 0)
  312. class ShelfNetBase(ShelfNetModuleBase):
  313. """
  314. ShelfNetBase - ShelfNet Base Generic Architecture
  315. """
  316. def __init__(
  317. self,
  318. backbone: ShelfResNetBackBone,
  319. planes: int,
  320. layers: int,
  321. num_classes: int = 21,
  322. image_size: int = 512,
  323. net_output_mid_channels_num: int = 64,
  324. arch_params: HpmStruct = None,
  325. ):
  326. self.num_classes = arch_params.num_classes if (arch_params and hasattr(arch_params, "num_classes")) else num_classes
  327. self.image_size = arch_params.image_size if (arch_params and hasattr(arch_params, "image_size")) else image_size
  328. super().__init__()
  329. self.net_output_mid_channels_num = net_output_mid_channels_num
  330. self.backbone = backbone(self.num_classes)
  331. self.layers = layers
  332. self.planes = planes
  333. # INITIALIZE WITH AUXILARY HEAD OUTPUTS ONN -> TURN IT OFF TO RUN A FORWARD PASS WITHOUT THE AUXILARY HEADS
  334. self.auxilary_head_outputs = True
  335. # DECODER AND LADDER SHOULD BE IMPLEMENTED BY THE INHERITING CLASS
  336. self.decoder = None
  337. self.ladder = None
  338. # BUILD THE CONV_OUT LIST BASED ON THE AMOUNT OF LAYERS IN THE SHELFNET
  339. self.conv_out_list = torch.nn.ModuleList()
  340. def forward(self, x):
  341. raise NotImplementedError
  342. def update_param_groups(self, param_groups: list, lr: float, epoch: int, iter: int, training_params: HpmStruct, total_batch: int) -> list:
  343. """
  344. update_optimizer_for_param_groups - Updates the specific parameters with different LR
  345. """
  346. # LEARNING RATE FOR THE BACKBONE IS lr
  347. param_groups[0]["lr"] = lr
  348. for i in range(1, len(param_groups)):
  349. # LEARNING RATE FOR OTHER SHELFNET PARAMS IS lr * 10
  350. param_groups[i]["lr"] = lr * 10
  351. return param_groups
  352. class ShelfNetHW(ShelfNetBase):
  353. """
  354. ShelfNetHW - Heavy-Weight Version of ShelfNet
  355. """
  356. def __init__(self, *args, **kwargs):
  357. super().__init__(*args, **kwargs)
  358. self.ladder = LadderBlockHW(planes=self.net_output_mid_channels_num, layers=self.layers)
  359. self.decoder = DecoderHW(planes=self.net_output_mid_channels_num, layers=self.layers)
  360. self.se_layer = nn.Linear(self.net_output_mid_channels_num * 2**3, self.num_classes)
  361. self.aux_head = FCNHead(1024, self.num_classes)
  362. self.final = nn.Conv2d(self.net_output_mid_channels_num, self.num_classes, 1)
  363. # THE MID CHANNELS NUMBER OF THE NET OUTPUT BLOCK
  364. net_out_planes = self.planes
  365. mid_channels_num = self.net_output_mid_channels_num
  366. # INITIALIZE THE conv_out_list
  367. for i in range(self.layers):
  368. self.conv_out_list.append(ConvBNReLU(in_chan=net_out_planes, out_chan=mid_channels_num, ks=1, padding=0))
  369. mid_channels_num *= 2
  370. net_out_planes *= 2
  371. def forward(self, x):
  372. image_size = x.size()[2:]
  373. backbone_features_list = list(self.backbone(x))
  374. conv_bn_relu_results_list = []
  375. for feature, conv_bn_relu in zip(backbone_features_list, self.conv_out_list):
  376. out = conv_bn_relu(feature)
  377. conv_bn_relu_results_list.append(out)
  378. decoder_out_list = self.decoder(conv_bn_relu_results_list)
  379. ladder_out_list = self.ladder(decoder_out_list)
  380. preds = [self.final(ladder_out_list[-1])]
  381. # SE_LOSS ENCODING
  382. enc = F.max_pool2d(ladder_out_list[0], kernel_size=ladder_out_list[0].size()[2:])
  383. enc = torch.squeeze(enc, -1)
  384. enc = torch.squeeze(enc, -1)
  385. se = self.se_layer(enc)
  386. preds.append(se)
  387. # UP SAMPLING THE TOP LAYER FOR PREDICTION
  388. preds[0] = F.interpolate(preds[0], image_size, mode="bilinear", align_corners=True)
  389. # AUXILARY HEAD OUTPUT (ONLY RELEVANT FOR LOSS CALCULATION) - USE self.auxilary_head_outputs=FALSE FOR INFERENCE
  390. if self.auxilary_head_outputs or self.training:
  391. aux_out = self.aux_head(backbone_features_list[2])
  392. aux_out = F.interpolate(aux_out, image_size, mode="bilinear", align_corners=True)
  393. preds.append(aux_out)
  394. return tuple(preds)
  395. else:
  396. return preds[0]
  397. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  398. """
  399. initialize_optimizer_for_model_param_groups - Initializes the weights of the optimizer
  400. Initializes the Backbone, the Output and the Auxilary Head
  401. differently
  402. :param optimizer_cls: The nn.optim (optimizer class) to initialize
  403. :param lr: lr to set for the optimizer
  404. :param training_params:
  405. :return: list of dictionaries with named params and optimizer attributes
  406. """
  407. # OPTIMIZER PARAMETER GROUPS
  408. params_list = []
  409. # OPTIMIZE BACKBONE USING DIFFERENT LR
  410. params_list.append({"named_params": self.backbone.named_parameters(), "lr": lr})
  411. # OPTIMIZE MAIN SHELFNET ARCHITECTURE LAYERS
  412. params_list.append(
  413. {
  414. "named_params": list(self.ladder.named_parameters())
  415. + list(self.decoder.named_parameters())
  416. + list(self.se_layer.named_parameters())
  417. + list(self.conv_out_list.named_parameters())
  418. + list(self.final.named_parameters())
  419. + list(self.aux_head.named_parameters()),
  420. "lr": lr * 10,
  421. }
  422. )
  423. return params_list
  424. class ShelfNetLW(ShelfNetBase):
  425. """
  426. ShelfNetLW - Light-Weight Implementation for ShelfNet
  427. """
  428. def __init__(self, *args, **kwargs):
  429. super().__init__(*args, **kwargs)
  430. self.net_output_list = nn.ModuleList()
  431. self.ladder = LadderBlockLW(planes=self.planes, layers=self.layers)
  432. self.decoder = DecoderLW(planes=self.planes, layers=self.layers)
  433. def forward(self, x):
  434. H, W = x.size()[2:]
  435. # SHELFNET LW ARCHITECTURE USES ONLY LAST 3 PARTIAL OUTPUTs OF THE BACKBONE'S 4 OUTPUT LAYERS
  436. backbone_features_tuple = self.backbone(x)[1:]
  437. if isinstance(self, ShelfNet18_LW):
  438. # FOR SHELFNET18 USE 1x1 CONVS AFTER THE BACKBONE'S FORWARD PASS TO MANIPULATE THE CHANNELS FOR THE DECODER
  439. conv_bn_relu_results_list = []
  440. for feature, conv_bn_relu in zip(backbone_features_tuple, self.conv_out_list):
  441. out = conv_bn_relu(feature)
  442. conv_bn_relu_results_list.append(out)
  443. else:
  444. # FOR SHELFNET34 THE CHANNELS ARE ALREADY ALIGNED
  445. conv_bn_relu_results_list = list(backbone_features_tuple)
  446. decoder_out_list = self.decoder(conv_bn_relu_results_list)
  447. ladder_out_list = self.ladder(decoder_out_list)
  448. # GET THE LAST ELEMENTS OF THE LADDER_BLOCK BASED ON THE AMOUNT OF SHELVES IN THE ARCHITECTURE AND REVERSE LIST
  449. feat_cp_list = list(reversed(ladder_out_list[(-1 * self.layers) :]))
  450. feat_out = self.net_output_list[0](feat_cp_list[0])
  451. feat_out = F.interpolate(feat_out, (H, W), mode="bilinear", align_corners=True)
  452. if self.auxilary_head_outputs or self.training:
  453. features_out_list = [feat_out]
  454. for conv_output_layer, feat_cp in zip(self.net_output_list[1:], feat_cp_list[1:]):
  455. feat_out_res = conv_output_layer(feat_cp)
  456. feat_out_res = F.interpolate(feat_out_res, (H, W), mode="bilinear", align_corners=True)
  457. features_out_list.append(feat_out_res)
  458. return tuple(features_out_list)
  459. else:
  460. # THIS DOES NOT CALCULATE THE AUXILARY HEADS THAT ARE CRITICAL FOR THE LOSS (USED MAINLY FOR INFERENCE)
  461. return feat_out
  462. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  463. """
  464. initialize_optimizer_for_model_param_groups - Initializes the optimizer group params, with 10x learning rate
  465. for all but the backbone
  466. :param lr: lr to set for the backbone
  467. :param training_params:
  468. :return: list of dictionaries with named params and optimizer attributes
  469. """
  470. # OPTIMIZER PARAMETER GROUPS
  471. params_list = []
  472. # OPTIMIZE BACKBONE USING DIFFERENT LR
  473. params_list.append({"named_params": self.backbone.named_parameters(), "lr": lr})
  474. # OPTIMIZE MAIN SHELFNET ARCHITECTURE LAYERS
  475. params_list.append(
  476. {
  477. "named_params": list(self.ladder.named_parameters()) + list(self.decoder.named_parameters()) + list(self.conv_out_list.named_parameters()),
  478. "lr": lr * 10,
  479. }
  480. )
  481. return params_list
  482. class ShelfNet18_LW(ShelfNetLW):
  483. def __init__(self, *args, **kwargs):
  484. super().__init__(backbone=ShelfResNetBackBone18, planes=64, layers=3, *args, **kwargs)
  485. # INITIALIZE THE net_output_list AND THE conv_out LIST
  486. out_planes = self.planes
  487. for i in range(self.layers):
  488. # THE MID CHANNELS NUMBER OF THE NET OUTPUT BLOCK
  489. mid_channels_num = self.planes if i == 0 else self.net_output_mid_channels_num
  490. self.net_output_list.append(NetOutput(out_planes, mid_channels_num, self.num_classes))
  491. self.conv_out_list.append(ConvBNReLU(out_planes * 2, out_planes, ks=1, stride=1, padding=0))
  492. out_planes *= 2
  493. class ShelfNet34_LW(ShelfNetLW):
  494. def __init__(self, *args, **kwargs):
  495. super().__init__(backbone=ShelfResNetBackBone34, planes=128, layers=3, *args, **kwargs)
  496. # INITIALIZE THE net_output_list
  497. net_out_planes = self.planes
  498. for i in range(self.layers):
  499. # IF IT'S THE FIRST LAYER THAN THE MID-CHANNELS NUM IS ACTUALLY self.planes
  500. mid_channels_num = self.planes if i == 0 else self.net_output_mid_channels_num
  501. self.net_output_list.append(NetOutput(net_out_planes, mid_channels_num, self.num_classes))
  502. net_out_planes *= 2
  503. class ShelfNet503343(ShelfNetHW):
  504. def __init__(self, *args, **kwargs):
  505. super().__init__(backbone=ShelfResNetBackBone503343, planes=256, layers=4, *args, **kwargs)
  506. class ShelfNet50(ShelfNetHW):
  507. def __init__(self, *args, **kwargs):
  508. super().__init__(backbone=ShelfResNetBackBone50, planes=256, layers=4, *args, **kwargs)
  509. class ShelfNet101(ShelfNetHW):
  510. def __init__(self, *args, **kwargs):
  511. super().__init__(backbone=ShelfResNetBackBone101, planes=256, layers=4, *args, **kwargs)
Discard
Tip!

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