yolov8_backbone.py 5.8 KB

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