pyramid_pool.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle
  15. import paddle.nn.functional as F
  16. from paddle import nn
  17. from paddlex.paddleseg.models import layers
  18. class ASPPModule(nn.Layer):
  19. """
  20. Atrous Spatial Pyramid Pooling.
  21. Args:
  22. aspp_ratios (tuple): The dilation rate using in ASSP module.
  23. in_channels (int): The number of input channels.
  24. out_channels (int): The number of output channels.
  25. align_corners (bool): An argument of F.interpolate. It should be set to False when the output size of feature
  26. is even, e.g. 1024x512, otherwise it is True, e.g. 769x769.
  27. use_sep_conv (bool, optional): If using separable conv in ASPP module. Default: False.
  28. image_pooling (bool, optional): If augmented with image-level features. Default: False
  29. """
  30. def __init__(self,
  31. aspp_ratios,
  32. in_channels,
  33. out_channels,
  34. align_corners,
  35. use_sep_conv=False,
  36. image_pooling=False):
  37. super().__init__()
  38. self.align_corners = align_corners
  39. self.aspp_blocks = nn.LayerList()
  40. for ratio in aspp_ratios:
  41. if use_sep_conv and ratio > 1:
  42. conv_func = layers.SeparableConvBNReLU
  43. else:
  44. conv_func = layers.ConvBNReLU
  45. block = conv_func(
  46. in_channels=in_channels,
  47. out_channels=out_channels,
  48. kernel_size=1 if ratio == 1 else 3,
  49. dilation=ratio,
  50. padding=0 if ratio == 1 else ratio)
  51. self.aspp_blocks.append(block)
  52. out_size = len(self.aspp_blocks)
  53. if image_pooling:
  54. self.global_avg_pool = nn.Sequential(
  55. nn.AdaptiveAvgPool2D(output_size=(1, 1)),
  56. layers.ConvBNReLU(
  57. in_channels, out_channels, kernel_size=1, bias_attr=False))
  58. out_size += 1
  59. self.image_pooling = image_pooling
  60. self.conv_bn_relu = layers.ConvBNReLU(
  61. in_channels=out_channels * out_size,
  62. out_channels=out_channels,
  63. kernel_size=1)
  64. self.dropout = nn.Dropout(p=0.1) # drop rate
  65. def forward(self, x):
  66. outputs = []
  67. interpolate_shape = paddle.shape(x)[2:]
  68. for block in self.aspp_blocks:
  69. y = block(x)
  70. y = F.interpolate(
  71. y,
  72. interpolate_shape,
  73. mode='bilinear',
  74. align_corners=self.align_corners)
  75. outputs.append(y)
  76. if self.image_pooling:
  77. img_avg = self.global_avg_pool(x)
  78. img_avg = F.interpolate(
  79. img_avg,
  80. interpolate_shape,
  81. mode='bilinear',
  82. align_corners=self.align_corners)
  83. outputs.append(img_avg)
  84. x = paddle.concat(outputs, axis=1)
  85. x = self.conv_bn_relu(x)
  86. x = self.dropout(x)
  87. return x
  88. class PPModule(nn.Layer):
  89. """
  90. Pyramid pooling module originally in PSPNet.
  91. Args:
  92. in_channels (int): The number of intput channels to pyramid pooling module.
  93. out_channels (int): The number of output channels after pyramid pooling module.
  94. bin_sizes (tuple, optional): The out size of pooled feature maps. Default: (1, 2, 3, 6).
  95. dim_reduction (bool, optional): A bool value represents if reducing dimension after pooling. Default: True.
  96. align_corners (bool): An argument of F.interpolate. It should be set to False when the output size of feature
  97. is even, e.g. 1024x512, otherwise it is True, e.g. 769x769.
  98. """
  99. def __init__(self, in_channels, out_channels, bin_sizes, dim_reduction,
  100. align_corners):
  101. super().__init__()
  102. self.bin_sizes = bin_sizes
  103. inter_channels = in_channels
  104. if dim_reduction:
  105. inter_channels = in_channels // len(bin_sizes)
  106. # we use dimension reduction after pooling mentioned in original implementation.
  107. self.stages = nn.LayerList([
  108. self._make_stage(in_channels, inter_channels, size)
  109. for size in bin_sizes
  110. ])
  111. self.conv_bn_relu2 = layers.ConvBNReLU(
  112. in_channels=in_channels + inter_channels * len(bin_sizes),
  113. out_channels=out_channels,
  114. kernel_size=3,
  115. padding=1)
  116. self.align_corners = align_corners
  117. def _make_stage(self, in_channels, out_channels, size):
  118. """
  119. Create one pooling layer.
  120. In our implementation, we adopt the same dimension reduction as the original paper that might be
  121. slightly different with other implementations.
  122. After pooling, the channels are reduced to 1/len(bin_sizes) immediately, while some other implementations
  123. keep the channels to be same.
  124. Args:
  125. in_channels (int): The number of intput channels to pyramid pooling module.
  126. size (int): The out size of the pooled layer.
  127. Returns:
  128. conv (Tensor): A tensor after Pyramid Pooling Module.
  129. """
  130. prior = nn.AdaptiveAvgPool2D(output_size=(size, size))
  131. conv = layers.ConvBNReLU(
  132. in_channels=in_channels, out_channels=out_channels, kernel_size=1)
  133. return nn.Sequential(prior, conv)
  134. def forward(self, input):
  135. cat_layers = []
  136. for stage in self.stages:
  137. x = stage(input)
  138. x = F.interpolate(
  139. x,
  140. paddle.shape(input)[2:],
  141. mode='bilinear',
  142. align_corners=self.align_corners)
  143. cat_layers.append(x)
  144. cat_layers = [input] + cat_layers[::-1]
  145. cat = paddle.concat(cat_layers, axis=1)
  146. out = self.conv_bn_relu2(cat)
  147. return out