rtcdetv2_backbone.py 6.1 KB

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