-
Notifications
You must be signed in to change notification settings - Fork 55
/
models.py
executable file
·1257 lines (1089 loc) · 52.7 KB
/
models.py
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
import numpy as np
from torchvision.transforms.functional import to_pil_image, to_tensor
from utils.google_utils import *
from utils.parse_config import *
from utils.utils import *
from utils.layers import *
ONNX_EXPORT = False
def create_modules(module_defs, img_size, arc):
# 通过module_defs进行构建模型
hyperparams = module_defs.pop(0)
output_filters = [int(hyperparams['channels'])]
module_list = nn.ModuleList()
routs = [] # 存储了所有的层,在route、shortcut会使用到。
yolo_index = -1
for i, mdef in enumerate(module_defs):
modules = nn.Sequential()
module_i=i
'''
通过type字样不同的类型,来进行模型构建
'''
# print(i, mdef['type'])
if mdef['type'] == 'convolutional':
bn = int(mdef['batch_normalize'])
filters = int(mdef['filters'])
size = int(mdef['size'])
stride = int(mdef['stride']) if 'stride' in mdef else (int(
mdef['stride_y']), int(mdef['stride_x']))
pad = (size - 1) // 2 if int(mdef['pad']) else 0
modules.add_module(
'Conv2d',
nn.Conv2d(
in_channels=output_filters[-1],
out_channels=filters,
kernel_size=size,
stride=stride,
padding=pad,
groups=int(mdef['groups']) if 'groups' in mdef else 1,
bias=not bn))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
elif mdef['activation'] == 'swish':
modules.add_module('activation', Swish())
# 在此处可以添加新的激活函数
elif mdef['type'] == 'dilatedconv':
bn = int(mdef['batch_normalize'])
filters = int(mdef['filters'])
size = int(mdef['size'])
stride = int(mdef['stride']) if 'stride' in mdef else (int(
mdef['stride_y']), int(mdef['stride_x']))
pad = (size + 1) // 2 if int(mdef['pad']) else 0
modules.add_module(
'Conv2d',
nn.Conv2d(
in_channels=output_filters[-1],
out_channels=filters,
kernel_size=size,
stride=stride,
padding=pad,
groups=int(mdef['groups']) if 'groups' in mdef else 1,
dilation=int(mdef['dilation']),
bias=not bn))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
elif mdef['activation'] == 'swish':
modules.add_module('activation', Swish())
# 在此处可以添加新的激活函数
elif mdef['type'] == 'dwconv':
# 只替换3*3卷积即可,size=3,stride=1,padding=1
filters = int(mdef['filters'])
bn = int(mdef['batch_normalize'])
modules.add_module(
'dwconv3x3',
DWConv(in_plane=output_filters[-1], out_plane=filters))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
elif mdef['type'] == 'acconv':
# ACNet只替换3*3卷积即可,size=3,stride=1,padding=1
# def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', deploy=False):
filters = int(mdef['filters'])
bn = int(mdef['batch_normalize'])
# size = int(mdef['size'])
# pad = (size + 1) // 2 if int(mdef['pad']) else 0
modules.add_module(
'acconv',
Conv2dBNReLU(in_channels=output_filters[-1],
out_channels=filters,
kernel_size=3,
stride=1,
padding=1))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
#新增Res2net模块yangchao
elif mdef["type"] == "res2net":
filters = int(mdef["planes"]) * 2
res2net = Bottle2neck(inplanes=int(mdef["inplanes"]),
planes=int(mdef["planes"]),
stride=1,
downsample=None,
baseWidth=26,
scale=4,
stype='normal')
modules.add_module(f"res2net_{module_i}", res2net)
#新增triangle模块yangchao
elif mdef["type"] == "triangle":
triangle = Bottle2neck(inplanes=int(mdef["inplanes"]),
planes=int(mdef["planes"]),
stride=1,
downsample=None,
baseWidth=16,
scale=4,
stype='normal')
modules.add_module(f"triangle_{module_i}", triangle)
elif mdef['type'] == "skconv":
skconv = SKConv(int(output_filters[-1]), M=int(mdef["branch"]))
modules.add_module("skconv", skconv)
elif mdef['type'] == 'gcblock':
gcblock = ContextBlock(inplanes=output_filters[-1],
ratio=int(mdef['ratio']))
modules.add_module('gcblock', gcblock)
elif mdef['type'] == 'maxpool':
# 最大池化操作
size = int(mdef['size'])
stride = int(mdef['stride'])
maxpool = nn.MaxPool2d(kernel_size=size,
stride=stride,
padding=int((size - 1) // 2))
if size == 2 and stride == 1: # yolov3-tiny
modules.add_module('ZeroPad2d', nn.ZeroPad2d((0, 1, 0, 1)))
modules.add_module('MaxPool2d', maxpool)
else:
modules = maxpool
elif mdef['type'] == 'maxpoolone':
size = int(mdef['size'])
stride = int(mdef['stride'])
maxpoolone = nn.MaxPool2d(kernel_size=(size, 1),
stride=stride,
padding=(int((size - 1) // 2), 0))
modules.add_module('maxpoolone', maxpoolone)
elif mdef['type'] == 'onemaxpool':
size = int(mdef['size'])
stride = int(mdef['stride'])
onemaxpool = nn.MaxPool2d(kernel_size=(1, size),
stride=stride,
padding=(0, int((size - 1) // 2)))
modules.add_module('onemaxpool', onemaxpool)
elif mdef['type'] == 'corner':
# corner pool
size = int(mdef['size'])
stride = int(mdef['stride'])
maxpool_1 = nn.MaxPool2d(kernel_size=(size, 1),
stride=stride,
padding=(int((size - 1) // 2), 0))
maxpool_2 = nn.MaxPool2d(kernel_size=(1, size),
stride=stride,
padding=(0, int((size - 1) // 2)))
if size == 2 and stride == 1: # yolov3-tiny
# 这里不考虑yolov3 tiny
modules.add_module('ZeroPad2d', nn.ZeroPad2d((0, 1, 0, 1)))
modules.add_module('MaxPool2d', maxpool)
else:
modules.add_module('corner_maxpool_1', maxpool_1)
modules.add_module('corner_maxpool_2', maxpool_2)
elif mdef['type'] == 'upsample':
# 通过近邻插值完成上采样
modules = nn.Upsample(scale_factor=int(mdef['stride']),
mode='nearest')
# modules = UpsampleDeterministic(upscale=int(mdef['stride']))
elif mdef['type'] == 'rfb':
modules = BasicRFB(output_filters[-1],
out_planes=int(mdef['filters']),
stride=int(mdef['stride']),
scale=float(mdef['scale']))
elif mdef['type'] == 'rfbs':
modules = BasicRFB_small(output_filters[-1],
out_planes=int(mdef['filters']),
stride=int(mdef['stride']),
scale=float(mdef['scale']))
elif mdef['type'] == 'se':
modules.add_module(
'se_module',
SELayer(output_filters[-1], reduction=int(mdef['reduction'])))
elif mdef['type'] == 'cbam':
ca = ChannelAttention(output_filters[-1], ratio=int(mdef['ratio']))
sa = SpatialAttention(kernel_size=int(mdef['kernelsize']))
modules.add_module('channel_attention', ca)
modules.add_module('spatial attention', sa)
elif mdef['type'] == 'channelAttention':
ca = ChannelAttention(output_filters[-1], ratio=int(mdef['ratio']))
modules.add_module('channel_attention', ca)
elif mdef['type'] == 'spatialAttention':
sa = SpatialAttention(kernel_size=int(mdef['kernelsize']))
modules.add_module('channel_attention', sa)
elif mdef['type'] == 'ppm':
ppm = PSPModule(output_filters[-1], int(mdef['out']))
modules.add_module('Pyramid Pooling Module', ppm)
elif mdef['type'] == 'aspp':
froms = [int(x) for x in mdef['from'].split(',')]
out = int(mdef['out'])
aspp0 = ASPP(output_filters[-1], out, rate=froms[0])
aspp1 = ASPP(output_filters[-1], out, rate=froms[1])
aspp2 = ASPP(output_filters[-1], out, rate=froms[2])
aspp3 = ASPP(output_filters[-1], out, rate=froms[3])
gavgpool = nn.Sequential(
nn.AdaptiveAvgPool2d((1, 1)),
nn.Conv2d(output_filters[-1], out, 1, stride=1, bias=False),
nn.BatchNorm2d(out), nn.ReLU())
modules.add_module('ASPP0', aspp0)
modules.add_module('ASPP1', aspp1)
modules.add_module('ASPP2', aspp2)
modules.add_module('ASPP3', aspp3)
modules.add_module('ASPP_avgpool', gavgpool)
filters = out * 6
elif mdef['type'] == 'route':
# nn.Sequential() placeholder for 'route' layer
layers = [int(x) for x in mdef['layers'].split(',')]
filters = sum(
[output_filters[i + 1 if i > 0 else i] for i in layers])
# extend表示添加一系列对象
routs.extend([l if l > 0 else l + i for l in layers])
elif mdef['type'] == 'fuse':
filters = output_filters[-1] * 2
elif mdef['type'] == 'shortcut':
# nn.Sequential() placeholder for 'shortcut' layer
# print("shortcut"*3, filters)
filters = output_filters[int(mdef['from'])]
layer = int(mdef['from'])
routs.extend([i + layer if layer < 0 else layer])
# modules.add_module(
# 'stride2conv',
# nn.Conv2d(filters,
# filters,
# kernel_size=1,
# stride=2,
# bias=False))
elif mdef['type'] == 'yolo':
yolo_index += 1
mask = [int(x) for x in mdef['mask'].split(',')] # anchor mask
modules = YOLOLayer(
anchors=mdef['anchors'][mask], # anchor list
nc=int(mdef['classes']), # number of classes
img_size=img_size, # (416, 416)
yolo_index=yolo_index, # 0, 1 or 2
arc=arc) # yolo architecture
# 这是在focal loss文章中提到的为卷积层添加bias
# 主要用于解决样本不平衡问题
# (论文地址 https://arxiv.org/pdf/1708.02002.pdf section 3.3)
# pw 代表pretrained weights
try:
if arc == 'defaultpw' or arc == 'Fdefaultpw':
# default with positive weights
b = [-5.0, -5.0] # obj, cls
elif arc == 'default':
# default no pw (40 cls, 80 obj)
b = [-5.0, -5.0]
elif arc == 'uBCE':
# unified BCE (80 classes)
b = [0, -9.0]
elif arc == 'uCE':
# unified CE (1 background + 80 classes)
b = [10, -0.1]
elif arc == 'Fdefault':
# Focal default no pw (28 cls, 21 obj, no pw)
b = [-2.1, -1.8]
elif arc == 'uFBCE' or arc == 'uFBCEpw':
# unified FocalBCE (5120 obj, 80 classes)
b = [0, -6.5]
elif arc == 'uFCE':
# unified FocalCE (64 cls, 1 background + 80 classes)
b = [7.7, -1.1]
# len(mask) = 3
bias = module_list[-1][0].bias.view(len(mask), -1)
# 255 to 3x85
bias[:, 4] += b[0] - bias[:, 4].mean() # obj
bias[:, 5:] += b[1] - bias[:, 5:].mean() # cls
# list of tensors [3x85, 3x85, 3x85]
module_list[-1][0].bias = torch.nn.Parameter(bias.view(-1))
except:
print('WARNING: smart bias initialization failure.')
else:
print('Warning: Unrecognized Layer Type: ' + mdef['type'])
# 将module内容保存在module_list中。
module_list.append(modules)
# 保存所有的filter个数
output_filters.append(filters)
return module_list, routs
class YOLOLayer(nn.Module):
def __init__(self, anchors, nc, img_size, yolo_index, arc):
super(YOLOLayer, self).__init__()
self.anchors = torch.Tensor(anchors)
self.na = len(anchors) # 该YOLOLayer分配给每个grid的anchor的个数
self.nc = nc # 类别个数
self.no = nc + 5 # 每个格子对应输出的维度 class + 5 中5代表x,y,w,h,conf
self.nx = 0 # 初始化x方向上的格子数量
self.ny = 0 # 初始化y方向上的格子数量
self.arc = arc
if ONNX_EXPORT: # grids must be computed in __init__
stride = [32, 16, 8][yolo_index] # stride of this layer
nx = int(img_size[1] / stride) # number x grid points
ny = int(img_size[0] / stride) # number y grid points
create_grids(self, img_size, (nx, ny))
def forward(self, p, img_size, var=None):
'''
onnx代表开放式神经网络交换
pytorch中的模型都可以导出或转换为标准ONNX格式
在模型采用ONNX格式后,即可在各种平台和设备上运行
在这里ONNX代表规范化的推理过程
'''
if ONNX_EXPORT:
bs = 1 # batch size
else:
bs, _, ny, nx = p.shape # bs, 255, 13, 13
if (self.nx, self.ny) != (nx, ny):
create_grids(self, img_size, (nx, ny), p.device, p.dtype)
# p.view(bs, 255, 13, 13) -- > (bs, 3, 13, 13, 85)
# (bs, anchors, grid, grid, xywhc+classes)
p = p.view(bs, self.na, self.no, self.ny,
self.nx).permute(0, 1, 3, 4, 2).contiguous()
if self.training:
return p
elif ONNX_EXPORT:
m = self.na * self.nx * self.ny
grid_xy = self.grid_xy.repeat((1, self.na, 1, 1, 1)).view(m, 2)
anchor_wh = self.anchor_wh.repeat(
(1, 1, self.nx, self.ny, 1)).view(m, 2) / self.ng
p = p.view(m, self.no)
xy = torch.sigmoid(p[:, 0:2]) + grid_xy # x, y
wh = torch.exp(p[:, 2:4]) * anchor_wh # width, height
p_cls = torch.sigmoid(p[:, 5:self.no]) * torch.sigmoid(
p[:, 4:5]) # conf
return p_cls, xy / self.ng, wh
else: # 测试推理过程
# s = 1.5 # scale_xy (pxy = pxy * s - (s - 1) / 2)
# (bs, anchors, grid, grid, xywhc+classes)
io = p.clone() # inference output
io[..., :2] = torch.sigmoid(io[..., :2]) + self.grid_xy # xy进行sigmoid归一化
io[..., 2:4] = torch.exp(
io[..., 2:4]) * self.anchor_wh # wh yolo method # wh
# io[..., 2:4] = ((torch.sigmoid(io[..., 2:4]) * 2) ** 3) * self.anchor_wh # wh power method
io[..., :4] *= self.stride # obj confidence
if 'default' in self.arc: # seperate obj and cls
torch.sigmoid_(io[..., 4])
elif 'BCE' in self.arc: # unified BCE (80 classes)
torch.sigmoid_(io[..., 5:])
io[..., 4] = 1
elif 'CE' in self.arc: # unified CE (1 background + 80 classes)
io[..., 4:] = F.softmax(io[..., 4:], dim=4)
io[..., 4] = 1
if self.nc == 1:
io[..., 5] = 1
# single-class model https://github.com/ultralytics/yolov3/issues/235
# reshape from [1, 3, 13, 13, 85] to [1, 507, 85]
return io.view(bs, -1, self.no), p
class Darknet(nn.Module):
# YOLOv3 object detection model
def __init__(self, cfg, img_size=(416, 416), arc='default'):
super(Darknet, self).__init__()
self.module_defs = parse_model_cfg(cfg)
self.module_list, self.routs = create_modules(self.module_defs,
img_size, arc)
self.yolo_layers = get_yolo_layers(self)
# Darknet Header https://github.com/AlexeyAB/darknet/issues/2914#issuecomment-496675346
self.version = np.array([0, 2, 5], dtype=np.int32)
# (int32) version info: major, minor, revision
self.seen = np.array([0], dtype=np.int64)
# (int64) number of images seen during training
self.show = True
def forward(self, x, var=None):
# process x
img_size = x.shape[-2:]
layer_outputs = []
output = []
for i, (mdef,
module) in enumerate(zip(self.module_defs, self.module_list)):
mtype = mdef['type']
# if self.show:
# print("第%3d层: %13s |" % (i, mtype), "shape:", x.shape)
if mtype in [
'convolutional', 'upsample', 'maxpool', 'se',
'dilatedconv', 'ppm', 'acconv', 'maxpoolone', 'onemaxpool',
'rfb', 'dwconv', 'res2net', 'triangle', 'skconv',
'channelAttention', 'spatialAttention', 'gcblock', 'rfbs'
]:
x = module(x)
elif mtype == 'route':
layers = [int(x) for x in mdef['layers'].split(',')]
if len(layers) == 1:
x = layer_outputs[layers[0]]
else:
try:
x = torch.cat([layer_outputs[i] for i in layers], 1)
except: # apply stride 2 for darknet reorg layer
layer_outputs[layers[1]] = F.interpolate(
layer_outputs[layers[1]], scale_factor=[0.5, 0.5])
x = torch.cat([layer_outputs[i] for i in layers], 1)
elif mtype == 'shortcut':
# print(x.shape, layer_outputs[int(mdef['from'])].shape)
x = x + layer_outputs[int(mdef['from'])]
elif mtype == 'corner':
x1 = module[0](x)
# print("after x1:", x1.shape)
x2 = module[1](x)
# print("after x2:",x2.shape)
x = x1 + x2
elif mtype == 'aspp':
x1 = module[0](x)
x2 = module[1](x)
x3 = module[2](x)
x4 = module[3](x)
x5 = module[4](x)
# print("x5",x5.shape)
x5 = F.interpolate(x5,
size=x4.size()[2:],
mode='bilinear',
align_corners=True)
# print("x5,",x5.shape)
x = torch.cat((x, x1, x2, x3, x4, x5), dim=1)
# print(x.shape)
elif mtype == 'cbam':
ca = module[0]
sa = module[1]
x = ca(x) * x
x = sa(x) * x
elif mtype == 'yolo':
output.append(module(x, img_size))
layer_outputs.append(x if i in self.routs else [])
# print(" | out:", x.shape)
self.show = False
if self.training:
return output
elif ONNX_EXPORT:
x = [torch.cat(x, 0) for x in zip(*output)]
return x[0], torch.cat(x[1:3], 1) # scores, boxes: 3780x80, 3780x4
else:
io, p = list(zip(*output)) # inference output, training output
return torch.cat(io, 1), p
def fuse(self):
# Fuse Conv2d + BatchNorm2d layers throughout model
fused_list = nn.ModuleList()
for a in list(self.children())[0]:
if isinstance(a, nn.Sequential):
for i, b in enumerate(a):
if isinstance(b, nn.modules.batchnorm.BatchNorm2d):
# fuse this bn layer with the previous conv2d layer
conv = a[i - 1]
fused = torch_utils.fuse_conv_and_bn(conv, b)
a = nn.Sequential(fused, *list(a.children())[i + 1:])
break
fused_list.append(a)
self.module_list = fused_list
# model_info(self) # yolov3-spp reduced from 225 to 152 layers
def create_modules_darknext(module_defs, img_size, arc):
# 通过module_defs进行构建模型
hyperparams = module_defs.pop(0)
output_filters = [int(hyperparams['channels'])]
module_list = nn.ModuleList()
multi_gray_module_list = nn.ModuleList()
routs = [] # 存储了所有的层,在route、shortcut会使用到。
yolo_index = -1
fuse_flag = True
for i, mdef in enumerate(module_defs):
modules = nn.Sequential()
multi_gray_modules = nn.Sequential()
'''
通过type字样不同的类型,来进行模型构建
'''
module_i = i
if mdef['type'] == 'convolutional':
bn = int(mdef['batch_normalize'])
filters = int(mdef['filters'])
size = int(mdef['size'])
stride = int(mdef['stride']) if 'stride' in mdef else (int(
mdef['stride_y']), int(mdef['stride_x']))
pad = (size - 1) // 2 if int(mdef['pad']) else 0
modules.add_module(
'Conv2d',
nn.Conv2d(
in_channels=output_filters[-1],
out_channels=filters,
kernel_size=size,
stride=stride,
padding=pad,
groups=int(mdef['groups']) if 'groups' in mdef else 1,
bias=not bn))
if fuse_flag:
multi_gray_modules.add_module(
'multi_gray_Conv2d',
nn.Conv2d(
in_channels=output_filters[-1],
out_channels=filters,
kernel_size=size,
stride=stride,
padding=pad,
groups=int(mdef['groups']) if 'groups' in mdef else 1,
bias=not bn))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if fuse_flag:
multi_gray_modules.add_module(
'multi_gray_BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
if fuse_flag:
multi_gray_modules.add_module(
'multi_gray_leaky_relu', nn.LeakyReLU(0.1,
inplace=True))
elif mdef['activation'] == 'swish':
modules.add_module('activation', Swish())
if fuse_flag:
multi_gray_modules.add_module('multi_gray_swish', Swish())
# 在此处可以添加新的激活函数
elif mdef['type'] == 'dilatedconv':
bn = int(mdef['batch_normalize'])
filters = int(mdef['filters'])
size = int(mdef['size'])
stride = int(mdef['stride']) if 'stride' in mdef else (int(
mdef['stride_y']), int(mdef['stride_x']))
pad = (size + 1) // 2 if int(mdef['pad']) else 0
modules.add_module(
'Conv2d',
nn.Conv2d(
in_channels=output_filters[-1],
out_channels=filters,
kernel_size=size,
stride=stride,
padding=pad,
groups=int(mdef['groups']) if 'groups' in mdef else 1,
dilation=int(mdef['dilation']),
bias=not bn))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
elif mdef['activation'] == 'swish':
modules.add_module('activation', Swish())
# 在此处可以添加新的激活函数
elif mdef['type'] == 'dwconv':
# 只替换3*3卷积即可,size=3,stride=1,padding=1
filters = int(mdef['filters'])
bn = int(mdef['batch_normalize'])
modules.add_module(
'dwconv3x3',
DWConv(in_plane=output_filters[-1], out_plane=filters))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
elif mdef['type'] == 'acconv':
# ACNet只替换3*3卷积即可,size=3,stride=1,padding=1
# def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', deploy=False):
filters = int(mdef['filters'])
bn = int(mdef['batch_normalize'])
# size = int(mdef['size'])
# pad = (size + 1) // 2 if int(mdef['pad']) else 0
modules.add_module(
'acconv',
Conv2dBNReLU(in_channels=output_filters[-1],
out_channels=filters,
kernel_size=3,
stride=1,
padding=1))
if bn:
modules.add_module('BatchNorm2d',
nn.BatchNorm2d(filters, momentum=0.1))
if mdef['activation'] == 'leaky': # TODO: activation study https://github.com/ultralytics/yolov3/issues/441
modules.add_module('activation', nn.LeakyReLU(0.1,
inplace=True))
#新增Res2net模块yangchao
elif mdef["type"] == "res2net":
filters = int(mdef["planes"]) * 2
res2net = Bottle2neck(inplanes=int(mdef["inplanes"]),
planes=int(mdef["planes"]),
stride=1,
downsample=None,
baseWidth=26,
scale=4,
stype='normal')
modules.add_module(f"res2net_{module_i}", res2net)
#新增triangle模块yangchao
elif mdef["type"] == "triangle":
triangle = Bottle2neck(inplanes=int(mdef["inplanes"]),
planes=int(mdef["planes"]),
stride=1,
downsample=None,
baseWidth=16,
scale=4,
stype='normal')
modules.add_module(f"triangle_{module_i}", triangle)
elif mdef['type'] == "skconv":
skconv = SKConv(int(output_filters[-1]), M=int(mdef["branch"]))
modules.add_module("skconv", skconv)
elif mdef['type'] == 'gcblock':
gcblock = ContextBlock(inplanes=output_filters[-1],
ratio=int(mdef['ratio']))
modules.add_module('gcblock', gcblock)
elif mdef['type'] == 'maxpool':
# 最大池化操作
size = int(mdef['size'])
stride = int(mdef['stride'])
maxpool = nn.MaxPool2d(kernel_size=size,
stride=stride,
padding=int((size - 1) // 2))
if size == 2 and stride == 1: # yolov3-tiny
modules.add_module('ZeroPad2d', nn.ZeroPad2d((0, 1, 0, 1)))
modules.add_module('MaxPool2d', maxpool)
else:
modules = maxpool
if fuse_flag:
if size == 2 and stride == 1: # yolov3-tiny
multi_gray_modules.add_module('ZeroPad2d',
nn.ZeroPad2d((0, 1, 0, 1)))
multi_gray_modules.add_module(
'MaxPool2d',
nn.MaxPool2d(kernel_size=size,
stride=stride,
padding=int((size - 1) // 2)))
elif mdef['type'] == 'maxpoolone':
size = int(mdef['size'])
stride = int(mdef['stride'])
maxpoolone = nn.MaxPool2d(kernel_size=(size, 1),
stride=stride,
padding=(int((size - 1) // 2), 0))
modules.add_module('maxpoolone', maxpoolone)
elif mdef['type'] == 'onemaxpool':
size = int(mdef['size'])
stride = int(mdef['stride'])
onemaxpool = nn.MaxPool2d(kernel_size=(1, size),
stride=stride,
padding=(0, int((size - 1) // 2)))
modules.add_module('onemaxpool', onemaxpool)
elif mdef['type'] == 'corner':
# corner pool
size = int(mdef['size'])
stride = int(mdef['stride'])
maxpool_1 = nn.MaxPool2d(kernel_size=(size, 1),
stride=stride,
padding=(int((size - 1) // 2), 0))
maxpool_2 = nn.MaxPool2d(kernel_size=(1, size),
stride=stride,
padding=(0, int((size - 1) // 2)))
if size == 2 and stride == 1: # yolov3-tiny
# 这里不考虑yolov3 tiny
modules.add_module('ZeroPad2d', nn.ZeroPad2d((0, 1, 0, 1)))
modules.add_module('MaxPool2d', maxpool)
else:
modules.add_module('corner_maxpool_1', maxpool_1)
modules.add_module('corner_maxpool_2', maxpool_2)
elif mdef['type'] == 'upsample':
# 通过近邻插值完成上采样
modules = nn.Upsample(scale_factor=int(mdef['stride']),
mode='nearest')
# modules = UpsampleDeterministic(int(mdef['stride']))
elif mdef['type'] == 'rfb':
modules = BasicRFB(output_filters[-1],
out_planes=int(mdef['filters']),
stride=int(mdef['stride']),
scale=float(mdef['scale']))
elif mdef['type'] == 'rfbs':
modules = BasicRFB_small(output_filters[-1],
out_planes=int(mdef['filters']),
stride=int(mdef['stride']),
scale=float(mdef['scale']))
elif mdef['type'] == 'se':
modules.add_module(
'se_module',
SELayer(output_filters[-1], reduction=int(mdef['reduction'])))
elif mdef['type'] == 'cbam':
ca = ChannelAttention(output_filters[-1], ratio=int(mdef['ratio']))
sa = SpatialAttention(kernel_size=int(mdef['kernelsize']))
modules.add_module('channel_attention', ca)
modules.add_module('spatial attention', sa)
elif mdef['type'] == 'channelAttention':
ca = ChannelAttention(output_filters[-1], ratio=int(mdef['ratio']))
modules.add_module('channel_attention', ca)
elif mdef['type'] == 'spatialAttention':
sa = SpatialAttention(kernel_size=int(mdef['kernelsize']))
modules.add_module('channel_attention', sa)
elif mdef['type'] == 'ppm':
ppm = PSPModule(output_filters[-1], int(mdef['out']))
modules.add_module('Pyramid Pooling Module', ppm)
elif mdef['type'] == 'aspp':
froms = [int(x) for x in mdef['from'].split(',')]
out = int(mdef['out'])
aspp0 = ASPP(output_filters[-1], out, rate=froms[0])
aspp1 = ASPP(output_filters[-1], out, rate=froms[1])
aspp2 = ASPP(output_filters[-1], out, rate=froms[2])
aspp3 = ASPP(output_filters[-1], out, rate=froms[3])
gavgpool = nn.Sequential(
nn.AdaptiveAvgPool2d((1, 1)),
nn.Conv2d(output_filters[-1], out, 1, stride=1, bias=False),
nn.BatchNorm2d(out), nn.ReLU())
modules.add_module('ASPP0', aspp0)
modules.add_module('ASPP1', aspp1)
modules.add_module('ASPP2', aspp2)
modules.add_module('ASPP3', aspp3)
modules.add_module('ASPP_avgpool', gavgpool)
filters = out * 6
elif mdef['type'] == 'route':
# nn.Sequential() placeholder for 'route' layer
layers = [int(x) for x in mdef['layers'].split(',')]
filters = sum(
[output_filters[i + 1 if i > 0 else i] for i in layers])
# extend表示添加一系列对象
routs.extend([l if l > 0 else l + i for l in layers])
elif mdef['type'] == 'fuse':
filters = output_filters[-1] * 2
fuse_flag = False
elif mdef['type'] == 'shortcut':
# nn.Sequential() placeholder for 'shortcut' layer
filters = output_filters[int(mdef['from'])]
layer = int(mdef['from'])
routs.extend([i + layer if layer < 0 else layer])
elif mdef['type'] == 'yolo':
yolo_index += 1
mask = [int(x) for x in mdef['mask'].split(',')] # anchor mask
modules = YOLOLayer(
anchors=mdef['anchors'][mask], # anchor list
nc=int(mdef['classes']), # number of classes
img_size=img_size, # (416, 416)
yolo_index=yolo_index, # 0, 1 or 2
arc=arc) # yolo architecture
# 这是在focal loss文章中提到的为卷积层添加bias
# 主要用于解决样本不平衡问题
# (论文地址 https://arxiv.org/pdf/1708.02002.pdf section 3.3)
# pw 代表pretrained weights
try:
if arc == 'defaultpw' or arc == 'Fdefaultpw':
# default with positive weights
b = [-5.0, -5.0] # obj, cls
elif arc == 'default':
# default no pw (40 cls, 80 obj)
b = [-5.0, -5.0]
elif arc == 'uBCE':
# unified BCE (80 classes)
b = [0, -9.0]
elif arc == 'uCE':
# unified CE (1 background + 80 classes)
b = [10, -0.1]
elif arc == 'Fdefault':
# Focal default no pw (28 cls, 21 obj, no pw)
b = [-2.1, -1.8]
elif arc == 'uFBCE' or arc == 'uFBCEpw':
# unified FocalBCE (5120 obj, 80 classes)
b = [0, -6.5]
elif arc == 'uFCE':
# unified FocalCE (64 cls, 1 background + 80 classes)
b = [7.7, -1.1]
# len(mask) = 3
bias = module_list[-1][0].bias.view(len(mask), -1)
# 255 to 3x85
bias[:, 4] += b[0] - bias[:, 4].mean() # obj
bias[:, 5:] += b[1] - bias[:, 5:].mean() # cls
# list of tensors [3x85, 3x85, 3x85]
module_list[-1][0].bias = torch.nn.Parameter(bias.view(-1))
except:
print('WARNING: smart bias initialization failure.')
else:
print('Warning: Unrecognized Layer Type: ' + mdef['type'])
# 将module内容保存在module_list中。
module_list.append(modules)
multi_gray_module_list.append(multi_gray_modules)
# 保存所有的filter个数
output_filters.append(filters)
return module_list, multi_gray_module_list, routs
class DarkneXt(nn.Module):
# YOLOv3 object detection model
def __init__(self, cfg, img_size=(416, 416), arc='default'):
super(DarkneXt, self).__init__()
self.module_defs = parse_model_cfg(cfg)
self.module_list, self.multi_gray_module_list, self.routs = create_modules_darknext(
self.module_defs, img_size, arc)
self.yolo_layers = get_yolo_layers(self)
# Darknet Header https://github.com/AlexeyAB/darknet/issues/2914#issuecomment-496675346
self.version = np.array([0, 2, 5], dtype=np.int32)
# (int32) version info: major, minor, revision
self.seen = np.array([0], dtype=np.int64)
# (int64) number of images seen during training
self.fuse = True
def forward(self, x, var=None):
bs, c, h, w = x.shape
# print("Batch size:", bs)
# x_multi_gray =
tmp_x = x.clone()
tmp_x = tmp_x.cpu()
for idx in range(bs):
# from tensor to pil
pil_img = to_pil_image(tmp_x[idx].cpu())
cv2_img = cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR)
outimg = cv2_img[..., np.newaxis]
outimg = np.repeat(outimg, 3, axis=2)
# from opencv to tensor
outimg = to_tensor(outimg)
outimg = outimg.unsqueeze(dim=0)
if idx == 0:
x_multi_gray = outimg
else:
x_multi_gray = torch.cat([x_multi_gray, outimg], dim=0)
x_multi_gray = x_multi_gray.cuda()
img_size = x.shape[-2:]
layer_outputs = []
layer_outputs_multi_gray = []
output = []
for i, (mdef,
module) in enumerate(zip(self.module_defs, self.module_list)):
mtype = mdef['type']
multi_gray_module = self.multi_gray_module_list[i]
# print("第%3d层: %13s |" % (i, mtype), "shape:", x.shape)
if mtype in [
'convolutional', 'upsample', 'maxpool', 'se',
'dilatedconv', 'ppm', 'acconv', 'maxpoolone', 'onemaxpool',
'rfb', 'dwconv', 'res2net', 'triangle', 'skconv',
'channelAttention', 'spatialAttention', 'gcblock', 'rfbs'
]:
x = module(x)
if self.fuse:
x_multi_gray = multi_gray_module(x_multi_gray)
elif mtype == 'fuse':
self.fuse = False
print("fusing.....................")
print(x.shape, "======", x_multi_gray.shape)
x = torch.cat([x, x_multi_gray], 1)
elif mtype == 'route':
layers = [int(x) for x in mdef['layers'].split(',')]
if len(layers) == 1:
x = layer_outputs[layers[0]]
else:
try:
x = torch.cat([layer_outputs[i] for i in layers], 1)
except: # apply stride 2 for darknet reorg layer
layer_outputs[layers[1]] = F.interpolate(
layer_outputs[layers[1]], scale_factor=[0.5, 0.5])
x = torch.cat([layer_outputs[i] for i in layers], 1)
if self.fuse:
layers = [int(x) for x in mdef['layers'].split(',')]
if len(layers) == 1:
x_multi_gray = layer_outputs_multi_gray[layers[0]]
else:
try:
x_multi_gray = torch.cat(
[layer_outputs_multi_gray[i] for i in layers],
1)
except: # apply stride 2 for darknet reorg layer
layer_outputs_multi_gray[