yolov7_af_backbone.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .yolov7_af_basic import BasicConv, MDown, ELANLayer
  5. except:
  6. from yolov7_af_basic import BasicConv, MDown, ELANLayer
  7. # IN1K pretrained weight
  8. pretrained_urls = {
  9. 't': "https://github.com/yjh0410/ICLab/releases/download/in1k_pretrained/elannet_t_in1k_62.0.pth",
  10. 'l': None,
  11. 'x': None,
  12. }
  13. # ELANNet-Tiny
  14. class Yolov7TBackbone(nn.Module):
  15. def __init__(self, cfg):
  16. super(Yolov7TBackbone, self).__init__()
  17. # ---------------- Basic parameters ----------------
  18. self.model_scale = cfg.scale
  19. self.bk_act = cfg.bk_act
  20. self.bk_norm = cfg.bk_norm
  21. self.bk_depthwise = cfg.bk_depthwise
  22. self.elan_depth = 1
  23. self.feat_dims = [round(64 * cfg.width), round(128 * cfg.width),
  24. round(256 * cfg.width), round(512 * cfg.width), round(1024 * cfg.width)]
  25. # ---------------- Model parameters ----------------
  26. self.layer_1 = self.make_stem(3, self.feat_dims[0])
  27. self.layer_2 = self.make_block(self.feat_dims[0], self.feat_dims[1], expansion=0.5, downsample="conv")
  28. self.layer_3 = self.make_block(self.feat_dims[1], self.feat_dims[2], expansion=0.5, downsample="maxpool")
  29. self.layer_4 = self.make_block(self.feat_dims[2], self.feat_dims[3], expansion=0.5, downsample="maxpool")
  30. self.layer_5 = self.make_block(self.feat_dims[3], self.feat_dims[4], expansion=0.5, downsample="maxpool")
  31. # Initialize all layers
  32. # Initialize all layers
  33. self.init_weights()
  34. # Load imagenet pretrained weight
  35. if cfg.use_pretrained:
  36. self.load_pretrained()
  37. def init_weights(self):
  38. """Initialize the parameters."""
  39. for m in self.modules():
  40. if isinstance(m, torch.nn.Conv2d):
  41. # In order to be consistent with the source code,
  42. # reset the Conv2d initialization parameters
  43. m.reset_parameters()
  44. def load_pretrained(self):
  45. url = pretrained_urls[self.model_scale]
  46. if url is not None:
  47. print('Loading backbone pretrained weight from : {}'.format(url))
  48. # checkpoint state dict
  49. checkpoint = torch.hub.load_state_dict_from_url(
  50. url=url, map_location="cpu", check_hash=True)
  51. checkpoint_state_dict = checkpoint.pop("model")
  52. # model state dict
  53. model_state_dict = self.state_dict()
  54. # check
  55. for k in list(checkpoint_state_dict.keys()):
  56. if k in model_state_dict:
  57. shape_model = tuple(model_state_dict[k].shape)
  58. shape_checkpoint = tuple(checkpoint_state_dict[k].shape)
  59. if shape_model != shape_checkpoint:
  60. checkpoint_state_dict.pop(k)
  61. else:
  62. checkpoint_state_dict.pop(k)
  63. print('Unused key: ', k)
  64. # load the weight
  65. self.load_state_dict(checkpoint_state_dict)
  66. else:
  67. print('No pretrained weight for model scale: {}.'.format(self.model_scale))
  68. def make_stem(self, in_dim, out_dim):
  69. stem = BasicConv(in_dim, out_dim, kernel_size=6, padding=2, stride=2,
  70. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise)
  71. return stem
  72. def make_block(self, in_dim, out_dim, expansion=0.5, downsample="maxpool"):
  73. if downsample == "maxpool":
  74. block = nn.Sequential(
  75. nn.MaxPool2d((2, 2), stride=2),
  76. ELANLayer(in_dim, out_dim, expansion=expansion, num_blocks=self.elan_depth,
  77. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  78. )
  79. elif downsample == "conv":
  80. block = nn.Sequential(
  81. BasicConv(in_dim, out_dim, kernel_size=3, padding=1, stride=2,
  82. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  83. ELANLayer(out_dim, out_dim, expansion=expansion, num_blocks=self.elan_depth,
  84. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  85. )
  86. else:
  87. raise NotImplementedError("Unknown downsample type: {}".format(downsample))
  88. return block
  89. def forward(self, x):
  90. c1 = self.layer_1(x)
  91. c2 = self.layer_2(c1)
  92. c3 = self.layer_3(c2)
  93. c4 = self.layer_4(c3)
  94. c5 = self.layer_5(c4)
  95. outputs = [c3, c4, c5]
  96. return outputs
  97. # ELANNet-Large
  98. class Yolov7LBackbone(nn.Module):
  99. def __init__(self, cfg):
  100. super(Yolov7LBackbone, self).__init__()
  101. # ---------------- Basic parameters ----------------
  102. self.model_scale = cfg.scale
  103. self.bk_act = cfg.bk_act
  104. self.bk_norm = cfg.bk_norm
  105. self.bk_depthwise = cfg.bk_depthwise
  106. self.elan_depth = 2
  107. self.feat_dims = [round(64 * cfg.width), round(128 * cfg.width), round(256 * cfg.width),
  108. round(512 * cfg.width), round(1024 * cfg.width), round(1024 * cfg.width)]
  109. # ---------------- Model parameters ----------------
  110. self.layer_1 = self.make_stem(3, self.feat_dims[0])
  111. self.layer_2 = self.make_block(self.feat_dims[0], self.feat_dims[1], self.feat_dims[2], expansion=0.5, conv_downsample=True)
  112. self.layer_3 = self.make_block(self.feat_dims[2], self.feat_dims[2], self.feat_dims[3], expansion=0.5)
  113. self.layer_4 = self.make_block(self.feat_dims[3], self.feat_dims[3], self.feat_dims[4], expansion=0.5)
  114. self.layer_5 = self.make_block(self.feat_dims[4], self.feat_dims[4], self.feat_dims[5], expansion=0.25)
  115. # Initialize all layers
  116. self.init_weights()
  117. # Load imagenet pretrained weight
  118. if cfg.use_pretrained:
  119. self.load_pretrained()
  120. def init_weights(self):
  121. """Initialize the parameters."""
  122. for m in self.modules():
  123. if isinstance(m, torch.nn.Conv2d):
  124. # In order to be consistent with the source code,
  125. # reset the Conv2d initialization parameters
  126. m.reset_parameters()
  127. def load_pretrained(self):
  128. url = pretrained_urls[self.model_scale]
  129. if url is not None:
  130. print('Loading backbone pretrained weight from : {}'.format(url))
  131. # checkpoint state dict
  132. checkpoint = torch.hub.load_state_dict_from_url(
  133. url=url, map_location="cpu", check_hash=True)
  134. checkpoint_state_dict = checkpoint.pop("model")
  135. # model state dict
  136. model_state_dict = self.state_dict()
  137. # check
  138. for k in list(checkpoint_state_dict.keys()):
  139. if k in model_state_dict:
  140. shape_model = tuple(model_state_dict[k].shape)
  141. shape_checkpoint = tuple(checkpoint_state_dict[k].shape)
  142. if shape_model != shape_checkpoint:
  143. checkpoint_state_dict.pop(k)
  144. else:
  145. checkpoint_state_dict.pop(k)
  146. print('Unused key: ', k)
  147. # load the weight
  148. self.load_state_dict(checkpoint_state_dict)
  149. else:
  150. print('No pretrained weight for model scale: {}.'.format(self.model_scale))
  151. def make_stem(self, in_dim, out_dim):
  152. stem = nn.Sequential(
  153. BasicConv(in_dim, out_dim//2, kernel_size=3, padding=1, stride=1,
  154. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  155. BasicConv(out_dim//2, out_dim, kernel_size=3, padding=1, stride=2,
  156. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  157. BasicConv(out_dim, out_dim, kernel_size=3, padding=1, stride=1,
  158. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise)
  159. )
  160. return stem
  161. def make_block(self, in_dim, out_dim_1, out_dim_2, expansion=0.5, conv_downsample=False):
  162. if conv_downsample:
  163. block = nn.Sequential(
  164. BasicConv(in_dim, out_dim_1, kernel_size=3, padding=1, stride=2,
  165. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  166. ELANLayer(out_dim_1, out_dim_2,
  167. expansion=expansion, num_blocks=self.elan_depth,
  168. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  169. )
  170. else:
  171. block = nn.Sequential(
  172. MDown(in_dim, out_dim_1,
  173. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  174. ELANLayer(out_dim_1, out_dim_2,
  175. expansion=expansion, num_blocks=self.elan_depth,
  176. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  177. )
  178. return block
  179. def forward(self, x):
  180. c1 = self.layer_1(x)
  181. c2 = self.layer_2(c1)
  182. c3 = self.layer_3(c2)
  183. c4 = self.layer_4(c3)
  184. c5 = self.layer_5(c4)
  185. outputs = [c3, c4, c5]
  186. return outputs
  187. if __name__ == '__main__':
  188. import time
  189. from thop import profile
  190. class BaseConfig(object):
  191. def __init__(self) -> None:
  192. self.bk_act = 'silu'
  193. self.bk_norm = 'BN'
  194. self.bk_depthwise = False
  195. self.use_pretrained = False
  196. self.width = 0.5
  197. self.scale = "t"
  198. cfg = BaseConfig()
  199. model = Yolov7TBackbone(cfg)
  200. x = torch.randn(1, 3, 640, 640)
  201. t0 = time.time()
  202. outputs = model(x)
  203. t1 = time.time()
  204. print('Time: ', t1 - t0)
  205. for out in outputs:
  206. print(out.shape)
  207. x = torch.randn(1, 3, 640, 640)
  208. print('==============================')
  209. flops, params = profile(model, inputs=(x, ), verbose=False)
  210. print('==============================')
  211. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  212. print('Params : {:.2f} M'.format(params / 1e6))