cascade_head.py 11.3 KB
Newer Older
W
wangguanzhong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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 paddle
import paddle.nn as nn
import paddle.nn.functional as F
M
Manuel Garcia 已提交
18
from paddle.nn.initializer import Normal
W
wangguanzhong 已提交
19

M
Manuel Garcia 已提交
20
from ppdet.core.workspace import register
F
Feng Ni 已提交
21
from .bbox_head import BBoxHead, TwoFCHead, XConvNormHead
W
wangguanzhong 已提交
22 23
from .roi_extractor import RoIAlign
from ..shape_spec import ShapeSpec
M
Manuel Garcia 已提交
24
from ..bbox_utils import delta2bbox, clip_bbox, nonempty_bbox
25
from ..cls_utils import _get_class_default_kwargs
W
wangguanzhong 已提交
26

F
Feng Ni 已提交
27 28
__all__ = ['CascadeTwoFCHead', 'CascadeXConvNormHead', 'CascadeHead']

W
wangguanzhong 已提交
29 30 31 32

@register
class CascadeTwoFCHead(nn.Layer):
    __shared__ = ['num_cascade_stage']
W
wangguanzhong 已提交
33 34 35 36 37 38 39 40 41
    """
    Cascade RCNN bbox head  with Two fc layers to extract feature

    Args:
        in_channel (int): Input channel which can be derived by from_config
        out_channel (int): Output channel
        resolution (int): Resolution of input feature map, default 7
        num_cascade_stage (int): The number of cascade stage, default 3
    """
W
wangguanzhong 已提交
42 43

    def __init__(self,
W
wangguanzhong 已提交
44 45
                 in_channel=256,
                 out_channel=1024,
W
wangguanzhong 已提交
46 47 48 49
                 resolution=7,
                 num_cascade_stage=3):
        super(CascadeTwoFCHead, self).__init__()

W
wangguanzhong 已提交
50 51
        self.in_channel = in_channel
        self.out_channel = out_channel
W
wangguanzhong 已提交
52 53 54 55

        self.head_list = []
        for stage in range(num_cascade_stage):
            head_per_stage = self.add_sublayer(
W
wangguanzhong 已提交
56
                str(stage), TwoFCHead(in_channel, out_channel, resolution))
W
wangguanzhong 已提交
57 58 59 60 61 62
            self.head_list.append(head_per_stage)

    @classmethod
    def from_config(cls, cfg, input_shape):
        s = input_shape
        s = s[0] if isinstance(s, (list, tuple)) else s
W
wangguanzhong 已提交
63
        return {'in_channel': s.channels}
F
Feng Ni 已提交
64 65 66

    @property
    def out_shape(self):
W
wangguanzhong 已提交
67
        return [ShapeSpec(channels=self.out_channel, )]
F
Feng Ni 已提交
68 69 70 71 72 73 74 75 76

    def forward(self, rois_feat, stage=0):
        out = self.head_list[stage](rois_feat)
        return out


@register
class CascadeXConvNormHead(nn.Layer):
    __shared__ = ['norm_type', 'freeze_norm', 'num_cascade_stage']
W
wangguanzhong 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90
    """
    Cascade RCNN bbox head with serveral convolution layers

    Args:
        in_channel (int): Input channels which can be derived by from_config
        num_convs (int): The number of conv layers
        conv_dim (int): The number of channels for the conv layers
        out_channel (int): Output channels
        resolution (int): Resolution of input feature map
        norm_type (string): Norm type, bn, gn, sync_bn are available, 
            default `gn`
        freeze_norm (bool): Whether to freeze the norm
        num_cascade_stage (int): The number of cascade stage, default 3
    """
F
Feng Ni 已提交
91 92

    def __init__(self,
W
wangguanzhong 已提交
93
                 in_channel=256,
F
Feng Ni 已提交
94 95
                 num_convs=4,
                 conv_dim=256,
W
wangguanzhong 已提交
96
                 out_channel=1024,
F
Feng Ni 已提交
97 98 99 100 101
                 resolution=7,
                 norm_type='gn',
                 freeze_norm=False,
                 num_cascade_stage=3):
        super(CascadeXConvNormHead, self).__init__()
W
wangguanzhong 已提交
102 103
        self.in_channel = in_channel
        self.out_channel = out_channel
