yolov7_backbone.py 8.4 KB

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