cascade_rcnn_cls_aware.py 7.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 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

import numpy as np
import sys

22 23 24
from collections import OrderedDict
import copy

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
import paddle.fluid as fluid

from ppdet.core.workspace import register

__all__ = ['CascadeRCNNClsAware']


@register
class CascadeRCNNClsAware(object):
    """
    Cascade R-CNN architecture, see https://arxiv.org/abs/1712.00726
    This is a kind of modification of Cascade R-CNN.
    Specifically, it predicts bboxes for all classes with different weights,
    while the standard vesion just predicts bboxes for foreground
    Args:
        backbone (object): backbone instance
        rpn_head (object): `RPNhead` instance
        bbox_assigner (object): `BBoxAssigner` instance
        roi_extractor (object): ROI extractor instance
        bbox_head (object): `BBoxHead` instance
        fpn (object): feature pyramid network instance
    """

    __category__ = 'architecture'
    __inject__ = [
        'backbone', 'fpn', 'rpn_head', 'bbox_assigner', 'roi_extractor',
        'bbox_head'
    ]

54 55 56 57 58 59 60 61
    def __init__(
            self,
            backbone,
            rpn_head,
            roi_extractor='FPNRoIAlign',
            bbox_head='CascadeBBoxHead',
            bbox_assigner='CascadeBBoxAssigner',
            fpn='FPN', ):
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        super(CascadeRCNNClsAware, self).__init__()
        assert fpn is not None, "cascade RCNN requires FPN"
        self.backbone = backbone
        self.fpn = fpn
        self.rpn_head = rpn_head
        self.bbox_assigner = bbox_assigner
        self.roi_extractor = roi_extractor
        self.bbox_head = bbox_head
        self.bbox_clip = np.log(1000. / 16.)
        # Cascade local cfg
        (brw0, brw1, brw2) = self.bbox_assigner.bbox_reg_weights
        self.cascade_bbox_reg_weights = [
            [1. / brw0, 1. / brw0, 2. / brw0, 2. / brw0],
            [1. / brw1, 1. / brw1, 2. / brw1, 2. / brw1],
            [1. / brw2, 1. / brw2, 2. / brw2, 2. / brw2]
        ]
        self.cascade_rcnn_loss_weight = [1.0, 0.5, 0.25]

    def build(self, feed_vars, mode='train'):
        im = feed_vars['image']
        im_info = feed_vars['im_info']
        if mode == 'train':
84
            gt_bbox = feed_vars['gt_bbox']
85
            is_crowd = feed_vars['is_crowd']
86
            gt_class = feed_vars['gt_class']
87 88 89 90 91 92 93 94 95 96 97 98 99 100
        else:
            im_shape = feed_vars['im_shape']

        # backbone
        body_feats = self.backbone(im)

        # FPN
        if self.fpn is not None:
            body_feats, spatial_scale = self.fpn.get_output(body_feats)

        # rpn proposals
        rpn_rois = self.rpn_head.get_proposals(body_feats, im_info, mode=mode)

        if mode == 'train':
101
            rpn_loss = self.rpn_head.get_loss(im_info, gt_bbox, is_crowd)
102 103 104 105 106 107 108

        proposal_list = []
        roi_feat_list = []
        rcnn_pred_list = []
        rcnn_target_list = []

        bbox_pred = None
109

110 111
        self.cascade_var_v = []
        for stage in range(3):
112 113
            var_v = np.array(
                self.cascade_bbox_reg_weights[stage], dtype="float32")
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
            prior_box_var = fluid.layers.create_tensor(dtype="float32")
            fluid.layers.assign(input=var_v, output=prior_box_var)
            self.cascade_var_v.append(prior_box_var)

        self.cascade_decoded_box = []
        self.cascade_cls_prob = []

        for stage in range(3):
            if stage > 0:
                pool_rois = decoded_assign_box
            else:
                pool_rois = rpn_rois
            if mode == "train":
                self.cascade_var_v[stage].stop_gradient = True
                outs = self.bbox_assigner(
                    input_rois=pool_rois, feed_vars=feed_vars, curr_stage=stage)
                pool_rois = outs[0]
