conv_upsample.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import torch.nn.functional as F
  3. from mmcv.cnn import ConvModule
  4. from mmengine.model import BaseModule, ModuleList
  5. class ConvUpsample(BaseModule):
  6. """ConvUpsample performs 2x upsampling after Conv.
  7. There are several `ConvModule` layers. In the first few layers, upsampling
  8. will be applied after each layer of convolution. The number of upsampling
  9. must be no more than the number of ConvModule layers.
  10. Args:
  11. in_channels (int): Number of channels in the input feature map.
  12. inner_channels (int): Number of channels produced by the convolution.
  13. num_layers (int): Number of convolution layers.
  14. num_upsample (int | optional): Number of upsampling layer. Must be no
  15. more than num_layers. Upsampling will be applied after the first
  16. ``num_upsample`` layers of convolution. Default: ``num_layers``.
  17. conv_cfg (dict): Config dict for convolution layer. Default: None,
  18. which means using conv2d.
  19. norm_cfg (dict): Config dict for normalization layer. Default: None.
  20. init_cfg (dict): Config dict for initialization. Default: None.
  21. kwargs (key word augments): Other augments used in ConvModule.
  22. """
  23. def __init__(self,
  24. in_channels,
  25. inner_channels,
  26. num_layers=1,
  27. num_upsample=None,
  28. conv_cfg=None,
  29. norm_cfg=None,
  30. init_cfg=None,
  31. **kwargs):
  32. super(ConvUpsample, self).__init__(init_cfg)
  33. if num_upsample is None:
  34. num_upsample = num_layers
  35. assert num_upsample <= num_layers, \
  36. f'num_upsample({num_upsample})must be no more than ' \
  37. f'num_layers({num_layers})'
  38. self.num_layers = num_layers
  39. self.num_upsample = num_upsample
  40. self.conv = ModuleList()
  41. for i in range(num_layers):
  42. self.conv.append(
  43. ConvModule(
  44. in_channels,
  45. inner_channels,
  46. 3,
  47. padding=1,
  48. stride=1,
  49. conv_cfg=conv_cfg,
  50. norm_cfg=norm_cfg,
  51. **kwargs))
  52. in_channels = inner_channels
  53. def forward(self, x):
  54. num_upsample = self.num_upsample
  55. for i in range(self.num_layers):
  56. x = self.conv[i](x)
  57. if num_upsample > 0:
  58. num_upsample -= 1
  59. x = F.interpolate(
  60. x, scale_factor=2, mode='bilinear', align_corners=False)
  61. return x