yolov5_backbone.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .yolov5_basic import Conv, CSPBlock
  5. from .yolov5_neck import SPPF
  6. except:
  7. from yolov5_basic import Conv, CSPBlock
  8. from yolov5_neck import SPPF
  9. model_urls = {
  10. "cspdarknet_large": "https://github.com/yjh0410/image_classification_pytorch/releases/download/weight/cspdarknet_large.pth",
  11. }
  12. # CSPDarkNet
  13. class CSPDarkNet(nn.Module):
  14. def __init__(self, depth=1.0, width=1.0, act_type='silu', norm_type='BN', depthwise=False):
  15. super(CSPDarkNet, self).__init__()
  16. self.feat_dims = [int(256*width), int(512*width), int(1024*width)]
  17. # P1
  18. self.layer_1 = Conv(3, int(64*width), k=6, p=2, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  19. # P2
  20. self.layer_2 = nn.Sequential(
  21. Conv(int(64*width), int(128*width), k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise),
  22. CSPBlock(int(128*width), int(128*width), expand_ratio=0.5, nblocks=int(3*depth),
  23. shortcut=True, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  24. )
  25. # P3
  26. self.layer_3 = nn.Sequential(
  27. Conv(int(128*width), int(256*width), k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise),
  28. CSPBlock(int(256*width), int(256*width), expand_ratio=0.5, nblocks=int(9*depth),
  29. shortcut=True, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  30. )
  31. # P4
  32. self.layer_4 = nn.Sequential(
  33. Conv(int(256*width), int(512*width), k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise),
  34. CSPBlock(int(512*width), int(512*width), expand_ratio=0.5, nblocks=int(9*depth),
  35. shortcut=True, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  36. )
  37. # P5
  38. self.layer_5 = nn.Sequential(
  39. Conv(int(512*width), int(1024*width), k=3, p=1, s=2, act_type=act_type, norm_type=norm_type, depthwise=depthwise),
  40. SPPF(int(1024*width), int(1024*width), expand_ratio=0.5, act_type=act_type, norm_type=norm_type),
  41. CSPBlock(int(1024*width), int(1024*width), expand_ratio=0.5, nblocks=int(3*depth),
  42. shortcut=True, act_type=act_type, norm_type=norm_type, depthwise=depthwise)
  43. )
  44. def forward(self, x):
  45. c1 = self.layer_1(x)
  46. c2 = self.layer_2(c1)
  47. c3 = self.layer_3(c2)
  48. c4 = self.layer_4(c3)
  49. c5 = self.layer_5(c4)
  50. outputs = [c3, c4, c5]
  51. return outputs
  52. # ---------------------------- Functions ----------------------------
  53. def build_backbone(cfg, pretrained=False):
  54. """Constructs a darknet-53 model.
  55. Args:
  56. pretrained (bool): If True, returns a model pre-trained on ImageNet
  57. """
  58. backbone = CSPDarkNet(cfg['depth'], cfg['width'], cfg['bk_act'], cfg['bk_norm'], cfg['bk_dpw'])
  59. feat_dims = backbone.feat_dims
  60. if pretrained:
  61. if cfg['width'] == 1.0 and cfg['depth'] == 1.0:
  62. url = model_urls['cspdarknet_large']
  63. if url is not None:
  64. print('Loading pretrained weight ...')
  65. checkpoint = torch.hub.load_state_dict_from_url(
  66. url=url, map_location="cpu", check_hash=True)
  67. # checkpoint state dict
  68. checkpoint_state_dict = checkpoint.pop("model")
  69. # model state dict
  70. model_state_dict = backbone.state_dict()
  71. # check
  72. for k in list(checkpoint_state_dict.keys()):
  73. if k in model_state_dict:
  74. shape_model = tuple(model_state_dict[k].shape)
  75. shape_checkpoint = tuple(checkpoint_state_dict[k].shape)
  76. if shape_model != shape_checkpoint:
  77. checkpoint_state_dict.pop(k)
  78. else:
  79. checkpoint_state_dict.pop(k)
  80. print(k)
  81. backbone.load_state_dict(checkpoint_state_dict)
  82. else:
  83. print('No backbone pretrained: CSPDarkNet53')
  84. return backbone, feat_dims
  85. if __name__ == '__main__':
  86. import time
  87. from thop import profile
  88. cfg = {
  89. 'pretrained': False,
  90. 'bk_act': 'lrelu',
  91. 'bk_norm': 'BN',
  92. 'bk_dpw': False,
  93. 'p6_feat': False,
  94. 'p7_feat': False,
  95. 'width': 1.0,
  96. 'depth': 1.0,
  97. }
  98. model, feats = build_backbone(cfg)
  99. x = torch.randn(1, 3, 224, 224)
  100. t0 = time.time()
  101. outputs = model(x)
  102. t1 = time.time()
  103. print('Time: ', t1 - t0)
  104. for out in outputs:
  105. print(out.shape)
  106. x = torch.randn(1, 3, 224, 224)
  107. print('==============================')
  108. flops, params = profile(model, inputs=(x, ), verbose=False)
  109. print('==============================')
  110. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  111. print('Params : {:.2f} M'.format(params / 1e6))