131 132
                rcnn_target_list.append(outs)

133 134 135
            # extract roi features
            roi_feat = self.roi_extractor(body_feats, pool_rois, spatial_scale)
            roi_feat_list.append(roi_feat)
136

137 138 139 140 141
            # bbox head
            cls_score, bbox_pred = self.bbox_head.get_output(
                roi_feat,
                cls_agnostic_bbox_reg=self.bbox_head.num_classes,
                wb_scalar=1.0 / self.cascade_rcnn_loss_weight[stage],
142
                name='_' + str(stage + 1))
143 144

            cls_prob = fluid.layers.softmax(cls_score, use_cudnn=False)
145

146
            decoded_box, decoded_assign_box = fluid.layers.box_decoder_and_assign(
147 148 149
                pool_rois, self.cascade_var_v[stage], bbox_pred, cls_prob,
                self.bbox_clip)

150 151 152 153
            if mode == "train":
                decoded_box.stop_gradient = True
                decoded_assign_box.stop_gradient = True
            else:
154
                self.cascade_cls_prob.append(cls_prob)
155
                self.cascade_decoded_box.append(decoded_box)
156

157
            rcnn_pred_list.append((cls_score, bbox_pred))
158

159 160
        # out loop
        if mode == 'train':
161
            loss = self.bbox_head.get_loss(rcnn_pred_list, rcnn_target_list,
162 163 164 165 166 167 168
                                           self.cascade_rcnn_loss_weight)
            loss.update(rpn_loss)
            total_loss = fluid.layers.sum(list(loss.values()))
            loss.update({'loss': total_loss})
            return loss
        else:
            pred = self.bbox_head.get_prediction_cls_aware(
169 170
                im_info, im_shape, self.cascade_cls_prob,
                self.cascade_decoded_box, self.cascade_bbox_reg_weights)
171
            return pred
172 173 174 175 176 177 178

    def _inputs_def(self, image_shape):
        im_shape = [None] + image_shape
        # yapf: disable
        inputs_def = {
            'image':    {'shape': im_shape,  'dtype': 'float32', 'lod_level': 0},
            'im_info':  {'shape': [None, 3], 'dtype': 'float32', 'lod_level': 0},
Q
qingqing01 已提交
179
            'im_id':    {'shape': [None, 1], 'dtype': 'int64',   'lod_level': 0},
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
            'im_shape': {'shape': [None, 3], 'dtype': 'float32', 'lod_level': 0},
            'gt_bbox':  {'shape': [None, 4], 'dtype': 'float32', 'lod_level': 1},
            'gt_class': {'shape': [None, 1], 'dtype': 'int32',   'lod_level': 1},
            'is_crowd': {'shape': [None, 1], 'dtype': 'int32',   'lod_level': 1},
            'is_difficult': {'shape': [None, 1], 'dtype': 'int32', 'lod_level': 1},
        }
        # yapf: enable
        return inputs_def

    def build_inputs(self,
                     image_shape=[3, None, None],
                     fields=[
                         'image', 'im_info', 'im_id', 'gt_bbox', 'gt_class',
                         'is_crowd', 'gt_mask'
                     ],
                     use_dataloader=True,
                     iterable=False):
        inputs_def = self._inputs_def(image_shape)
        feed_vars = OrderedDict([(key, fluid.layers.data(
            name=key,
            shape=inputs_def[key]['shape'],
            dtype=inputs_def[key]['dtype'],
            lod_level=inputs_def[key]['lod_level'])) for key in fields])
        loader = fluid.io.DataLoader.from_generator(
            feed_list=list(feed_vars.values()),
            capacity=64,
            use_double_buffer=True,
            iterable=iterable) if use_dataloader else None
        return feed_vars, loader
209 210 211 212 213 214 215 216 217

    def train(self, feed_vars):
        return self.build(feed_vars, 'train')

    def eval(self, feed_vars):
        return self.build(feed_vars, 'test')

    def test(self, feed_vars):
        return self.build(feed_vars, 'test')