rtcdet_v2_backbone.py 6.0 KB

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