F
Feng Ni 已提交
104 105 106 107 108 109

        self.head_list = []
        for stage in range(num_cascade_stage):
            head_per_stage = self.add_sublayer(
                str(stage),
                XConvNormHead(
W
wangguanzhong 已提交
110
                    in_channel,
F
Feng Ni 已提交
111 112
                    num_convs,
                    conv_dim,
W
wangguanzhong 已提交
113
                    out_channel,
F
Feng Ni 已提交
114 115 116 117 118 119 120 121 122 123
                    resolution,
                    norm_type,
                    freeze_norm,
                    stage_name='stage{}_'.format(stage)))
            self.head_list.append(head_per_stage)

    @classmethod
    def from_config(cls, cfg, input_shape):
        s = input_shape
        s = s[0] if isinstance(s, (list, tuple)) else s
W
wangguanzhong 已提交
124
        return {'in_channel': s.channels}
W
wangguanzhong 已提交
125 126 127

    @property
    def out_shape(self):
W
wangguanzhong 已提交
128
        return [ShapeSpec(channels=self.out_channel, )]
W
wangguanzhong 已提交
129 130 131 132 133 134 135 136 137

    def forward(self, rois_feat, stage=0):
        out = self.head_list[stage](rois_feat)
        return out


@register
class CascadeHead(BBoxHead):
    __shared__ = ['num_classes', 'num_cascade_stages']
138
    __inject__ = ['bbox_assigner', 'bbox_loss']
W
wangguanzhong 已提交
139
    """
W
wangguanzhong 已提交
140 141 142 143 144 145 146 147 148 149 150 151
    Cascade RCNN bbox head

    Args:
        head (nn.Layer): Extract feature in bbox head
        in_channel (int): Input channel after RoI extractor
        roi_extractor (object): The module of RoI Extractor
        bbox_assigner (object): The module of Box Assigner, label and sample the 
            box.
        num_classes (int): The number of classes
        bbox_weight (List[List[float]]): The weight to get the decode box and the 
            length of weight is the number of cascade stage
        num_cascade_stages (int): THe number of stage to refine the box
W
wangguanzhong 已提交
152 153 154 155 156
    """

    def __init__(self,
                 head,
                 in_channel,
157
                 roi_extractor=_get_class_default_kwargs(RoIAlign),
W
wangguanzhong 已提交
158 159 160 161
                 bbox_assigner='BboxAssigner',
                 num_classes=80,
                 bbox_weight=[[10., 10., 5., 5.], [20.0, 20.0, 10.0, 10.0],
                              [30.0, 30.0, 15.0, 15.0]],
162
                 num_cascade_stages=3,
W
Wenyu 已提交
163
                 bbox_loss=None,
W
Wenyu 已提交
164 165 166
                 reg_class_agnostic=True,
                 stage_loss_weights=None):

W
wangguanzhong 已提交
167 168 169 170 171 172 173 174 175 176
        nn.Layer.__init__(self, )
        self.head = head
        self.roi_extractor = roi_extractor
        if isinstance(roi_extractor, dict):
            self.roi_extractor = RoIAlign(**roi_extractor)
        self.bbox_assigner = bbox_assigner

        self.num_classes = num_classes
        self.bbox_weight = bbox_weight
        self.num_cascade_stages = num_cascade_stages
177
        self.bbox_loss = bbox_loss
W
Wenyu 已提交
178 179 180 181 182 183
        self.stage_loss_weights = [
            1. / num_cascade_stages for _ in range(num_cascade_stages)
        ] if stage_loss_weights is None else stage_loss_weights
        assert len(
            self.stage_loss_weights
        ) == num_cascade_stages, f'stage_loss_weights({len(self.stage_loss_weights)}) do not equal to num_cascade_stages({num_cascade_stages})'
W
wangguanzhong 已提交
184

W
Wenyu 已提交
185 186 187
        self.reg_class_agnostic = reg_class_agnostic
        num_bbox_delta = 4 if reg_class_agnostic else 4 * num_classes

