rpn.py 12.1 KB
Newer Older
1 2 3 4 5 6 7 8
# -*- coding:utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 10
import numpy as np

11 12 13
import megengine as mge
import megengine.functional as F
import megengine.module as M
14 15
import megengine.random as rand

16 17 18 19 20 21 22 23
from official.vision.detection import layers
from official.vision.detection.tools.gpu_nms import batched_nms


class RPN(M.Module):
    def __init__(self, cfg):
        super().__init__()
        self.cfg = cfg
24 25
        self.box_coder = layers.BoxCoder(cfg.rpn_reg_mean, cfg.rpn_reg_std)
        self.num_cell_anchors = len(cfg.anchor_scales) * len(cfg.anchor_ratios)
26

27
        self.stride_list = np.array(cfg.rpn_stride).astype(np.float32)
28 29 30 31 32
        rpn_channel = cfg.rpn_channel
        self.in_features = cfg.rpn_in_features
        self.anchors_generator = layers.DefaultAnchorGenerator(
            cfg.anchor_base_size,
            cfg.anchor_scales,
33
            cfg.anchor_ratios,
34 35 36 37
            cfg.anchor_offset,
        )
        self.rpn_conv = M.Conv2d(256, rpn_channel, kernel_size=3, stride=1, padding=1)
        self.rpn_cls_score = M.Conv2d(
38
            rpn_channel, self.num_cell_anchors * 2, kernel_size=1, stride=1
39 40
        )
        self.rpn_bbox_offsets = M.Conv2d(
41
            rpn_channel, self.num_cell_anchors * 4, kernel_size=1, stride=1
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
        )

        for l in [self.rpn_conv, self.rpn_cls_score, self.rpn_bbox_offsets]:
            M.init.normal_(l.weight, std=0.01)
            M.init.fill_(l.bias, 0)

    def forward(self, features, im_info, boxes=None):
        # prediction
        features = [features[x] for x in self.in_features]

        # get anchors
        all_anchors_list = [
            self.anchors_generator(fm, stride)
            for fm, stride in zip(features, self.stride_list)
        ]

58 59
        pred_cls_logit_list = []
        pred_bbox_offset_list = []
60 61 62
        for x in features:
            t = F.relu(self.rpn_conv(x))
            scores = self.rpn_cls_score(t)
63
            pred_cls_logit_list.append(
64
                scores.reshape(
65 66 67 68 69
                    scores.shape[0],
                    2,
                    self.num_cell_anchors,
                    scores.shape[2],
                    scores.shape[3],
70 71 72
                )
            )
            bbox_offsets = self.rpn_bbox_offsets(t)
73
            pred_bbox_offset_list.append(
74
                bbox_offsets.reshape(
75 76 77 78 79
                    bbox_offsets.shape[0],
                    self.num_cell_anchors,
                    4,
                    bbox_offsets.shape[2],
                    bbox_offsets.shape[3],
80 81 82 83
                )
            )
        # sample from the predictions
        rpn_rois = self.find_top_rpn_proposals(
84
            pred_bbox_offset_list, pred_cls_logit_list, all_anchors_list, im_info
85 86 87 88
        )

        if self.training:
            rpn_labels, rpn_bbox_targets = self.get_ground_truth(
89 90
                boxes, im_info, all_anchors_list
            )
91 92
            pred_cls_logits, pred_bbox_offsets = self.merge_rpn_score_box(
                pred_cls_logit_list, pred_bbox_offset_list
93 94 95
            )

            # rpn loss
96
            loss_rpn_cls = layers.softmax_loss(pred_cls_logits, rpn_labels)
97 98 99 100 101
            loss_rpn_loc = layers.get_smooth_l1_loss(
                pred_bbox_offsets,
                rpn_bbox_targets,
                rpn_labels,
                self.cfg.rpn_smooth_l1_beta,
102
                norm_type="all",
103
            )
104
            loss_dict = {"loss_rpn_cls": loss_rpn_cls, "loss_rpn_loc": loss_rpn_loc}
105 106 107 108 109
            return rpn_rois, loss_dict
        else:
            return rpn_rois

    def find_top_rpn_proposals(
110
        self, rpn_bbox_offset_list, rpn_cls_score_list, all_anchors_list, im_info
111
    ):
112 113 114 115 116 117 118 119 120 121
        prev_nms_top_n = (
            self.cfg.train_prev_nms_top_n
            if self.training
            else self.cfg.test_prev_nms_top_n
        )
        post_nms_top_n = (
            self.cfg.train_post_nms_top_n
            if self.training
            else self.cfg.test_post_nms_top_n
        )
