pspnet.py 8.7 KB
Newer Older
M
michaelowenliu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import paddle.nn.functional as F
from paddle import fluid
from paddle.fluid.dygraph import Conv2D

from dygraph.cvlibs import manager
from dygraph.models import model_utils
from dygraph.models.architectures import layer_utils
from dygraph.utils import utils


class PSPNet(fluid.dygraph.Layer):
    """
    The PSPNet implementation

C
chenguowei01 已提交
31 32
    The orginal artile refers to
        Zhao, Hengshuang, et al. "Pyramid scene parsing network."
M
michaelowenliu 已提交
33 34 35 36
        Proceedings of the IEEE conference on computer vision and pattern recognition. 2017.
        (https://openaccess.thecvf.com/content_cvpr_2017/papers/Zhao_Pyramid_Scene_Parsing_CVPR_2017_paper.pdf)

    Args:
C
chenguowei01 已提交
37 38 39
        num_classes (int): the unique number of target classes.

        backbone (Paddle.nn.Layer): backbone name, currently support Resnet50/101.
M
michaelowenliu 已提交
40

C
chenguowei01 已提交
41
        model_pretrained (str): the path of pretrained model.
M
michaelowenliu 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

        output_stride (int): the ratio of input size and final feature size. Default 16.

        backbone_indices (tuple): two values in the tuple indicte the indices of output of backbone.
                        the first index will be taken as a deep-supervision feature in auxiliary layer;
                        the second one will be taken as input of Pyramid Pooling Module (PPModule).
                        Usually backbone consists of four downsampling stage, and return an output of
                        each stage, so we set default (2, 3), which means taking feature map of the third
                        stage (res4b22) in backbone, and feature map of the fourth stage (res5c) as input of PPModule.

        backbone_channels (tuple): the same length with "backbone_indices". It indicates the channels of corresponding index.

        pp_out_channels (int): output channels after Pyramid Pooling Module. Default to 1024.

        bin_sizes (tuple): the out size of pooled feature maps. Default to (1,2,3,6).

        enable_auxiliary_loss (bool): a bool values indictes whether adding auxiliary loss. Default to True.

        ignore_index (int): the value of ground-truth mask would be ignored while doing evaluation. Default to 255.
    """

    def __init__(self,
C
chenguowei01 已提交
64
                 num_classes,
M
michaelowenliu 已提交
65
                 backbone,
C
chenguowei01 已提交
66
                 model_pretrained=None,
M
michaelowenliu 已提交
67 68 69 70 71 72
                 output_stride=16,
                 backbone_indices=(2, 3),
                 backbone_channels=(1024, 2048),
                 pp_out_channels=1024,
                 bin_sizes=(1, 2, 3, 6),
                 enable_auxiliary_loss=True,
C
chenguowei01 已提交
73
                 ignore_index=255):
M
michaelowenliu 已提交
74 75

        super(PSPNet, self).__init__()
C
chenguowei01 已提交
76 77 78
        # self.backbone = manager.BACKBONES[backbone](output_stride=output_stride,
        #                                             multi_grid=(1, 1, 1))
        self.backbone = backbone
M
michaelowenliu 已提交
79 80
        self.backbone_indices = backbone_indices

C
chenguowei01 已提交
81 82 83 84
        self.psp_module = PPModule(
            in_channels=backbone_channels[1],
            out_channels=pp_out_channels,
            bin_sizes=bin_sizes)
M
michaelowenliu 已提交
85

C
chenguowei01 已提交
86 87 88 89
        self.conv = Conv2D(
            num_channels=pp_out_channels,
            num_filters=num_classes,
            filter_size=1)
M
michaelowenliu 已提交
90 91

        if enable_auxiliary_loss:
C
chenguowei01 已提交
92 93
            self.fcn_head = model_utils.FCNHead(
                in_channels=backbone_channels[0], out_channels=num_classes)
M
michaelowenliu 已提交
94 95 96 97

        self.enable_auxiliary_loss = enable_auxiliary_loss
        self.ignore_index = ignore_index

C
chenguowei01 已提交
98
        self.init_weight(model_pretrained)
M
michaelowenliu 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112

    def forward(self, input, label=None):

        _, feat_list = self.backbone(input)

        x = feat_list[self.backbone_indices[1]]
        x = self.psp_module(x)
        x = F.dropout(x, dropout_prob=0.1)
        logit = self.conv(x)
        logit = fluid.layers.resize_bilinear(logit, input.shape[2:])

        if self.enable_auxiliary_loss:
            auxiliary_feat = feat_list[self.backbone_indices[0]]
            auxiliary_logit = self.fcn_head(auxiliary_feat)
C
chenguowei01 已提交
113 114
            auxiliary_logit = fluid.layers.resize_bilinear(
                auxiliary_logit, input.shape[2:])
