yolov7_backbone.py 4.8 KB

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