rtcdet_backbone.py 6.4 KB

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