yolov5_backbone.py 5.7 KB

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