mask_head.py 5.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# Copyright (c) 2019 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from paddle import fluid
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.initializer import MSRA
from paddle.fluid.regularizer import L2Decay

from ppdet.core.workspace import register
Y
Yuan Gao 已提交
25
from ppdet.modeling.ops import ConvNorm
26 27 28 29 30 31 32 33 34

__all__ = ['MaskHead']


@register
class MaskHead(object):
    """
    RCNN mask head
    Args:
Y
Yuan Gao 已提交
35 36
        num_convs (int): num of convolutions, 4 for FPN, 1 otherwise
        conv_dim (int): num of channels after first convolution
37 38 39 40 41
        resolution (int): size of the output mask
        dilation (int): dilation rate
        num_classes (int): number of output classes
    """

42 43
    __shared__ = ['num_classes']

44 45
    def __init__(self,
                 num_convs=0,
Y
Yuan Gao 已提交
46
                 conv_dim=256,
47 48
                 resolution=14,
                 dilation=1,
Y
Yuan Gao 已提交
49 50
                 num_classes=81,
                 norm_type=None):
51 52
        super(MaskHead, self).__init__()
        self.num_convs = num_convs
Y
Yuan Gao 已提交
53
        self.conv_dim = conv_dim
54 55 56
        self.resolution = resolution
        self.dilation = dilation
        self.num_classes = num_classes
Y
Yuan Gao 已提交
57
        self.norm_type = norm_type
58

Y
Yuan Gao 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    def _mask_conv_head(self, roi_feat, num_convs, norm_type):
        if norm_type == 'gn':
            for i in range(num_convs):
                layer_name = "mask_inter_feat_" + str(i + 1)
                fan = self.conv_dim * 3 * 3
                initializer = MSRA(uniform=False, fan_in=fan)
                roi_feat = ConvNorm(
                    roi_feat,
                    self.conv_dim,
                    3,
                    act='relu',
                    dilation=self.dilation,
                    initializer=initializer,
                    norm_type=self.norm_type,
                    name=layer_name,
                    norm_name=layer_name)
        else:
            for i in range(num_convs):
                layer_name = "mask_inter_feat_" + str(i + 1)
                fan = self.conv_dim * 3 * 3
                initializer = MSRA(uniform=False, fan_in=fan)
                roi_feat = fluid.layers.conv2d(
                    input=roi_feat,
                    num_filters=self.conv_dim,
                    filter_size=3,
                    padding=1 * self.dilation,
                    act='relu',
                    stride=1,
                    dilation=self.dilation,
                    name=layer_name,
                    param_attr=ParamAttr(
                        name=layer_name + '_w', initializer=initializer),
                    bias_attr=ParamAttr(
                        name=layer_name + '_b',
                        learning_rate=2.,
                        regularizer=L2Decay(0.)))
95 96 97
        fan = roi_feat.shape[1] * 2 * 2
        feat = fluid.layers.conv2d_transpose(
            input=roi_feat,
Y
Yuan Gao 已提交
98
            num_filters=self.conv_dim,
99 100 101 102 103 104 105 106 107 108 109 110 111 112
            filter_size=2,
            stride=2,
            act='relu',
            param_attr=ParamAttr(
                name='conv5_mask_w',
                initializer=MSRA(
                    uniform=False, fan_in=fan)),
            bias_attr=ParamAttr(
                name='conv5_mask_b', learning_rate=2., regularizer=L2Decay(0.)))
        return feat

    def _get_output(self, roi_feat):
        class_num = self.num_classes
        # configure the conv number for FPN if necessary
Y
Yuan Gao 已提交
113 114
        head_feat = self._mask_conv_head(roi_feat, self.num_convs,
                                         self.norm_type)
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        fan = class_num
        mask_logits = fluid.layers.conv2d(
            input=head_feat,
            num_filters=class_num,
            filter_size=1,
            act=None,
            param_attr=ParamAttr(
                name='mask_fcn_logits_w',
                initializer=MSRA(
                    uniform=False, fan_in=fan)),
            bias_attr=ParamAttr(
                name="mask_fcn_logits_b",
                learning_rate=2.,
                regularizer=L2Decay(0.)))
        return mask_logits

    def get_loss(self, roi_feat, mask_int32):
        mask_logits = self._get_output(roi_feat)
        num_classes = self.num_classes
        resolution = self.resolution
        dim = num_classes * resolution * resolution
        mask_logits = fluid.layers.reshape(mask_logits, (-1, dim))

        mask_label = fluid.layers.cast(x=mask_int32, dtype='float32')
        mask_label.stop_gradient = True
        loss_mask = fluid.layers.sigmoid_cross_entropy_with_logits(
            x=mask_logits, label=mask_label, ignore_index=-1, normalize=True)
        loss_mask = fluid.layers.reduce_sum(loss_mask, name='loss_mask')
        return {'loss_mask': loss_mask}

    def get_prediction(self, roi_feat, bbox_pred):
        """
        Get prediction mask in test stage.

        Args:
            roi_feat (Variable): RoI feature from RoIExtractor.
            bbox_pred (Variable): predicted bbox.

        Returns:
            mask_pred (Variable): Prediction mask with shape
                [N, num_classes, resolution, resolution].
        """
        mask_logits = self._get_output(roi_feat)
        mask_prob = fluid.layers.sigmoid(mask_logits)
        mask_prob = fluid.layers.lod_reset(mask_prob, bbox_pred)
        return mask_prob