rtmdet_v2_backbone.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .rtmdet_v2_basic import Conv, MCBlock, DSBlock
  5. except:
  6. from rtmdet_v2_basic import Conv, MCBlock, DSBlock
  7. model_urls = {
  8. 'mcnet_p': None,
  9. 'mcnet_n': None,
  10. 'mcnet_t': None,
  11. 'mcnet_s': None,
  12. 'mcnet_m': None,
  13. 'mcnet_l': None,
  14. 'mcnet_x': None,
  15. }
  16. # ---------------------------- Backbones ----------------------------
  17. class MixedConvNet(nn.Module):
  18. def __init__(self, width=1.0, depth=1.0, num_heads=4, act_type='silu', norm_type='BN', depthwise=False):
  19. super(MixedConvNet, self).__init__()
  20. # ------------------ Basic parameters ------------------
  21. self.feat_dims_base = [64, 128, 256, 512, 1024]
  22. self.nblocks_base = [3, 6, 9, 3]
  23. self.feat_dims = [round(dim * width) for dim in self.feat_dims_base]
  24. self.nblocks = [round(nblock * depth) for nblock in self.nblocks_base]
  25. self.num_heads = num_heads
  26. self.act_type = act_type
  27. self.norm_type = norm_type
  28. self.depthwise = depthwise
  29. # ------------------ Network parameters ------------------
  30. ## P1/2
  31. self.layer_1 = nn.Sequential(
  32. Conv(3, self.feat_dims[0], k=3, p=1, s=2, act_type=self.act_type, norm_type=self.norm_type),
  33. 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),
  34. )
  35. ## P2/4
  36. self.layer_2 = nn.Sequential(
  37. 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),
  38. MCBlock(self.feat_dims[1], self.feat_dims[1], self.nblocks[0], self.num_heads, True, self.act_type, self.norm_type, self.depthwise)
  39. )
  40. ## P3/8
  41. self.layer_3 = nn.Sequential(
  42. DSBlock(self.feat_dims[1], self.feat_dims[2], self.num_heads, self.act_type, self.norm_type, self.depthwise),
  43. MCBlock(self.feat_dims[2], self.feat_dims[2], self.nblocks[1], self.num_heads, True, self.act_type, self.norm_type, self.depthwise)
  44. )
  45. ## P4/16
  46. self.layer_4 = nn.Sequential(
  47. DSBlock(self.feat_dims[2], self.feat_dims[3], self.num_heads, self.act_type, self.norm_type, self.depthwise),
  48. MCBlock(self.feat_dims[3], self.feat_dims[3], self.nblocks[2], self.num_heads, True, self.act_type, self.norm_type, self.depthwise)
  49. )
  50. ## P5/32
  51. self.layer_5 = nn.Sequential(
  52. DSBlock(self.feat_dims[3], self.feat_dims[4], self.num_heads, self.act_type, self.norm_type, self.depthwise),
  53. MCBlock(self.feat_dims[4], self.feat_dims[4], self.nblocks[3], self.num_heads, True, self.act_type, self.norm_type, self.depthwise)
  54. )
  55. def forward(self, x):
  56. c1 = self.layer_1(x)
  57. c2 = self.layer_2(c1)
  58. c3 = self.layer_3(c2)
  59. c4 = self.layer_4(c3)
  60. c5 = self.layer_5(c4)
  61. outputs = [c3, c4, c5]
  62. return outputs
  63. # ---------------------------- Functions ----------------------------
  64. ## load pretrained weight
  65. def load_weight(model, model_name):
  66. # load weight
  67. print('Loading pretrained weight ...')
  68. url = model_urls[model_name]
  69. if url is not None:
  70. checkpoint = torch.hub.load_state_dict_from_url(
  71. url=url, map_location="cpu", check_hash=True)
  72. # checkpoint state dict
  73. checkpoint_state_dict = checkpoint.pop("model")
  74. # model state dict
  75. model_state_dict = model.state_dict()
  76. # check
  77. for k in list(checkpoint_state_dict.keys()):
  78. if k in model_state_dict:
  79. shape_model = tuple(model_state_dict[k].shape)
  80. shape_checkpoint = tuple(checkpoint_state_dict[k].shape)
  81. if shape_model != shape_checkpoint:
  82. checkpoint_state_dict.pop(k)
  83. else:
  84. checkpoint_state_dict.pop(k)
  85. print(k)
  86. model.load_state_dict(checkpoint_state_dict)
  87. else:
  88. print('No pretrained for {}'.format(model_name))
  89. return model
  90. ## build MCNet
  91. def build_backbone(cfg, pretrained=False):
  92. # model
  93. backbone = MixedConvNet(cfg['width'], cfg['depth'], cfg['bk_num_heads'], cfg['bk_act'], cfg['bk_norm'], cfg['bk_depthwise'])
  94. # check whether to load imagenet pretrained weight
  95. if pretrained:
  96. if cfg['width'] == 0.25 and cfg['depth'] == 0.34 and cfg['bk_depthwise']:
  97. backbone = load_weight(backbone, model_name='mcnet_p')
  98. elif cfg['width'] == 0.25 and cfg['depth'] == 0.34:
  99. backbone = load_weight(backbone, model_name='mcnet_n')
  100. elif cfg['width'] == 0.375 and cfg['depth'] == 0.34:
  101. backbone = load_weight(backbone, model_name='mcnet_t')
  102. elif cfg['width'] == 0.5 and cfg['depth'] == 0.34:
  103. backbone = load_weight(backbone, model_name='mcnet_s')
  104. elif cfg['width'] == 0.75 and cfg['depth'] == 0.67:
  105. backbone = load_weight(backbone, model_name='mcnet_m')
  106. elif cfg['width'] == 1.0 and cfg['depth'] == 1.0:
  107. backbone = load_weight(backbone, model_name='mcnet_l')
  108. elif cfg['width'] == 1.25 and cfg['depth'] == 1.34:
  109. backbone = load_weight(backbone, model_name='mcnet_x')
  110. feat_dims = backbone.feat_dims[-3:]
  111. return backbone, feat_dims
  112. if __name__ == '__main__':
  113. import time
  114. from thop import profile
  115. cfg = {
  116. ## Backbone
  117. 'backbone': 'mcnet',
  118. 'pretrained': True,
  119. 'bk_act': 'silu',
  120. 'bk_norm': 'BN',
  121. 'bk_depthwise': False,
  122. 'bk_num_heads': 4,
  123. 'width': 0.25,
  124. 'depth': 0.34,
  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))