W
wangguanzhong 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        self.bbox_score_list = []
        self.bbox_delta_list = []
        for i in range(num_cascade_stages):
            score_name = 'bbox_score_stage{}'.format(i)
            delta_name = 'bbox_delta_stage{}'.format(i)
            bbox_score = self.add_sublayer(
                score_name,
                nn.Linear(
                    in_channel,
                    self.num_classes + 1,
                    weight_attr=paddle.ParamAttr(initializer=Normal(
                        mean=0.0, std=0.01))))

            bbox_delta = self.add_sublayer(
                delta_name,
                nn.Linear(
                    in_channel,
W
Wenyu 已提交
205
                    num_bbox_delta,
W
wangguanzhong 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
                    weight_attr=paddle.ParamAttr(initializer=Normal(
                        mean=0.0, std=0.001))))
            self.bbox_score_list.append(bbox_score)
            self.bbox_delta_list.append(bbox_delta)
        self.assigned_label = None
        self.assigned_rois = None

    def forward(self, body_feats=None, rois=None, rois_num=None, inputs=None):
        """
        body_feats (list[Tensor]): Feature maps from backbone
        rois (Tensor): RoIs generated from RPN module
        rois_num (Tensor): The number of RoIs in each image
        inputs (dict{Tensor}): The ground-truth of image
        """
        targets = []
        if self.training:
            rois, rois_num, targets = self.bbox_assigner(rois, rois_num, inputs)
            targets_list = [targets]
            self.assigned_rois = (rois, rois_num)
            self.assigned_targets = targets

        pred_bbox = None
        head_out_list = []
        for i in range(self.num_cascade_stages):
            if i > 0:
                rois, rois_num = self._get_rois_from_boxes(pred_bbox,
                                                           inputs['im_shape'])
                if self.training:
                    rois, rois_num, targets = self.bbox_assigner(
                        rois, rois_num, inputs, i, is_cascade=True)
W
wangguanzhong 已提交
236
                    targets_list.append(targets)
W
wangguanzhong 已提交
237 238 239 240 241

            rois_feat = self.roi_extractor(body_feats, rois, rois_num)
            bbox_feat = self.head(rois_feat, i)
            scores = self.bbox_score_list[i](bbox_feat)
            deltas = self.bbox_delta_list[i](bbox_feat)
W
Wenyu 已提交
242 243 244 245 246 247 248

            # TODO (lyuwenyu) Is it correct for only one class ?
            if not self.reg_class_agnostic and i < self.num_cascade_stages - 1:
                deltas = deltas.reshape([-1, self.num_classes, 4])
                labels = scores[:, :-1].argmax(axis=-1)
                deltas = deltas[paddle.arange(deltas.shape[0]), labels]

W
wangguanzhong 已提交
249 250 251 252 253 254 255 256 257 258 259
            head_out_list.append([scores, deltas, rois])
            pred_bbox = self._get_pred_bbox(deltas, rois, self.bbox_weight[i])

        if self.training:
            loss = {}
            for stage, value in enumerate(zip(head_out_list, targets_list)):
                (scores, deltas, rois), targets = value
                loss_stage = self.get_loss(scores, deltas, targets, rois,
                                           self.bbox_weight[stage])
                for k, v in loss_stage.items():
                    loss[k + "_stage{}".format(
W
Wenyu 已提交
260
                        stage)] = v * self.stage_loss_weights[stage]
W
wangguanzhong 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273

            return loss, bbox_feat
        else:
            scores, deltas, self.refined_rois = self.get_prediction(
                head_out_list)
            return (deltas, scores), self.head

    def _get_rois_from_boxes(self, boxes, im_shape):
        rois = []
        for i, boxes_per_image in enumerate(boxes):
            clip_box = clip_bbox(boxes_per_image, im_shape[i])
            if self.training:
                keep = nonempty_bbox(clip_box)
274 275
                if keep.shape[0] == 0:
                    keep = paddle.zeros([1], dtype='int32')
W
wangguanzhong 已提交
276 277 278 279 280 281 282 283 284
                clip_box = paddle.gather(clip_box, keep)
            rois.append(clip_box)
        rois_num = paddle.concat([paddle.shape(r)[0] for r in rois])
        return rois, rois_num

    def _get_pred_bbox(self, deltas, proposals, weights):
        pred_proposals = paddle.concat(proposals) if len(
            proposals) > 1 else proposals[0]
        pred_bbox = delta2bbox(deltas, pred_proposals, weights)
285
        pred_bbox = paddle.reshape(pred_bbox, [-1, deltas.shape[-1]])
C
cnn 已提交
286 287 288
        num_prop = []
        for p in proposals:
            num_prop.append(p.shape[0])
W
wangguanzhong 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        return pred_bbox.split(num_prop)

    def get_prediction(self, head_out_list):
        """
        head_out_list(List[Tensor]): scores, deltas, rois
        """
        pred_list = []
        scores_list = [F.softmax(head[0]) for head in head_out_list]
        scores = paddle.add_n(scores_list) / self.num_cascade_stages
        # Get deltas and rois from the last stage
        _, deltas, rois = head_out_list[-1]
        return scores, deltas, rois

    def get_refined_rois(self, ):
        return self.refined_rois