rtcdet_backbone.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .rtcdet_basic import Conv, RTCBlock
  5. except:
  6. from rtcdet_basic import Conv, RTCBlock
  7. # IN-1k MIM pretrained
  8. model_urls = {
  9. "rtcnet_n": None,
  10. "rtcnet_s": None,
  11. "rtcnet_m": None,
  12. "rtcnet_l": None,
  13. "rtcnet_x": None,
  14. }
  15. # ---------------------------- Basic functions ----------------------------
  16. ## Real-time Convolutional Backbone
  17. class RTCBackbone(nn.Module):
  18. def __init__(self, width=1.0, depth=1.0, ratio=1.0, act_type='silu', norm_type='BN', depthwise=False):
  19. super(RTCBackbone, self).__init__()
  20. # ---------------- Basic parameters ----------------
  21. self.width_factor = width
  22. self.depth_factor = depth
  23. self.last_stage_factor = ratio
  24. self.feat_dims = [round(64 * width), round(128 * width), round(256 * width), round(512 * width), round(512 * width * ratio)]
  25. # ---------------- Network parameters ----------------
  26. ## P1/2
  27. self.layer_1 = Conv(3, self.feat_dims[0], k=3, p=1, s=2, act_type=act_type, norm_type=norm_type)
  28. ## P2/4
  29. self.layer_2 = nn.Sequential(
  30. Conv(self.feat_dims[0], self.feat_dims[1], k=3, p=1, s=2, act_type=act_type, norm_type=norm_type),
  31. RTCBlock(in_dim = self.feat_dims[1],
  32. out_dim = self.feat_dims[1],
  33. num_blocks = round(3*depth),
  34. shortcut = True,
  35. act_type = act_type,
  36. norm_type = norm_type,
  37. depthwise = depthwise)
  38. )
  39. ## P3/8
  40. self.layer_3 = nn.Sequential(
  41. Conv(self.feat_dims[1], self.feat_dims[2], k=3, p=1, s=2, act_type=act_type, norm_type=norm_type),
  42. RTCBlock(in_dim = self.feat_dims[2],
  43. out_dim = self.feat_dims[2],
  44. num_blocks = round(6*depth),
  45. shortcut = True,
  46. act_type = act_type,
  47. norm_type = norm_type,
  48. depthwise = depthwise)
  49. )
  50. ## P4/16
  51. self.layer_4 = nn.Sequential(
  52. Conv(self.feat_dims[2], self.feat_dims[3], k=3, p=1, s=2, act_type=act_type, norm_type=norm_type),
  53. RTCBlock(in_dim = self.feat_dims[3],
  54. out_dim = self.feat_dims[3],
  55. num_blocks = round(6*depth),
  56. shortcut = True,
  57. act_type = act_type,
  58. norm_type = norm_type,
  59. depthwise = depthwise)
  60. )
  61. ## P5/32
  62. self.layer_5 = nn.Sequential(
  63. Conv(self.feat_dims[3], self.feat_dims[4], k=3, p=1, s=2, act_type=act_type, norm_type=norm_type),
  64. RTCBlock(in_dim = self.feat_dims[4],
  65. out_dim = self.feat_dims[4],
  66. num_blocks = round(3*depth),
  67. shortcut = True,
  68. act_type = act_type,
  69. norm_type = norm_type,
  70. depthwise = depthwise)
  71. )
  72. def forward(self, x):
  73. c1 = self.layer_1(x)
  74. c2 = self.layer_2(c1)
  75. c3 = self.layer_3(c2)
  76. c4 = self.layer_4(c3)
  77. c5 = self.layer_5(c4)
  78. outputs = [c3, c4, c5]
  79. return outputs
  80. # ---------------------------- Functions ----------------------------
  81. ## Build Backbone network
  82. def build_backbone(cfg, pretrained=False):
  83. # build backbone model
  84. backbone = RTCBackbone(width=cfg['width'],
  85. depth=cfg['depth'],
  86. ratio=cfg['ratio'],
  87. act_type=cfg['bk_act'],
  88. norm_type=cfg['bk_norm'],
  89. depthwise=cfg['bk_depthwise']
  90. )
  91. feat_dims = backbone.feat_dims[-3:]
  92. # Model name
  93. width, depth, ratio = cfg['width'], cfg['depth'], cfg['ratio']
  94. if width == 0.25 and depth == 0.34 and ratio == 2.0:
  95. model_name = "rtcnet_n"
  96. elif width == 0.50 and depth == 0.34 and ratio == 2.0:
  97. model_name = "rtcnet_s"
  98. elif width == 0.75 and depth == 0.67 and ratio == 1.5:
  99. model_name = "rtcnet_m"
  100. elif width == 1.0 and depth == 1.0 and ratio == 1.0:
  101. model_name = "rtcnet_l"
  102. elif width == 1.25 and depth == 1.34 and ratio == 1.0:
  103. model_name = "rtcnet_x"
  104. else:
  105. raise NotImplementedError("No such model size : width={}, depth={}, ratio={}. ".format(width, depth, ratio))
  106. # Load pretrained weight
  107. if pretrained:
  108. backbone = load_pretrained_weight(backbone, model_name)
  109. return backbone, feat_dims
  110. ## Load pretrained weight
  111. def load_pretrained_weight(model, model_name):
  112. # Load pretrained weight
  113. url = model_urls[model_name]
  114. if url is not None:
  115. print('Loading pretrained weight ...')
  116. checkpoint = torch.hub.load_state_dict_from_url(
  117. url=url, map_location="cpu", check_hash=True)
  118. # checkpoint state dict
  119. checkpoint_state_dict = checkpoint.pop("model")
  120. # model state dict
  121. model_state_dict = model.state_dict()
  122. # check
  123. for k in list(checkpoint_state_dict.keys()):
  124. if k in model_state_dict:
  125. shape_model = tuple(model_state_dict[k].shape)
  126. shape_checkpoint = tuple(checkpoint_state_dict[k].shape)
  127. if shape_model != shape_checkpoint:
  128. checkpoint_state_dict.pop(k)
  129. else:
  130. checkpoint_state_dict.pop(k)
  131. print('Unused key: ', k)
  132. # load the weight
  133. model.load_state_dict(checkpoint_state_dict)
  134. else:
  135. print('No backbone pretrained for {}.'.format(model_name))
  136. return model
  137. if __name__ == '__main__':
  138. import time
  139. from thop import profile
  140. cfg = {
  141. 'bk_pretrained': True,
  142. 'bk_act': 'silu',
  143. 'bk_norm': 'BN',
  144. 'bk_depthwise': False,
  145. 'width': 0.25,
  146. 'depth': 0.34,
  147. 'ratio': 2.0,
  148. }
  149. model, feats = build_backbone(cfg, pretrained=cfg['bk_pretrained'])
  150. x = torch.randn(1, 3, 640, 640)
  151. t0 = time.time()
  152. outputs = model(x)
  153. t1 = time.time()
  154. print('Time: ', t1 - t0)
  155. for out in outputs:
  156. print(out.shape)
  157. x = torch.randn(1, 3, 640, 640)
  158. print('==============================')
  159. flops, params = profile(model, inputs=(x, ), verbose=False)
  160. print('==============================')
  161. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  162. print('Params : {:.2f} M'.format(params / 1e6))
  163. for n, p in model.named_parameters():
  164. print(n)