122 123 124 125

        batch_per_gpu = self.cfg.batch_per_gpu if self.training else 1
        nms_threshold = self.cfg.rpn_nms_threshold

126
        list_size = len(rpn_bbox_offset_list)
127 128 129 130

        return_rois = []

        for bid in range(batch_per_gpu):
131 132
            batch_proposal_list = []
            batch_score_list = []
133 134
            batch_level_list = []
            for l in range(list_size):
135
                # get proposals and scores
136
                offsets = (
137
                    rpn_bbox_offset_list[l][bid].dimshuffle(2, 3, 0, 1).reshape(-1, 4)
138
                )
139 140 141
                all_anchors = all_anchors_list[l]
                proposals = self.box_coder.decode(all_anchors, offsets)

142
                scores = rpn_cls_score_list[l][bid, 1].dimshuffle(1, 2, 0).reshape(1, -1)
143
                # prev nms top n
144 145 146
                scores, order = F.argsort(scores, descending=True)
                num_proposals = F.minimum(scores.shapeof(1), prev_nms_top_n)
                scores = scores.reshape(-1)[:num_proposals]
147 148 149
                order = order.reshape(-1)[:num_proposals]
                proposals = proposals.ai[order, :]

150 151 152
                batch_proposal_list.append(proposals)
                batch_score_list.append(scores)
                batch_level_list.append(mge.ones(scores.shapeof(0)) * l)
153

154 155 156
            proposals = F.concat(batch_proposal_list, axis=0)
            scores = F.concat(batch_score_list, axis=0)
            levels = F.concat(batch_level_list, axis=0)
157 158 159 160 161 162 163

            proposals = layers.get_clipped_box(proposals, im_info[bid, :])
            # filter empty
            keep_mask = layers.filter_boxes(proposals)
            _, keep_inds = F.cond_take(keep_mask == 1, keep_mask)
            proposals = proposals.ai[keep_inds, :]
            scores = scores.ai[keep_inds]
164
            levels = levels.ai[keep_inds]
165

166
            # gather the proposals and scores
167 168 169 170
            # sort nms by scores
            scores, order = F.argsort(scores.reshape(1, -1), descending=True)
            order = order.reshape(-1)
            proposals = proposals.ai[order, :]
171
            levels = levels.ai[order]
172

173
            # apply total levels nms
174
            rois = F.concat([proposals, scores.reshape(-1, 1)], axis=1)
175
            keep_inds = batched_nms(
176
                proposals, scores, levels, nms_threshold, post_nms_top_n
177
            )
178 179 180 181 182 183 184 185 186
            rois = rois.ai[keep_inds]

            # rois shape (N, 5), info [batch_id, x1, y1, x2, y2]
            batch_inds = mge.ones((rois.shapeof(0), 1)) * bid
            batch_rois = F.concat([batch_inds, rois[:, :4]], axis=1)
            return_rois.append(batch_rois)

        return F.zero_grad(F.concat(return_rois, axis=0))

187
    def merge_rpn_score_box(self, rpn_cls_score_list, rpn_bbox_offset_list):
188
        final_rpn_cls_score_list = []
189
        final_rpn_bbox_offset_list = []
190 191 192

        for bid in range(self.cfg.batch_per_gpu):
            batch_rpn_cls_score_list = []
193
            batch_rpn_bbox_offset_list = []
194 195

            for i in range(len(self.in_features)):
196
                rpn_cls_scores = (
197 198 199
                    rpn_cls_score_list[i][bid].dimshuffle(2, 3, 1, 0).reshape(-1, 2)
                )
                rpn_bbox_offsets = (
200
                    rpn_bbox_offset_list[i][bid].dimshuffle(2, 3, 0, 1).reshape(-1, 4)
201
                )
202

203 204
                batch_rpn_cls_score_list.append(rpn_cls_scores)
                batch_rpn_bbox_offset_list.append(rpn_bbox_offsets)
205

206 207
            batch_rpn_cls_scores = F.concat(batch_rpn_cls_score_list, axis=0)
            batch_rpn_bbox_offsets = F.concat(batch_rpn_bbox_offset_list, axis=0)
208

209 210
            final_rpn_cls_score_list.append(batch_rpn_cls_scores)
            final_rpn_bbox_offset_list.append(batch_rpn_bbox_offsets)
211

212 213 214
        final_rpn_cls_scores = F.concat(final_rpn_cls_score_list, axis=0)
        final_rpn_bbox_offsets = F.concat(final_rpn_bbox_offset_list, axis=0)
        return final_rpn_cls_scores, final_rpn_bbox_offsets
215