M
michaelowenliu 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

        if self.training:
            loss = model_utils.get_loss(logit, label)
            if self.enable_auxiliary_loss:
                auxiliary_loss = model_utils.get_loss(auxiliary_logit, label)
                loss += (0.4 * auxiliary_loss)
            return loss

        else:
            pred, score_map = model_utils.get_pred_score_map(logit)
            return pred, score_map

    def init_weight(self, pretrained_model=None):
        """
        Initialize the parameters of model parts.
        Args:
C
chenguowei01 已提交
131
            pretrained_model ([str], optional): the path of pretrained model. Defaults to None.
M
michaelowenliu 已提交
132 133 134
        """
        if pretrained_model is not None:
            if os.path.exists(pretrained_model):
C
chenguowei01 已提交
135 136 137 138
                utils.load_pretrained_model(self, pretrained_model)
            else:
                raise Exception('Pretrained model is not found: {}'.format(
                    pretrained_model))
M
michaelowenliu 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157


class PPModule(fluid.dygraph.Layer):
    """
    Pyramid pooling module

    Args:
        in_channels (int): the number of intput channels to pyramid pooling module.

        out_channels (int): the number of output channels after pyramid pooling module.

        bin_sizes (tuple): the out size of pooled feature maps. Default to (1,2,3,6).
    """

    def __init__(self, in_channels, out_channels, bin_sizes=(1, 2, 3, 6)):
        super(PPModule, self).__init__()
        self.bin_sizes = bin_sizes

        # we use dimension reduction after pooling mentioned in original implementation.
C
chenguowei01 已提交
158 159
        self.stages = fluid.dygraph.LayerList(
            [self._make_stage(in_channels, size) for size in bin_sizes])
M
michaelowenliu 已提交
160

C
chenguowei01 已提交
161 162 163 164 165
        self.conv_bn_relu2 = layer_utils.ConvBnRelu(
            num_channels=in_channels * 2,
            num_filters=out_channels,
            filter_size=3,
            padding=1)
M
michaelowenliu 已提交
166 167 168 169 170 171

    def _make_stage(self, in_channels, size):
        """
        Create one pooling layer.

        In our implementation, we adopt the same dimention reduction as the original paper that might be
C
chenguowei01 已提交
172
        slightly different with other implementations.
M
michaelowenliu 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

        After pooling, the channels are reduced to 1/len(bin_sizes) immediately, while some other implementations
        keep the channels to be same.


        Args:
            in_channels (int): the number of intput channels to pyramid pooling module.

            size (int): the out size of the pooled layer.

        Returns:
            conv (tensor): a tensor after Pyramid Pooling Module
        """

        # this paddle version does not support AdaptiveAvgPool2d, so skip it here.
        # prior = nn.AdaptiveAvgPool2d(output_size=(size, size))
C
chenguowei01 已提交
189 190 191 192
        conv = layer_utils.ConvBnRelu(
            num_channels=in_channels,
            num_filters=in_channels // len(self.bin_sizes),
            filter_size=1)
M
michaelowenliu 已提交
193 194 195 196 197 198 199

        return conv

    def forward(self, input):
        cat_layers = []
        for i, stage in enumerate(self.stages):
            size = self.bin_sizes[i]
C
chenguowei01 已提交
200 201
            x = fluid.layers.adaptive_pool2d(
                input, pool_size=(size, size), pool_type="max")
M
michaelowenliu 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214
            x = stage(x)
            x = fluid.layers.resize_bilinear(x, out_shape=input.shape[2:])
            cat_layers.append(x)
        cat_layers = [input] + cat_layers[::-1]
        cat = fluid.layers.concat(cat_layers, axis=1)
        out = self.conv_bn_relu2(cat)

        return out


@manager.MODELS.add_component
def pspnet_resnet101_vd(*args, **kwargs):
    pretrained_model = None
C
chenguowei01 已提交
215 216
    return PSPNet(
        backbone='ResNet101_vd', pretrained_model=pretrained_model, **kwargs)
M
michaelowenliu 已提交
217 218 219 220 221


@manager.MODELS.add_component
def pspnet_resnet101_vd_os8(*args, **kwargs):
    pretrained_model = None
C
chenguowei01 已提交
222 223 224 225 226
    return PSPNet(
        backbone='ResNet101_vd',
        output_stride=8,
        pretrained_model=pretrained_model,
        **kwargs)
M
michaelowenliu 已提交
227 228 229 230 231


@manager.MODELS.add_component
def pspnet_resnet50_vd(*args, **kwargs):
    pretrained_model = None
C
chenguowei01 已提交
232 233
    return PSPNet(
        backbone='ResNet50_vd', pretrained_model=pretrained_model, **kwargs)
M
michaelowenliu 已提交
234 235 236 237 238


@manager.MODELS.add_component
def pspnet_resnet50_vd_os8(*args, **kwargs):
    pretrained_model = None
C
chenguowei01 已提交
239 240 241 242 243
    return PSPNet(
        backbone='ResNet50_vd',
        output_stride=8,
        pretrained_model=pretrained_model,
        **kwargs)