rtcdet_v2_backbone.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .rtcdet_v2_basic import Conv, FasterBlock, DSBlock
  5. except:
  6. from rtcdet_v2_basic import Conv, FasterBlock, DSBlock
  7. model_urls = {
  8. 'fasternet_n': None,
  9. 'fasternet_t': None,
  10. 'fasternet_s': None,
  11. 'fasternet_m': None,
  12. 'fasternet_l': None,
  13. 'fasternet_x': None,
  14. }
  15. # ---------------------------- Backbones ----------------------------
  16. # Modified FasterNet
  17. class FasterConvNet(nn.Module):
  18. def __init__(self, width=1.0, depth=1.0, split_ratio=0.25, act_type='silu', norm_type='BN', depthwise=False):
  19. super(FasterConvNet, self).__init__()
  20. # ------------------ Basic parameters ------------------
  21. ## scale factor
  22. self.width = width
  23. self.depth = depth
  24. self.split_ratio = split_ratio
  25. ## pyramid feats
  26. self.base_dims = [64, 128, 256, 512, 1024]
  27. self.feat_dims = [round(dim * width) for dim in self.base_dims]
  28. ## block depth
  29. self.base_depth = [3, 9, 9, 3]
  30. self.feat_depth = [round(num * depth) for num in self.base_depth]
  31. ## nonlinear
  32. self.act_type = act_type
  33. self.norm_type = norm_type
  34. self.depthwise = depthwise
  35. # ------------------ Network parameters ------------------
  36. ## P1/2
  37. self.layer_1 = nn.Sequential(
  38. Conv(3, self.feat_dims[0], k=6, p=2, s=2, act_type=self.act_type, norm_type=self.norm_type),
  39. 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),
  40. )
  41. ## P2/4
  42. self.layer_2 = nn.Sequential(
  43. Conv(self.feat_dims[0], self.feat_dims[1], k=3, p=1, s=2, act_type=self.act_type, norm_type=self.norm_type),
  44. FasterBlock(self.feat_dims[1], self.feat_dims[1], self.split_ratio, self.feat_depth[0], True, self.act_type, self.norm_type)
  45. )
  46. ## P3/8
  47. self.layer_3 = nn.Sequential(
  48. DSBlock(self.feat_dims[1], self.feat_dims[2], self.act_type, self.norm_type, self.depthwise),
  49. FasterBlock(self.feat_dims[2], self.feat_dims[2], self.split_ratio, self.feat_depth[1], True, self.act_type, self.norm_type)
  50. )
  51. ## P4/16
  52. self.layer_4 = nn.Sequential(
  53. DSBlock(self.feat_dims[2], self.feat_dims[3], self.act_type, self.norm_type, self.depthwise),
  54. FasterBlock(self.feat_dims[3], self.feat_dims[3], self.split_ratio, self.feat_depth[2], True, self.act_type, self.norm_type)
  55. )
  56. ## P5/32
  57. self.layer_5 = nn.Sequential(
  58. DSBlock(self.feat_dims[3], self.feat_dims[4], self.act_type, self.norm_type, self.depthwise),
  59. FasterBlock(self.feat_dims[4], self.feat_dims[4], self.split_ratio, self.feat_depth[3], True, self.act_type, self.norm_type)
  60. )
  61. def forward(self, x):
  62. c1 = self.layer_1(x)
  63. c2 = self.layer_2(c1)
  64. c3 = self.layer_3(c2)
  65. c4 = self.layer_4(c3)
  66. c5 = self.layer_5(c4)
  67. outputs = [c3, c4, c5]
  68. return outputs
  69. # ---------------------------- Functions ----------------------------
  70. ## load pretrained weight
  71. def load_weight(model, model_name):
  72. # load weight
  73. print('Loading pretrained weight ...')
  74. url = model_urls[model_name]
  75. if url is not None:
  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 = model.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. model.load_state_dict(checkpoint_state_dict)
  93. else:
  94. print('No pretrained for {}'.format(model_name))
  95. return model
  96. ## build MCNet
  97. def build_backbone(cfg, pretrained=False):
  98. # model
  99. backbone = FasterConvNet(cfg['width'], cfg['depth'], cfg['bk_split_ratio'], cfg['bk_act'], cfg['bk_norm'], cfg['bk_depthwise'])
  100. # check whether to load imagenet pretrained weight
  101. if pretrained:
  102. if cfg['width'] == 0.25 and cfg['depth'] == 0.34:
  103. backbone = load_weight(backbone, model_name='fasternet_n')
  104. elif cfg['width'] == 0.375 and cfg['depth'] == 0.34:
  105. backbone = load_weight(backbone, model_name='fasternet_t')
  106. elif cfg['width'] == 0.5 and cfg['depth'] == 0.34:
  107. backbone = load_weight(backbone, model_name='fasternet_s')
  108. elif cfg['width'] == 0.75 and cfg['depth'] == 0.67:
  109. backbone = load_weight(backbone, model_name='fasternet_m')
  110. elif cfg['width'] == 1.0 and cfg['depth'] == 1.0:
  111. backbone = load_weight(backbone, model_name='fasternet_l')
  112. elif cfg['width'] == 1.25 and cfg['depth'] == 1.34:
  113. backbone = load_weight(backbone, model_name='fasternet_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': 'mcnet',
  122. 'pretrained': True,
  123. 'bk_act': 'silu',
  124. 'bk_norm': 'BN',
  125. 'bk_depthwise': False,
  126. 'bk_split_ratio': 0.25,
  127. 'width': 1.0,
  128. 'depth': 1.0,
  129. 'stride': [8, 16, 32], # P3, P4, P5
  130. 'max_stride': 32,
  131. }
  132. model, feats = build_backbone(cfg)
  133. x = torch.randn(1, 3, 640, 640)
  134. t0 = time.time()
  135. outputs = model(x)
  136. t1 = time.time()
  137. print('Time: ', t1 - t0)
  138. for out in outputs:
  139. print(out.shape)
  140. print('==============================')
  141. flops, params = profile(model, inputs=(x, ), verbose=False)
  142. print('==============================')
  143. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  144. print('Params : {:.2f} M'.format(params / 1e6))