216
    def per_level_gt(self, gt_boxes, im_info, anchors, allow_low_quality_matches=True):
217 218
        ignore_label = self.cfg.ignore_label
        # get the gt boxes
219
        valid_gt_boxes = gt_boxes[: im_info[4], :]
220 221 222 223 224 225 226 227 228 229 230
        # compute the iou matrix
        overlaps = layers.get_iou(anchors, valid_gt_boxes[:, :4])
        # match the dtboxes
        a_shp0 = anchors.shape[0]
        max_overlaps = F.max(overlaps, axis=1)
        argmax_overlaps = F.argmax(overlaps, axis=1)
        # all ignore
        labels = mge.ones(a_shp0).astype("int32") * ignore_label
        # set negative ones
        labels = labels * (max_overlaps >= self.cfg.rpn_negative_overlap)
        # set positive ones
231
        fg_mask = max_overlaps >= self.cfg.rpn_positive_overlap
232 233 234 235 236 237 238
        const_one = mge.tensor(1.0)
        if allow_low_quality_matches:
            # make sure that max iou of gt matched
            gt_argmax_overlaps = F.argmax(overlaps, axis=0)
            num_valid_boxes = valid_gt_boxes.shapeof(0)
            gt_id = F.linspace(0, num_valid_boxes - 1, num_valid_boxes).astype("int32")
            argmax_overlaps = argmax_overlaps.set_ai(gt_id)[gt_argmax_overlaps]
239 240 241 242
            max_overlaps = max_overlaps.set_ai(const_one.broadcast(num_valid_boxes))[
                gt_argmax_overlaps
            ]
            fg_mask = max_overlaps >= self.cfg.rpn_positive_overlap
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
        # set positive ones
        _, fg_mask_ind = F.cond_take(fg_mask == 1, fg_mask)
        labels = labels.set_ai(const_one.broadcast(fg_mask_ind.shapeof(0)))[fg_mask_ind]
        # compute the targets
        bbox_targets = self.box_coder.encode(
            anchors, valid_gt_boxes.ai[argmax_overlaps, :4]
        )
        return labels, bbox_targets

    def get_ground_truth(self, gt_boxes, im_info, all_anchors_list):
        final_labels_list = []
        final_bbox_targets_list = []

        for bid in range(self.cfg.batch_per_gpu):
            batch_labels_list = []
            batch_bbox_targets_list = []
            for anchors in all_anchors_list:
                rpn_labels_perlvl, rpn_bbox_targets_perlvl = self.per_level_gt(
                    gt_boxes[bid], im_info[bid], anchors,
                )
                batch_labels_list.append(rpn_labels_perlvl)
                batch_bbox_targets_list.append(rpn_bbox_targets_perlvl)

            concated_batch_labels = F.concat(batch_labels_list, axis=0)
            concated_batch_bbox_targets = F.concat(batch_bbox_targets_list, axis=0)

            # sample labels
            num_positive = self.cfg.num_sample_anchors * self.cfg.positive_anchor_ratio
            # sample positive
            concated_batch_labels = self._bernoulli_sample_labels(
273
                concated_batch_labels, num_positive, 1, self.cfg.ignore_label
274 275 276 277 278
            )
            # sample negative
            num_positive = (concated_batch_labels == 1).sum()
            num_negative = self.cfg.num_sample_anchors - num_positive
            concated_batch_labels = self._bernoulli_sample_labels(
279
                concated_batch_labels, num_negative, 0, self.cfg.ignore_label
280 281 282 283 284 285 286 287 288 289 290 291
            )

            final_labels_list.append(concated_batch_labels)
            final_bbox_targets_list.append(concated_batch_bbox_targets)
        final_labels = F.concat(final_labels_list, axis=0)
        final_bbox_targets = F.concat(final_bbox_targets_list, axis=0)
        return F.zero_grad(final_labels), F.zero_grad(final_bbox_targets)

    def _bernoulli_sample_labels(
        self, labels, num_samples, sample_value, ignore_label=-1
    ):
        """ Using the bernoulli sampling method"""
292
        sample_label_mask = labels == sample_value
293 294
        num_mask = sample_label_mask.sum()
        num_final_samples = F.minimum(num_mask, num_samples)
295 296
        # here, we use the bernoulli scoreability to sample the anchors
        sample_score = num_final_samples / num_mask
297
        uniform_rng = rand.uniform(sample_label_mask.shapeof(0))
298
        to_ignore_mask = (uniform_rng >= sample_score) * sample_label_mask
299 300 301
        labels = labels * (1 - to_ignore_mask) + to_ignore_mask * ignore_label

        return labels