bbox_head.py 5.5 KB
Newer Older
F
FDInSky 已提交
1 2 3 4 5 6 7
import paddle.fluid as fluid
from paddle.fluid.dygraph import Layer
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.initializer import Normal, MSRA
from paddle.fluid.regularizer import L2Decay
from paddle.fluid.dygraph.nn import Conv2D, Pool2D
from ppdet.core.workspace import register
8
# TODO: del import and use inject
F
FDInSky 已提交
9 10 11 12 13 14
from ..backbone.resnet import Blocks


@register
class BBoxFeat(Layer):
    __inject__ = ['roi_extractor']
15
    __shared__ = ['num_stages']
F
FDInSky 已提交
16

17
    def __init__(self, roi_extractor, feat_in=1024, feat_out=512, num_stages=1):
F
FDInSky 已提交
18 19
        super(BBoxFeat, self).__init__()
        self.roi_extractor = roi_extractor
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
        self.num_stages = num_stages
        self.res5s = []
        for i in range(self.num_stages):
            if i == 0:
                postfix = ''
            else:
                postfix = '_' + str(i)
            # TODO: set norm type  
            res5 = Blocks(
                "res5" + postfix,
                ch_in=feat_in,
                ch_out=feat_out,
                count=3,
                stride=2)
            self.res5s.append(res5)
F
FDInSky 已提交
35 36 37 38
        self.res5_pool = fluid.dygraph.Pool2D(
            pool_type='avg', global_pooling=True)

    def forward(self, inputs):
39

F
FDInSky 已提交
40
        if inputs['mode'] == 'train':
41 42 43
            in_rois = inputs['proposal_' + str(inputs['stage'])]
            rois = in_rois['rois']
            rois_num = in_rois['rois_nums']
F
FDInSky 已提交
44 45 46 47 48 49 50 51
        elif inputs['mode'] == 'infer':
            rois = inputs['rpn_rois']
            rois_num = inputs['rpn_rois_nums']
        else:
            raise "BBoxFeat only support train or infer mode!"

        rois_feat = self.roi_extractor(inputs['res4'], rois, rois_num)
        # TODO: add others 
52
        y_res5 = self.res5s[inputs['stage']](rois_feat)
F
FDInSky 已提交
53 54 55 56 57 58
        y = self.res5_pool(y_res5)
        y = fluid.layers.squeeze(y, axes=[2, 3])
        outs = {
            'rois_feat': rois_feat,
            'res5': y_res5,
            "bbox_feat": y,
59
            'shared_res5_block': self.res5s[inputs['stage']],
F
FDInSky 已提交
60 61 62 63 64 65 66 67
            'shared_roi_extractor': self.roi_extractor
        }
        return outs


@register
class BBoxHead(Layer):
    __inject__ = ['bbox_feat']
68
    __shared__ = ['num_classes', 'num_stages']
F
FDInSky 已提交
69 70

    def __init__(self,
71 72
                 bbox_feat,
                 feat_in=2048,
F
FDInSky 已提交
73
                 num_classes=81,
74 75
                 cls_agnostic_bbox_reg=81,
                 num_stages=1):
F
FDInSky 已提交
76 77
        super(BBoxHead, self).__init__()
        self.bbox_feat = bbox_feat
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        self.num_classes = num_classes
        self.cls_agnostic_bbox_reg = cls_agnostic_bbox_reg
        self.num_stages = num_stages

        self.bbox_scores = []
        self.bbox_deltas = []
        for i in range(self.num_stages):
            if i == 0:
                postfix = ''
            else:
                postfix = '_' + str(i)
            bbox_score = fluid.dygraph.Linear(
                input_dim=feat_in,
                output_dim=1 * self.num_classes,
                act=None,
                param_attr=ParamAttr(
                    name='cls_score_w' + postfix,
                    initializer=Normal(
                        loc=0.0, scale=0.001)),
                bias_attr=ParamAttr(
                    name='cls_score_b' + postfix,
                    learning_rate=2.,
                    regularizer=L2Decay(0.)))

            bbox_delta = fluid.dygraph.Linear(
                input_dim=feat_in,
                output_dim=4 * self.cls_agnostic_bbox_reg,
                act=None,
                param_attr=ParamAttr(
                    name='bbox_pred_w' + postfix,
                    initializer=Normal(
                        loc=0.0, scale=0.01)),
                bias_attr=ParamAttr(
                    name='bbox_pred_b' + postfix,
                    learning_rate=2.,
                    regularizer=L2Decay(0.)))
            self.bbox_scores.append(bbox_score)
            self.bbox_deltas.append(bbox_delta)
F
FDInSky 已提交
116 117 118 119

    def forward(self, inputs):
        outs = self.bbox_feat(inputs)
        x = outs['bbox_feat']
120 121
        bs = self.bbox_scores[inputs['stage']](x)
        bd = self.bbox_deltas[inputs['stage']](x)
F
FDInSky 已提交
122
        outs.update({'bbox_score': bs, 'bbox_delta': bd})
123 124
        if inputs['stage'] == 0:
            outs.update({"cls_agnostic_bbox_reg": self.cls_agnostic_bbox_reg})
F
FDInSky 已提交
125 126 127 128 129 130
        if inputs['mode'] == 'infer':
            bbox_prob = fluid.layers.softmax(bs, use_cudnn=False)
            outs['bbox_prob'] = bbox_prob
        return outs

    def loss(self, inputs):
131 132 133
        bbox_out = inputs['bbox_head_' + str(inputs['stage'])]
        bbox_target = inputs['proposal_' + str(inputs['stage'])]

F
FDInSky 已提交
134 135
        # bbox cls  
        labels_int64 = fluid.layers.cast(
136
            x=bbox_target['labels_int32'], dtype='int64')
F
FDInSky 已提交
137
        labels_int64.stop_gradient = True
138
        bbox_score = fluid.layers.reshape(bbox_out['bbox_score'],
F
FDInSky 已提交
139 140 141 142
                                          (-1, self.num_classes))
        loss_bbox_cls = fluid.layers.softmax_with_cross_entropy(
            logits=bbox_score, label=labels_int64)
        loss_bbox_cls = fluid.layers.reduce_mean(
143 144
            loss_bbox_cls, name='loss_bbox_cls_' + str(inputs['stage']))

F
FDInSky 已提交
145 146
        # bbox reg
        loss_bbox_reg = fluid.layers.smooth_l1(
147 148 149 150
            x=bbox_out['bbox_delta'],
            y=bbox_target['bbox_targets'],
            inside_weight=bbox_target['bbox_inside_weights'],
            outside_weight=bbox_target['bbox_outside_weights'],
F
FDInSky 已提交
151 152
            sigma=1.0)
        loss_bbox_reg = fluid.layers.reduce_mean(
153
            loss_bbox_reg, name='loss_bbox_loc_' + str(inputs['stage']))
F
FDInSky 已提交
154 155

        return loss_bbox_cls, loss_bbox_reg