pspnet.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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.nn as nn
  15. import paddle.nn.functional as F
  16. import paddle
  17. from paddlex.paddleseg.cvlibs import manager
  18. from paddlex.paddleseg.models import layers
  19. from paddlex.paddleseg.utils import utils
  20. @manager.MODELS.add_component
  21. class PSPNet(nn.Layer):
  22. """
  23. The PSPNet implementation based on PaddlePaddle.
  24. The original article refers to
  25. Zhao, Hengshuang, et al. "Pyramid scene parsing network"
  26. (https://openaccess.thecvf.com/content_cvpr_2017/papers/Zhao_Pyramid_Scene_Parsing_CVPR_2017_paper.pdf).
  27. Args:
  28. num_classes (int): The unique number of target classes.
  29. backbone (Paddle.nn.Layer): Backbone network, currently support Resnet50/101.
  30. backbone_indices (tuple, optional): Two values in the tuple indicate the indices of output of backbone.
  31. pp_out_channels (int, optional): The output channels after Pyramid Pooling Module. Default: 1024.
  32. bin_sizes (tuple, optional): The out size of pooled feature maps. Default: (1,2,3,6).
  33. enable_auxiliary_loss (bool, optional): A bool value indicates whether adding auxiliary loss. Default: True.
  34. align_corners (bool, optional): An argument of F.interpolate. It should be set to False when the feature size is even,
  35. e.g. 1024x512, otherwise it is True, e.g. 769x769. Default: False.
  36. pretrained (str, optional): The path or url of pretrained model. Default: None.
  37. """
  38. def __init__(self,
  39. num_classes,
  40. backbone,
  41. backbone_indices=(2, 3),
  42. pp_out_channels=1024,
  43. bin_sizes=(1, 2, 3, 6),
  44. enable_auxiliary_loss=True,
  45. align_corners=False,
  46. pretrained=None):
  47. super().__init__()
  48. self.backbone = backbone
  49. backbone_channels = [
  50. backbone.feat_channels[i] for i in backbone_indices
  51. ]
  52. self.head = PSPNetHead(num_classes, backbone_indices, backbone_channels,
  53. pp_out_channels, bin_sizes,
  54. enable_auxiliary_loss, align_corners)
  55. self.align_corners = align_corners
  56. self.pretrained = pretrained
  57. self.init_weight()
  58. def forward(self, x):
  59. feat_list = self.backbone(x)
  60. logit_list = self.head(feat_list)
  61. return [
  62. F.interpolate(
  63. logit,
  64. paddle.shape(x)[2:],
  65. mode='bilinear',
  66. align_corners=self.align_corners) for logit in logit_list
  67. ]
  68. def init_weight(self):
  69. if self.pretrained is not None:
  70. utils.load_entire_model(self, self.pretrained)
  71. class PSPNetHead(nn.Layer):
  72. """
  73. The PSPNetHead implementation.
  74. Args:
  75. num_classes (int): The unique number of target classes.
  76. backbone_indices (tuple): Two values in the tuple indicate the indices of output of backbone.
  77. The first index will be taken as a deep-supervision feature in auxiliary layer;
  78. the second one will be taken as input of Pyramid Pooling Module (PPModule).
  79. Usually backbone consists of four downsampling stage, and return an output of
  80. each stage. If we set it as (2, 3) in ResNet, that means taking feature map of the third
  81. stage (res4b22) in backbone, and feature map of the fourth stage (res5c) as input of PPModule.
  82. backbone_channels (tuple): The same length with "backbone_indices". It indicates the channels of corresponding index.
  83. pp_out_channels (int): The output channels after Pyramid Pooling Module.
  84. bin_sizes (tuple): The out size of pooled feature maps.
  85. enable_auxiliary_loss (bool, optional): A bool value indicates whether adding auxiliary loss. Default: True.
  86. align_corners (bool): An argument of F.interpolate. It should be set to False when the output size of feature
  87. is even, e.g. 1024x512, otherwise it is True, e.g. 769x769.
  88. """
  89. def __init__(self, num_classes, backbone_indices, backbone_channels,
  90. pp_out_channels, bin_sizes, enable_auxiliary_loss,
  91. align_corners):
  92. super().__init__()
  93. self.backbone_indices = backbone_indices
  94. self.psp_module = layers.PPModule(
  95. in_channels=backbone_channels[1],
  96. out_channels=pp_out_channels,
  97. bin_sizes=bin_sizes,
  98. dim_reduction=True,
  99. align_corners=align_corners)
  100. self.dropout = nn.Dropout(p=0.1) # dropout_prob
  101. self.conv = nn.Conv2D(
  102. in_channels=pp_out_channels,
  103. out_channels=num_classes,
  104. kernel_size=1)
  105. if enable_auxiliary_loss:
  106. self.auxlayer = layers.AuxLayer(
  107. in_channels=backbone_channels[0],
  108. inter_channels=backbone_channels[0] // 4,
  109. out_channels=num_classes)
  110. self.enable_auxiliary_loss = enable_auxiliary_loss
  111. def forward(self, feat_list):
  112. logit_list = []
  113. x = feat_list[self.backbone_indices[1]]
  114. x = self.psp_module(x)
  115. x = self.dropout(x)
  116. logit = self.conv(x)
  117. logit_list.append(logit)
  118. if self.enable_auxiliary_loss:
  119. auxiliary_feat = feat_list[self.backbone_indices[0]]
  120. auxiliary_logit = self.auxlayer(auxiliary_feat)
  121. logit_list.append(auxiliary_logit)
  122. return logit_list