resnet.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import warnings
  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, build_plugin_layer
  7. from mmengine.model import BaseModule
  8. from torch.nn.modules.batchnorm import _BatchNorm
  9. from mmdet.registry import MODELS
  10. from ..layers import ResLayer
  11. from ..layers import SPD
  12. class BasicBlock(BaseModule):
  13. expansion = 1
  14. def __init__(self,
  15. inplanes,
  16. planes,
  17. stride=1,
  18. dilation=1,
  19. downsample=None,
  20. style='pytorch',
  21. with_cp=False,
  22. with_spd=False,
  23. conv_cfg=None,
  24. norm_cfg=dict(type='BN'),
  25. dcn=None,
  26. plugins=None,
  27. init_cfg=None):
  28. super(BasicBlock, self).__init__(init_cfg)
  29. assert dcn is None, 'Not implemented yet.'
  30. assert plugins is None, 'Not implemented yet.'
  31. self.with_spd=with_spd
  32. if stride==2 and self.with_spd:
  33. self.norm1_name, norm1 = build_norm_layer(norm_cfg, 4*planes, postfix=1)
  34. self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
  35. self.spd=SPD()
  36. self.conv1 = build_conv_layer(
  37. conv_cfg,
  38. inplanes,
  39. planes,
  40. 3,
  41. stride=1,
  42. padding=dilation,
  43. dilation=dilation,
  44. bias=False)
  45. self.add_module(self.norm1_name, norm1)
  46. self.conv2 = build_conv_layer(
  47. conv_cfg, 4*planes, planes, 3, padding=1, bias=False)
  48. self.add_module(self.norm2_name, norm2)
  49. else:
  50. self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
  51. self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
  52. self.conv1 = build_conv_layer(
  53. conv_cfg,
  54. inplanes,
  55. planes,
  56. 3,
  57. stride=stride,
  58. padding=dilation,
  59. dilation=dilation,
  60. bias=False)
  61. self.add_module(self.norm1_name, norm1)
  62. self.conv2 = build_conv_layer(
  63. conv_cfg, planes, planes, 3, padding=1, bias=False)
  64. self.add_module(self.norm2_name, norm2)
  65. self.relu = nn.ReLU(inplace=True)
  66. self.downsample = downsample
  67. self.stride = stride
  68. self.dilation = dilation
  69. self.with_cp = with_cp
  70. @property
  71. def norm1(self):
  72. """nn.Module: normalization layer after the first convolution layer"""
  73. return getattr(self, self.norm1_name)
  74. @property
  75. def norm2(self):
  76. """nn.Module: normalization layer after the second convolution layer"""
  77. return getattr(self, self.norm2_name)
  78. def forward(self, x):
  79. """Forward function."""
  80. def _inner_forward(x):
  81. identity = x
  82. if self.stride==2 and self.with_spd:
  83. out = self.conv1(x)
  84. out = self.spd(out)
  85. out = self.norm1(out)
  86. out = self.relu(out)
  87. out = self.conv2(out)
  88. out = self.norm2(out)
  89. else:
  90. out = self.conv1(x)
  91. out = self.norm1(out)
  92. out = self.relu(out)
  93. out = self.conv2(out)
  94. out = self.norm2(out)
  95. if self.downsample is not None:
  96. identity = self.downsample(x)
  97. out += identity
  98. return out
  99. if self.with_cp and x.requires_grad:
  100. out = cp.checkpoint(_inner_forward, x)
  101. else:
  102. out = _inner_forward(x)
  103. out = self.relu(out)
  104. return out
  105. class Bottleneck(BaseModule):
  106. expansion = 4
  107. def __init__(self,
  108. inplanes,
  109. planes,
  110. stride=1,
  111. dilation=1,
  112. downsample=None,
  113. style='pytorch',
  114. with_cp=False,
  115. conv_cfg=None,
  116. norm_cfg=dict(type='BN'),
  117. dcn=None,
  118. plugins=None,
  119. init_cfg=None):
  120. """Bottleneck block for ResNet.
  121. If style is "pytorch", the stride-two layer is the 3x3 conv layer, if
  122. it is "caffe", the stride-two layer is the first 1x1 conv layer.
  123. """
  124. super(Bottleneck, self).__init__(init_cfg)
  125. assert style in ['pytorch', 'caffe']
  126. assert dcn is None or isinstance(dcn, dict)
  127. assert plugins is None or isinstance(plugins, list)
  128. if plugins is not None:
  129. allowed_position = ['after_conv1', 'after_conv2', 'after_conv3']
  130. assert all(p['position'] in allowed_position for p in plugins)
  131. self.inplanes = inplanes
  132. self.planes = planes
  133. self.stride = stride
  134. self.dilation = dilation
  135. self.style = style
  136. self.with_cp = with_cp
  137. self.conv_cfg = conv_cfg
  138. self.norm_cfg = norm_cfg
  139. self.dcn = dcn
  140. self.with_dcn = dcn is not None
  141. self.plugins = plugins
  142. self.with_plugins = plugins is not None
  143. if self.with_plugins:
  144. # collect plugins for conv1/conv2/conv3
  145. self.after_conv1_plugins = [
  146. plugin['cfg'] for plugin in plugins
  147. if plugin['position'] == 'after_conv1'
  148. ]
  149. self.after_conv2_plugins = [
  150. plugin['cfg'] for plugin in plugins
  151. if plugin['position'] == 'after_conv2'
  152. ]
  153. self.after_conv3_plugins = [
  154. plugin['cfg'] for plugin in plugins
  155. if plugin['position'] == 'after_conv3'
  156. ]
  157. if self.style == 'pytorch':
  158. self.conv1_stride = 1
  159. self.conv2_stride = stride
  160. else:
  161. self.conv1_stride = stride
  162. self.conv2_stride = 1
  163. self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
  164. self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
  165. self.norm3_name, norm3 = build_norm_layer(
  166. norm_cfg, planes * self.expansion, postfix=3)
  167. self.conv1 = build_conv_layer(
  168. conv_cfg,
  169. inplanes,
  170. planes,
  171. kernel_size=1,
  172. stride=self.conv1_stride,
  173. bias=False)
  174. self.add_module(self.norm1_name, norm1)
  175. fallback_on_stride = False
  176. if self.with_dcn:
  177. fallback_on_stride = dcn.pop('fallback_on_stride', False)
  178. if not self.with_dcn or fallback_on_stride:
  179. self.conv2 = build_conv_layer(
  180. conv_cfg,
  181. planes,
  182. planes,
  183. kernel_size=3,
  184. stride=self.conv2_stride,
  185. padding=dilation,
  186. dilation=dilation,
  187. bias=False)
  188. else:
  189. assert self.conv_cfg is None, 'conv_cfg must be None for DCN'
  190. self.conv2 = build_conv_layer(
  191. dcn,
  192. planes,
  193. planes,
  194. kernel_size=3,
  195. stride=self.conv2_stride,
  196. padding=dilation,
  197. dilation=dilation,
  198. bias=False)
  199. self.add_module(self.norm2_name, norm2)
  200. self.conv3 = build_conv_layer(
  201. conv_cfg,
  202. planes,
  203. planes * self.expansion,
  204. kernel_size=1,
  205. bias=False)
  206. self.add_module(self.norm3_name, norm3)
  207. self.relu = nn.ReLU(inplace=True)
  208. self.downsample = downsample
  209. if self.with_plugins:
  210. self.after_conv1_plugin_names = self.make_block_plugins(
  211. planes, self.after_conv1_plugins)
  212. self.after_conv2_plugin_names = self.make_block_plugins(
  213. planes, self.after_conv2_plugins)
  214. self.after_conv3_plugin_names = self.make_block_plugins(
  215. planes * self.expansion, self.after_conv3_plugins)
  216. def make_block_plugins(self, in_channels, plugins):
  217. """make plugins for block.
  218. Args:
  219. in_channels (int): Input channels of plugin.
  220. plugins (list[dict]): List of plugins cfg to build.
  221. Returns:
  222. list[str]: List of the names of plugin.
  223. """
  224. assert isinstance(plugins, list)
  225. plugin_names = []
  226. for plugin in plugins:
  227. plugin = plugin.copy()
  228. name, layer = build_plugin_layer(
  229. plugin,
  230. in_channels=in_channels,
  231. postfix=plugin.pop('postfix', ''))
  232. assert not hasattr(self, name), f'duplicate plugin {name}'
  233. self.add_module(name, layer)
  234. plugin_names.append(name)
  235. return plugin_names
  236. def forward_plugin(self, x, plugin_names):
  237. out = x
  238. for name in plugin_names:
  239. out = getattr(self, name)(out)
  240. return out
  241. @property
  242. def norm1(self):
  243. """nn.Module: normalization layer after the first convolution layer"""
  244. return getattr(self, self.norm1_name)
  245. @property
  246. def norm2(self):
  247. """nn.Module: normalization layer after the second convolution layer"""
  248. return getattr(self, self.norm2_name)
  249. @property
  250. def norm3(self):
  251. """nn.Module: normalization layer after the third convolution layer"""
  252. return getattr(self, self.norm3_name)
  253. def forward(self, x):
  254. """Forward function."""
  255. def _inner_forward(x):
  256. identity = x
  257. out = self.conv1(x)
  258. out = self.norm1(out)
  259. out = self.relu(out)
  260. if self.with_plugins:
  261. out = self.forward_plugin(out, self.after_conv1_plugin_names)
  262. out = self.conv2(out)
  263. out = self.norm2(out)
  264. out = self.relu(out)
  265. if self.with_plugins:
  266. out = self.forward_plugin(out, self.after_conv2_plugin_names)
  267. out = self.conv3(out)
  268. out = self.norm3(out)
  269. if self.with_plugins:
  270. out = self.forward_plugin(out, self.after_conv3_plugin_names)
  271. if self.downsample is not None:
  272. identity = self.downsample(x)
  273. out += identity
  274. return out
  275. if self.with_cp and x.requires_grad:
  276. out = cp.checkpoint(_inner_forward, x)
  277. else:
  278. out = _inner_forward(x)
  279. out = self.relu(out)
  280. return out
  281. @MODELS.register_module()
  282. class ResNet(BaseModule):
  283. """ResNet backbone.
  284. Args:
  285. depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.
  286. stem_channels (int | None): Number of stem channels. If not specified,
  287. it will be the same as `base_channels`. Default: None.
  288. base_channels (int): Number of base channels of res layer. Default: 64.
  289. in_channels (int): Number of input image channels. Default: 3.
  290. num_stages (int): Resnet stages. Default: 4.
  291. strides (Sequence[int]): Strides of the first block of each stage.
  292. dilations (Sequence[int]): Dilation of each stage.
  293. out_indices (Sequence[int]): Output from which stages.
  294. style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
  295. layer is the 3x3 conv layer, otherwise the stride-two layer is
  296. the first 1x1 conv layer.
  297. deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv
  298. avg_down (bool): Use AvgPool instead of stride conv when
  299. downsampling in the bottleneck.
  300. frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
  301. -1 means not freezing any parameters.
  302. norm_cfg (dict): Dictionary to construct and config norm layer.
  303. norm_eval (bool): Whether to set norm layers to eval mode, namely,
  304. freeze running stats (mean and var). Note: Effect on Batch Norm
  305. and its variants only.
  306. plugins (list[dict]): List of plugins for stages, each dict contains:
  307. - cfg (dict, required): Cfg dict to build plugin.
  308. - position (str, required): Position inside block to insert
  309. plugin, options are 'after_conv1', 'after_conv2', 'after_conv3'.
  310. - stages (tuple[bool], optional): Stages to apply plugin, length
  311. should be same as 'num_stages'.
  312. with_cp (bool): Use checkpoint or not. Using checkpoint will save some
  313. memory while slowing down the training speed.
  314. zero_init_residual (bool): Whether to use zero init for last norm layer
  315. in resblocks to let them behave as identity.
  316. pretrained (str, optional): model pretrained path. Default: None
  317. init_cfg (dict or list[dict], optional): Initialization config dict.
  318. Default: None
  319. Example:
  320. >>> from mmdet.models import ResNet
  321. >>> import torch
  322. >>> self = ResNet(depth=18)
  323. >>> self.eval()
  324. >>> inputs = torch.rand(1, 3, 32, 32)
  325. >>> level_outputs = self.forward(inputs)
  326. >>> for level_out in level_outputs:
  327. ... print(tuple(level_out.shape))
  328. (1, 64, 8, 8)
  329. (1, 128, 4, 4)
  330. (1, 256, 2, 2)
  331. (1, 512, 1, 1)
  332. """
  333. arch_settings = {
  334. 18: (BasicBlock, (2, 2, 2, 2)),
  335. 34: (BasicBlock, (3, 4, 6, 3)),
  336. 50: (Bottleneck, (3, 4, 6, 3)),
  337. 101: (Bottleneck, (3, 4, 23, 3)),
  338. 152: (Bottleneck, (3, 8, 36, 3))
  339. }
  340. def __init__(self,
  341. depth,
  342. in_channels=1,
  343. stem_channels=None,
  344. base_channels=64,
  345. num_stages=4,
  346. strides=(1, 2, 2, 2),
  347. dilations=(1, 1, 1, 1),
  348. out_indices=(0, 1, 2, 3),
  349. style='pytorch',
  350. #for presnet we use deep_stem and avg_down
  351. deep_stem=True,
  352. avg_down=True,
  353. frozen_stages=-1,
  354. conv_cfg=None,
  355. norm_cfg=dict(type='BN', requires_grad=True),
  356. norm_eval=True,
  357. dcn=None,
  358. stage_with_dcn=(False, False, False, False),
  359. plugins=None,
  360. with_cp=False,
  361. zero_init_residual=True,
  362. pretrained=None,
  363. init_cfg=None):
  364. super(ResNet, self).__init__(init_cfg)
  365. self.zero_init_residual = zero_init_residual
  366. if depth not in self.arch_settings:
  367. raise KeyError(f'invalid depth {depth} for resnet')
  368. block_init_cfg = None
  369. assert not (init_cfg and pretrained), \
  370. 'init_cfg and pretrained cannot be specified at the same time'
  371. if isinstance(pretrained, str):
  372. warnings.warn('DeprecationWarning: pretrained is deprecated, '
  373. 'please use "init_cfg" instead')
  374. self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
  375. elif pretrained is None:
  376. if init_cfg is None:
  377. self.init_cfg = [
  378. dict(type='Kaiming', layer='Conv2d'),
  379. dict(
  380. type='Constant',
  381. val=1,
  382. layer=['_BatchNorm', 'GroupNorm'])
  383. ]
  384. block = self.arch_settings[depth][0]
  385. if self.zero_init_residual:
  386. if block is BasicBlock:
  387. block_init_cfg = dict(
  388. type='Constant',
  389. val=0,
  390. override=dict(name='norm2'))
  391. elif block is Bottleneck:
  392. block_init_cfg = dict(
  393. type='Constant',
  394. val=0,
  395. override=dict(name='norm3'))
  396. else:
  397. raise TypeError('pretrained must be a str or None')
  398. self.depth = depth
  399. if stem_channels is None:
  400. stem_channels = base_channels
  401. self.stem_channels = stem_channels
  402. self.base_channels = base_channels
  403. self.num_stages = num_stages
  404. assert num_stages >= 1 and num_stages <= 4
  405. self.strides = strides
  406. self.dilations = dilations
  407. assert len(strides) == len(dilations) == num_stages
  408. self.out_indices = out_indices
  409. assert max(out_indices) < num_stages
  410. self.style = style
  411. self.deep_stem = deep_stem
  412. self.avg_down = avg_down
  413. self.frozen_stages = frozen_stages
  414. self.conv_cfg = conv_cfg
  415. self.norm_cfg = norm_cfg
  416. self.with_cp = with_cp
  417. self.norm_eval = norm_eval
  418. self.dcn = dcn
  419. self.stage_with_dcn = stage_with_dcn
  420. if dcn is not None:
  421. assert len(stage_with_dcn) == num_stages
  422. self.plugins = plugins
  423. self.block, stage_blocks = self.arch_settings[depth]
  424. self.stage_blocks = stage_blocks[:num_stages]
  425. self.inplanes = stem_channels
  426. self._make_stem_layer(in_channels, stem_channels)
  427. self.res_layers = []
  428. for i, num_blocks in enumerate(self.stage_blocks):
  429. stride = strides[i]
  430. dilation = dilations[i]
  431. dcn = self.dcn if self.stage_with_dcn[i] else None
  432. if plugins is not None:
  433. stage_plugins = self.make_stage_plugins(plugins, i)
  434. else:
  435. stage_plugins = None
  436. planes = base_channels * 2**i
  437. res_layer = self.make_res_layer(
  438. block=self.block,
  439. inplanes=self.inplanes,
  440. planes=planes,
  441. num_blocks=num_blocks,
  442. stride=stride,
  443. dilation=dilation,
  444. style=self.style,
  445. avg_down=self.avg_down,
  446. with_cp=with_cp,
  447. conv_cfg=conv_cfg,
  448. norm_cfg=norm_cfg,
  449. dcn=dcn,
  450. plugins=stage_plugins,
  451. init_cfg=block_init_cfg)
  452. self.inplanes = planes * self.block.expansion
  453. layer_name = f'layer{i + 1}'
  454. self.add_module(layer_name, res_layer)
  455. self.res_layers.append(layer_name)
  456. self._freeze_stages()
  457. self.feat_dim = self.block.expansion * base_channels * 2**(
  458. len(self.stage_blocks) - 1)
  459. def make_stage_plugins(self, plugins, stage_idx):
  460. """Make plugins for ResNet ``stage_idx`` th stage.
  461. Currently we support to insert ``context_block``,
  462. ``empirical_attention_block``, ``nonlocal_block`` into the backbone
  463. like ResNet/ResNeXt. They could be inserted after conv1/conv2/conv3 of
  464. Bottleneck.
  465. An example of plugins format could be:
  466. Examples:
  467. >>> plugins=[
  468. ... dict(cfg=dict(type='xxx', arg1='xxx'),
  469. ... stages=(False, True, True, True),
  470. ... position='after_conv2'),
  471. ... dict(cfg=dict(type='yyy'),
  472. ... stages=(True, True, True, True),
  473. ... position='after_conv3'),
  474. ... dict(cfg=dict(type='zzz', postfix='1'),
  475. ... stages=(True, True, True, True),
  476. ... position='after_conv3'),
  477. ... dict(cfg=dict(type='zzz', postfix='2'),
  478. ... stages=(True, True, True, True),
  479. ... position='after_conv3')
  480. ... ]
  481. >>> self = ResNet(depth=18)
  482. >>> stage_plugins = self.make_stage_plugins(plugins, 0)
  483. >>> assert len(stage_plugins) == 3
  484. Suppose ``stage_idx=0``, the structure of blocks in the stage would be:
  485. .. code-block:: none
  486. conv1-> conv2->conv3->yyy->zzz1->zzz2
  487. Suppose 'stage_idx=1', the structure of blocks in the stage would be:
  488. .. code-block:: none
  489. conv1-> conv2->xxx->conv3->yyy->zzz1->zzz2
  490. If stages is missing, the plugin would be applied to all stages.
  491. Args:
  492. plugins (list[dict]): List of plugins cfg to build. The postfix is
  493. required if multiple same type plugins are inserted.
  494. stage_idx (int): Index of stage to build
  495. Returns:
  496. list[dict]: Plugins for current stage
  497. """
  498. stage_plugins = []
  499. for plugin in plugins:
  500. plugin = plugin.copy()
  501. stages = plugin.pop('stages', None)
  502. assert stages is None or len(stages) == self.num_stages
  503. # whether to insert plugin into current stage
  504. if stages is None or stages[stage_idx]:
  505. stage_plugins.append(plugin)
  506. return stage_plugins
  507. def make_res_layer(self, **kwargs):
  508. """Pack all blocks in a stage into a ``ResLayer``."""
  509. return ResLayer(**kwargs)
  510. @property
  511. def norm1(self):
  512. """nn.Module: the normalization layer named "norm1" """
  513. return getattr(self, self.norm1_name)
  514. def _make_stem_layer(self, in_channels, stem_channels):
  515. if self.deep_stem:
  516. self.stem = nn.Sequential(
  517. build_conv_layer(
  518. self.conv_cfg,
  519. in_channels,
  520. stem_channels // 2,
  521. kernel_size=3,
  522. stride=2,
  523. padding=1,
  524. bias=False),
  525. build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
  526. nn.ReLU(inplace=True),
  527. build_conv_layer(
  528. self.conv_cfg,
  529. stem_channels // 2,
  530. stem_channels // 2,
  531. kernel_size=3,
  532. stride=1,
  533. padding=1,
  534. bias=False),
  535. build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
  536. nn.ReLU(inplace=True),
  537. build_conv_layer(
  538. self.conv_cfg,
  539. stem_channels // 2,
  540. stem_channels,
  541. kernel_size=3,
  542. stride=1,
  543. padding=1,
  544. bias=False),
  545. build_norm_layer(self.norm_cfg, stem_channels)[1],
  546. nn.ReLU(inplace=True))
  547. else:
  548. self.conv1 = build_conv_layer(
  549. self.conv_cfg,
  550. in_channels,
  551. stem_channels,
  552. kernel_size=7,
  553. stride=2,
  554. padding=3,
  555. bias=False)
  556. self.norm1_name, norm1 = build_norm_layer(
  557. self.norm_cfg, stem_channels, postfix=1)
  558. self.add_module(self.norm1_name, norm1)
  559. self.relu = nn.ReLU(inplace=True)
  560. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  561. def _freeze_stages(self):
  562. if self.frozen_stages >= 0:
  563. if self.deep_stem:
  564. self.stem.eval()
  565. for param in self.stem.parameters():
  566. param.requires_grad = False
  567. else:
  568. self.norm1.eval()
  569. for m in [self.conv1, self.norm1]:
  570. for param in m.parameters():
  571. param.requires_grad = False
  572. for i in range(1, self.frozen_stages + 1):
  573. m = getattr(self, f'layer{i}')
  574. m.eval()
  575. for param in m.parameters():
  576. param.requires_grad = False
  577. def forward(self, x):
  578. """Forward function."""
  579. if self.deep_stem:
  580. x = self.stem(x)
  581. else:
  582. x = self.conv1(x)
  583. x = self.norm1(x)
  584. x = self.relu(x)
  585. x = self.maxpool(x)
  586. outs = []
  587. for i, layer_name in enumerate(self.res_layers):
  588. res_layer = getattr(self, layer_name)
  589. x = res_layer(x)
  590. if i in self.out_indices:
  591. outs.append(x)
  592. return tuple(outs)
  593. def train(self, mode=True):
  594. """Convert the model into training mode while keep normalization layer
  595. freezed."""
  596. super(ResNet, self).train(mode)
  597. self._freeze_stages()
  598. if mode and self.norm_eval:
  599. for m in self.modules():
  600. # trick: eval have effect on BatchNorm only
  601. if isinstance(m, _BatchNorm):
  602. m.eval()
  603. @MODELS.register_module()
  604. class ResNetV1d(ResNet):
  605. r"""ResNetV1d variant described in `Bag of Tricks
  606. <https://arxiv.org/pdf/1812.01187.pdf>`_.
  607. Compared with default ResNet(ResNetV1b), ResNetV1d replaces the 7x7 conv in
  608. the input stem with three 3x3 convs. And in the downsampling block, a 2x2
  609. avg_pool with stride 2 is added before conv, whose stride is changed to 1.
  610. """
  611. def __init__(self, **kwargs):
  612. super(ResNetV1d, self).__init__(
  613. deep_stem=True, avg_down=True, **kwargs)