res2net.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import math
  3. import torch
  4. import torch.nn as nn
  5. import torch.utils.checkpoint as cp
  6. from mmcv.cnn import build_conv_layer, build_norm_layer
  7. from mmengine.model import Sequential
  8. from mmdet.registry import MODELS
  9. from .resnet import Bottleneck as _Bottleneck
  10. from .resnet import ResNet
  11. class Bottle2neck(_Bottleneck):
  12. expansion = 4
  13. def __init__(self,
  14. inplanes,
  15. planes,
  16. scales=4,
  17. base_width=26,
  18. base_channels=64,
  19. stage_type='normal',
  20. **kwargs):
  21. """Bottle2neck block for Res2Net.
  22. If style is "pytorch", the stride-two layer is the 3x3 conv layer, if
  23. it is "caffe", the stride-two layer is the first 1x1 conv layer.
  24. """
  25. super(Bottle2neck, self).__init__(inplanes, planes, **kwargs)
  26. assert scales > 1, 'Res2Net degenerates to ResNet when scales = 1.'
  27. width = int(math.floor(self.planes * (base_width / base_channels)))
  28. self.norm1_name, norm1 = build_norm_layer(
  29. self.norm_cfg, width * scales, postfix=1)
  30. self.norm3_name, norm3 = build_norm_layer(
  31. self.norm_cfg, self.planes * self.expansion, postfix=3)
  32. self.conv1 = build_conv_layer(
  33. self.conv_cfg,
  34. self.inplanes,
  35. width * scales,
  36. kernel_size=1,
  37. stride=self.conv1_stride,
  38. bias=False)
  39. self.add_module(self.norm1_name, norm1)
  40. if stage_type == 'stage' and self.conv2_stride != 1:
  41. self.pool = nn.AvgPool2d(
  42. kernel_size=3, stride=self.conv2_stride, padding=1)
  43. convs = []
  44. bns = []
  45. fallback_on_stride = False
  46. if self.with_dcn:
  47. fallback_on_stride = self.dcn.pop('fallback_on_stride', False)
  48. if not self.with_dcn or fallback_on_stride:
  49. for i in range(scales - 1):
  50. convs.append(
  51. build_conv_layer(
  52. self.conv_cfg,
  53. width,
  54. width,
  55. kernel_size=3,
  56. stride=self.conv2_stride,
  57. padding=self.dilation,
  58. dilation=self.dilation,
  59. bias=False))
  60. bns.append(
  61. build_norm_layer(self.norm_cfg, width, postfix=i + 1)[1])
  62. self.convs = nn.ModuleList(convs)
  63. self.bns = nn.ModuleList(bns)
  64. else:
  65. assert self.conv_cfg is None, 'conv_cfg must be None for DCN'
  66. for i in range(scales - 1):
  67. convs.append(
  68. build_conv_layer(
  69. self.dcn,
  70. width,
  71. width,
  72. kernel_size=3,
  73. stride=self.conv2_stride,
  74. padding=self.dilation,
  75. dilation=self.dilation,
  76. bias=False))
  77. bns.append(
  78. build_norm_layer(self.norm_cfg, width, postfix=i + 1)[1])
  79. self.convs = nn.ModuleList(convs)
  80. self.bns = nn.ModuleList(bns)
  81. self.conv3 = build_conv_layer(
  82. self.conv_cfg,
  83. width * scales,
  84. self.planes * self.expansion,
  85. kernel_size=1,
  86. bias=False)
  87. self.add_module(self.norm3_name, norm3)
  88. self.stage_type = stage_type
  89. self.scales = scales
  90. self.width = width
  91. delattr(self, 'conv2')
  92. delattr(self, self.norm2_name)
  93. def forward(self, x):
  94. """Forward function."""
  95. def _inner_forward(x):
  96. identity = x
  97. out = self.conv1(x)
  98. out = self.norm1(out)
  99. out = self.relu(out)
  100. if self.with_plugins:
  101. out = self.forward_plugin(out, self.after_conv1_plugin_names)
  102. spx = torch.split(out, self.width, 1)
  103. sp = self.convs[0](spx[0].contiguous())
  104. sp = self.relu(self.bns[0](sp))
  105. out = sp
  106. for i in range(1, self.scales - 1):
  107. if self.stage_type == 'stage':
  108. sp = spx[i]
  109. else:
  110. sp = sp + spx[i]
  111. sp = self.convs[i](sp.contiguous())
  112. sp = self.relu(self.bns[i](sp))
  113. out = torch.cat((out, sp), 1)
  114. if self.stage_type == 'normal' or self.conv2_stride == 1:
  115. out = torch.cat((out, spx[self.scales - 1]), 1)
  116. elif self.stage_type == 'stage':
  117. out = torch.cat((out, self.pool(spx[self.scales - 1])), 1)
  118. if self.with_plugins:
  119. out = self.forward_plugin(out, self.after_conv2_plugin_names)
  120. out = self.conv3(out)
  121. out = self.norm3(out)
  122. if self.with_plugins:
  123. out = self.forward_plugin(out, self.after_conv3_plugin_names)
  124. if self.downsample is not None:
  125. identity = self.downsample(x)
  126. out += identity
  127. return out
  128. if self.with_cp and x.requires_grad:
  129. out = cp.checkpoint(_inner_forward, x)
  130. else:
  131. out = _inner_forward(x)
  132. out = self.relu(out)
  133. return out
  134. class Res2Layer(Sequential):
  135. """Res2Layer to build Res2Net style backbone.
  136. Args:
  137. block (nn.Module): block used to build ResLayer.
  138. inplanes (int): inplanes of block.
  139. planes (int): planes of block.
  140. num_blocks (int): number of blocks.
  141. stride (int): stride of the first block. Default: 1
  142. avg_down (bool): Use AvgPool instead of stride conv when
  143. downsampling in the bottle2neck. Default: False
  144. conv_cfg (dict): dictionary to construct and config conv layer.
  145. Default: None
  146. norm_cfg (dict): dictionary to construct and config norm layer.
  147. Default: dict(type='BN')
  148. scales (int): Scales used in Res2Net. Default: 4
  149. base_width (int): Basic width of each scale. Default: 26
  150. """
  151. def __init__(self,
  152. block,
  153. inplanes,
  154. planes,
  155. num_blocks,
  156. stride=1,
  157. avg_down=True,
  158. conv_cfg=None,
  159. norm_cfg=dict(type='BN'),
  160. scales=4,
  161. base_width=26,
  162. **kwargs):
  163. self.block = block
  164. downsample = None
  165. if stride != 1 or inplanes != planes * block.expansion:
  166. downsample = nn.Sequential(
  167. nn.AvgPool2d(
  168. kernel_size=stride,
  169. stride=stride,
  170. ceil_mode=True,
  171. count_include_pad=False),
  172. build_conv_layer(
  173. conv_cfg,
  174. inplanes,
  175. planes * block.expansion,
  176. kernel_size=1,
  177. stride=1,
  178. bias=False),
  179. build_norm_layer(norm_cfg, planes * block.expansion)[1],
  180. )
  181. layers = []
  182. layers.append(
  183. block(
  184. inplanes=inplanes,
  185. planes=planes,
  186. stride=stride,
  187. downsample=downsample,
  188. conv_cfg=conv_cfg,
  189. norm_cfg=norm_cfg,
  190. scales=scales,
  191. base_width=base_width,
  192. stage_type='stage',
  193. **kwargs))
  194. inplanes = planes * block.expansion
  195. for i in range(1, num_blocks):
  196. layers.append(
  197. block(
  198. inplanes=inplanes,
  199. planes=planes,
  200. stride=1,
  201. conv_cfg=conv_cfg,
  202. norm_cfg=norm_cfg,
  203. scales=scales,
  204. base_width=base_width,
  205. **kwargs))
  206. super(Res2Layer, self).__init__(*layers)
  207. @MODELS.register_module()
  208. class Res2Net(ResNet):
  209. """Res2Net backbone.
  210. Args:
  211. scales (int): Scales used in Res2Net. Default: 4
  212. base_width (int): Basic width of each scale. Default: 26
  213. depth (int): Depth of res2net, from {50, 101, 152}.
  214. in_channels (int): Number of input image channels. Default: 3.
  215. num_stages (int): Res2net stages. Default: 4.
  216. strides (Sequence[int]): Strides of the first block of each stage.
  217. dilations (Sequence[int]): Dilation of each stage.
  218. out_indices (Sequence[int]): Output from which stages.
  219. style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
  220. layer is the 3x3 conv layer, otherwise the stride-two layer is
  221. the first 1x1 conv layer.
  222. deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv
  223. avg_down (bool): Use AvgPool instead of stride conv when
  224. downsampling in the bottle2neck.
  225. frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
  226. -1 means not freezing any parameters.
  227. norm_cfg (dict): Dictionary to construct and config norm layer.
  228. norm_eval (bool): Whether to set norm layers to eval mode, namely,
  229. freeze running stats (mean and var). Note: Effect on Batch Norm
  230. and its variants only.
  231. plugins (list[dict]): List of plugins for stages, each dict contains:
  232. - cfg (dict, required): Cfg dict to build plugin.
  233. - position (str, required): Position inside block to insert
  234. plugin, options are 'after_conv1', 'after_conv2', 'after_conv3'.
  235. - stages (tuple[bool], optional): Stages to apply plugin, length
  236. should be same as 'num_stages'.
  237. with_cp (bool): Use checkpoint or not. Using checkpoint will save some
  238. memory while slowing down the training speed.
  239. zero_init_residual (bool): Whether to use zero init for last norm layer
  240. in resblocks to let them behave as identity.
  241. pretrained (str, optional): model pretrained path. Default: None
  242. init_cfg (dict or list[dict], optional): Initialization config dict.
  243. Default: None
  244. Example:
  245. >>> from mmdet.models import Res2Net
  246. >>> import torch
  247. >>> self = Res2Net(depth=50, scales=4, base_width=26)
  248. >>> self.eval()
  249. >>> inputs = torch.rand(1, 3, 32, 32)
  250. >>> level_outputs = self.forward(inputs)
  251. >>> for level_out in level_outputs:
  252. ... print(tuple(level_out.shape))
  253. (1, 256, 8, 8)
  254. (1, 512, 4, 4)
  255. (1, 1024, 2, 2)
  256. (1, 2048, 1, 1)
  257. """
  258. arch_settings = {
  259. 50: (Bottle2neck, (3, 4, 6, 3)),
  260. 101: (Bottle2neck, (3, 4, 23, 3)),
  261. 152: (Bottle2neck, (3, 8, 36, 3))
  262. }
  263. def __init__(self,
  264. scales=4,
  265. base_width=26,
  266. style='pytorch',
  267. deep_stem=True,
  268. avg_down=True,
  269. pretrained=None,
  270. init_cfg=None,
  271. **kwargs):
  272. self.scales = scales
  273. self.base_width = base_width
  274. super(Res2Net, self).__init__(
  275. style='pytorch',
  276. deep_stem=True,
  277. avg_down=True,
  278. pretrained=pretrained,
  279. init_cfg=init_cfg,
  280. **kwargs)
  281. def make_res_layer(self, **kwargs):
  282. return Res2Layer(
  283. scales=self.scales,
  284. base_width=self.base_width,
  285. base_channels=self.base_channels,
  286. **kwargs)