yolov7_af_backbone.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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_6.6.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)
  28. self.layer_3 = self.make_block(self.feat_dims[1], self.feat_dims[2], expansion=0.5)
  29. self.layer_4 = self.make_block(self.feat_dims[2], self.feat_dims[3], expansion=0.5)
  30. self.layer_5 = self.make_block(self.feat_dims[3], self.feat_dims[4], expansion=0.5)
  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):
  73. block = nn.Sequential(
  74. nn.MaxPool2d((2, 2), stride=2),
  75. ELANLayer(in_dim, out_dim,
  76. expansion=expansion, num_blocks=self.elan_depth,
  77. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  78. )
  79. return block
  80. def forward(self, x):
  81. c1 = self.layer_1(x)
  82. c2 = self.layer_2(c1)
  83. c3 = self.layer_3(c2)
  84. c4 = self.layer_4(c3)
  85. c5 = self.layer_5(c4)
  86. outputs = [c3, c4, c5]
  87. return outputs
  88. # ELANNet-Large
  89. class Yolov7LBackbone(nn.Module):
  90. def __init__(self, cfg):
  91. super(Yolov7LBackbone, self).__init__()
  92. # ---------------- Basic parameters ----------------
  93. self.model_scale = cfg.scale
  94. self.bk_act = cfg.bk_act
  95. self.bk_norm = cfg.bk_norm
  96. self.bk_depthwise = cfg.bk_depthwise
  97. self.elan_depth = 2
  98. self.feat_dims = [round(64 * cfg.width), round(128 * cfg.width), round(256 * cfg.width),
  99. round(512 * cfg.width), round(1024 * cfg.width), round(1024 * cfg.width)]
  100. # ---------------- Model parameters ----------------
  101. self.layer_1 = self.make_stem(3, self.feat_dims[0])
  102. self.layer_2 = self.make_block(self.feat_dims[0], self.feat_dims[1], self.feat_dims[2], expansion=0.5, conv_downsample=True)
  103. self.layer_3 = self.make_block(self.feat_dims[2], self.feat_dims[2], self.feat_dims[3], expansion=0.5)
  104. self.layer_4 = self.make_block(self.feat_dims[3], self.feat_dims[3], self.feat_dims[4], expansion=0.5)
  105. self.layer_5 = self.make_block(self.feat_dims[4], self.feat_dims[4], self.feat_dims[5], expansion=0.25)
  106. # Initialize all layers
  107. self.init_weights()
  108. # Load imagenet pretrained weight
  109. if cfg.use_pretrained:
  110. self.load_pretrained()
  111. def init_weights(self):
  112. """Initialize the parameters."""
  113. for m in self.modules():
  114. if isinstance(m, torch.nn.Conv2d):
  115. # In order to be consistent with the source code,
  116. # reset the Conv2d initialization parameters
  117. m.reset_parameters()
  118. def load_pretrained(self):
  119. url = pretrained_urls[self.model_scale]
  120. if url is not None:
  121. print('Loading backbone pretrained weight from : {}'.format(url))
  122. # checkpoint state dict
  123. checkpoint = torch.hub.load_state_dict_from_url(
  124. url=url, map_location="cpu", check_hash=True)
  125. checkpoint_state_dict = checkpoint.pop("model")
  126. # model state dict
  127. model_state_dict = self.state_dict()
  128. # check
  129. for k in list(checkpoint_state_dict.keys()):
  130. if k in model_state_dict:
  131. shape_model = tuple(model_state_dict[k].shape)
  132. shape_checkpoint = tuple(checkpoint_state_dict[k].shape)
  133. if shape_model != shape_checkpoint:
  134. checkpoint_state_dict.pop(k)
  135. else:
  136. checkpoint_state_dict.pop(k)
  137. print('Unused key: ', k)
  138. # load the weight
  139. self.load_state_dict(checkpoint_state_dict)
  140. else:
  141. print('No pretrained weight for model scale: {}.'.format(self.model_scale))
  142. def make_stem(self, in_dim, out_dim):
  143. stem = nn.Sequential(
  144. BasicConv(in_dim, out_dim//2, kernel_size=3, padding=1, stride=1,
  145. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  146. BasicConv(out_dim//2, out_dim, kernel_size=3, padding=1, stride=2,
  147. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  148. BasicConv(out_dim, out_dim, kernel_size=3, padding=1, stride=1,
  149. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise)
  150. )
  151. return stem
  152. def make_block(self, in_dim, out_dim_1, out_dim_2, expansion=0.5, conv_downsample=False):
  153. if conv_downsample:
  154. block = nn.Sequential(
  155. BasicConv(in_dim, out_dim_1, kernel_size=3, padding=1, stride=2,
  156. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  157. ELANLayer(out_dim_1, out_dim_2,
  158. expansion=expansion, num_blocks=self.elan_depth,
  159. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  160. )
  161. else:
  162. block = nn.Sequential(
  163. MDown(in_dim, out_dim_1,
  164. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  165. ELANLayer(out_dim_1, out_dim_2,
  166. expansion=expansion, num_blocks=self.elan_depth,
  167. act_type=self.bk_act, norm_type=self.bk_norm, depthwise=self.bk_depthwise),
  168. )
  169. return block
  170. def forward(self, x):
  171. c1 = self.layer_1(x)
  172. c2 = self.layer_2(c1)
  173. c3 = self.layer_3(c2)
  174. c4 = self.layer_4(c3)
  175. c5 = self.layer_5(c4)
  176. outputs = [c3, c4, c5]
  177. return outputs
  178. if __name__ == '__main__':
  179. import time
  180. from thop import profile
  181. class BaseConfig(object):
  182. def __init__(self) -> None:
  183. self.bk_act = 'silu'
  184. self.bk_norm = 'BN'
  185. self.bk_depthwise = False
  186. self.use_pretrained = True
  187. self.width = 0.5
  188. self.scale = "t"
  189. cfg = BaseConfig()
  190. model = Yolov7TBackbone(cfg)
  191. x = torch.randn(1, 3, 640, 640)
  192. t0 = time.time()
  193. outputs = model(x)
  194. t1 = time.time()
  195. print('Time: ', t1 - t0)
  196. for out in outputs:
  197. print(out.shape)
  198. x = torch.randn(1, 3, 640, 640)
  199. print('==============================')
  200. flops, params = profile(model, inputs=(x, ), verbose=False)
  201. print('==============================')
  202. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  203. print('Params : {:.2f} M'.format(params / 1e6))