rtcdet_backbone.py 6.5 KB

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