rpn.py 14.9 KB
Newer Older
1
from typing import List, Optional, Dict, Tuple, cast
2

3
import torch
4
import torchvision
5
6
from torch import nn, Tensor
from torch.nn import functional as F
7
8
9
10
from torchvision.ops import boxes as box_ops

from . import _utils as det_utils

11
# Import AnchorGenerator to keep compatibility.
12
from .anchor_utils import AnchorGenerator  # noqa: 401
13
from .image_list import ImageList
14

15

16
@torch.jit.unused
17
def _onnx_get_num_anchors_and_pre_nms_top_n(ob: Tensor, orig_pre_nms_top_n: int) -> Tuple[int, int]:
18
    from torch.onnx import operators
19

20
    num_anchors = operators.shape_as_tensor(ob)[1].unsqueeze(0)
21
    pre_nms_top_n = torch.min(torch.cat((torch.tensor([orig_pre_nms_top_n], dtype=num_anchors.dtype), num_anchors), 0))
22

23
24
    # for mypy we cast at runtime
    return cast(int, num_anchors), cast(int, pre_nms_top_n)
25
26


27
28
29
class RPNHead(nn.Module):
    """
    Adds a simple RPN Head with classification and regression heads
30

31
    Args:
32
33
        in_channels (int): number of channels of the input feature
        num_anchors (int): number of anchors to be predicted
34
35
    """

36
    def __init__(self, in_channels: int, num_anchors: int) -> None:
37
        super().__init__()
38
        self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
39
        self.cls_logits = nn.Conv2d(in_channels, num_anchors, kernel_size=1, stride=1)
40
        self.bbox_pred = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=1, stride=1)
41

Francisco Massa's avatar
Francisco Massa committed
42
        for layer in self.children():
43
44
            torch.nn.init.normal_(layer.weight, std=0.01)  # type: ignore[arg-type]
            torch.nn.init.constant_(layer.bias, 0)  # type: ignore[arg-type]
45

46
    def forward(self, x: List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]:
47
48
49
50
51
52
53
54
55
        logits = []
        bbox_reg = []
        for feature in x:
            t = F.relu(self.conv(feature))
            logits.append(self.cls_logits(t))
            bbox_reg.append(self.bbox_pred(t))
        return logits, bbox_reg


56
def permute_and_flatten(layer: Tensor, N: int, A: int, C: int, H: int, W: int) -> Tensor:
57
58
59
60
61
62
    layer = layer.view(N, -1, C, H, W)
    layer = layer.permute(0, 3, 4, 1, 2)
    layer = layer.reshape(N, -1, C)
    return layer


63
def concat_box_prediction_layers(box_cls: List[Tensor], box_regression: List[Tensor]) -> Tuple[Tensor, Tensor]:
64
65
66
67
68
69
    box_cls_flattened = []
    box_regression_flattened = []
    # for each feature level, permute the outputs to make them be in the
    # same format as the labels. Note that the labels are computed for
    # all feature levels concatenated, so we keep the same representation
    # for the objectness and the box_regression
70
    for box_cls_per_level, box_regression_per_level in zip(box_cls, box_regression):
71
72
73
74
        N, AxC, H, W = box_cls_per_level.shape
        Ax4 = box_regression_per_level.shape[1]
        A = Ax4 // 4
        C = AxC // A
75
        box_cls_per_level = permute_and_flatten(box_cls_per_level, N, A, C, H, W)
76
77
        box_cls_flattened.append(box_cls_per_level)

78
        box_regression_per_level = permute_and_flatten(box_regression_per_level, N, A, 4, H, W)
79
80
81
82
        box_regression_flattened.append(box_regression_per_level)
    # concatenate on the first dimension (representing the feature levels), to
    # take into account the way the labels were generated (with all feature maps
    # being concatenated as well)
83
    box_cls = torch.cat(box_cls_flattened, dim=1).flatten(0, -2)
84
85
86
87
88
    box_regression = torch.cat(box_regression_flattened, dim=1).reshape(-1, 4)
    return box_cls, box_regression


class RegionProposalNetwork(torch.nn.Module):
89
90
91
    """
    Implements Region Proposal Network (RPN).

92
    Args:
93
94
95
96
97
98
99
100
101
102
103
        anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
            maps.
        head (nn.Module): module that computes the objectness and regression deltas
        fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
            considered as positive during training of the RPN.
        bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
            considered as negative during training of the RPN.
        batch_size_per_image (int): number of anchors that are sampled during training of the RPN
            for computing the loss
        positive_fraction (float): proportion of positive anchors in a mini-batch during training
            of the RPN
104
        pre_nms_top_n (Dict[str, int]): number of proposals to keep before applying NMS. It should
105
106
            contain two fields: training and testing, to allow for different values depending
            on training or evaluation
107
        post_nms_top_n (Dict[str, int]): number of proposals to keep after applying NMS. It should
108
109
110
111
112
            contain two fields: training and testing, to allow for different values depending
            on training or evaluation
        nms_thresh (float): NMS threshold used for postprocessing the RPN proposals

    """
113

eellison's avatar
eellison committed
114
    __annotations__ = {
115
116
117
        "box_coder": det_utils.BoxCoder,
        "proposal_matcher": det_utils.Matcher,
        "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler,
eellison's avatar
eellison committed
118
    }
119

120
121
    def __init__(
        self,
122
123
124
125
126
127
128
129
130
131
132
133
134
        anchor_generator: AnchorGenerator,
        head: nn.Module,
        # Faster-RCNN Training
        fg_iou_thresh: float,
        bg_iou_thresh: float,
        batch_size_per_image: int,
        positive_fraction: float,
        # Faster-RCNN Inference
        pre_nms_top_n: Dict[str, int],
        post_nms_top_n: Dict[str, int],
        nms_thresh: float,
        score_thresh: float = 0.0,
    ) -> None:
135
        super().__init__()
136
137
138
139
140
141
142
143
144
145
146
147
148
        self.anchor_generator = anchor_generator
        self.head = head
        self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0))

        # used during training
        self.box_similarity = box_ops.box_iou

        self.proposal_matcher = det_utils.Matcher(
            fg_iou_thresh,
            bg_iou_thresh,
            allow_low_quality_matches=True,
        )

149
        self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction)
150
151
152
153
        # used during testing
        self._pre_nms_top_n = pre_nms_top_n
        self._post_nms_top_n = post_nms_top_n
        self.nms_thresh = nms_thresh
154
        self.score_thresh = score_thresh
155
        self.min_size = 1e-3
156

157
    def pre_nms_top_n(self) -> int:
158
        if self.training:
159
160
            return self._pre_nms_top_n["training"]
        return self._pre_nms_top_n["testing"]
161

162
    def post_nms_top_n(self) -> int:
163
        if self.training:
164
165
            return self._post_nms_top_n["training"]
        return self._post_nms_top_n["testing"]
166

167
168
169
170
    def assign_targets_to_anchors(
        self, anchors: List[Tensor], targets: List[Dict[str, Tensor]]
    ) -> Tuple[List[Tensor], List[Tensor]]:

171
172
173
174
        labels = []
        matched_gt_boxes = []
        for anchors_per_image, targets_per_image in zip(anchors, targets):
            gt_boxes = targets_per_image["boxes"]
175
176
177
178
179
180
181

            if gt_boxes.numel() == 0:
                # Background image (negative example)
                device = anchors_per_image.device
                matched_gt_boxes_per_image = torch.zeros(anchors_per_image.shape, dtype=torch.float32, device=device)
                labels_per_image = torch.zeros((anchors_per_image.shape[0],), dtype=torch.float32, device=device)
            else:
182
                match_quality_matrix = self.box_similarity(gt_boxes, anchors_per_image)
183
184
185
186
187
188
189
190
191
192
193
194
                matched_idxs = self.proposal_matcher(match_quality_matrix)
                # get the targets corresponding GT for each proposal
                # NB: need to clamp the indices because we can have a single
                # GT in the image, and matched_idxs can be -2, which goes
                # out of bounds
                matched_gt_boxes_per_image = gt_boxes[matched_idxs.clamp(min=0)]

                labels_per_image = matched_idxs >= 0
                labels_per_image = labels_per_image.to(dtype=torch.float32)

                # Background (negative examples)
                bg_indices = matched_idxs == self.proposal_matcher.BELOW_LOW_THRESHOLD
195
                labels_per_image[bg_indices] = 0.0
196
197
198

                # discard indices that are between thresholds
                inds_to_discard = matched_idxs == self.proposal_matcher.BETWEEN_THRESHOLDS
199
                labels_per_image[inds_to_discard] = -1.0
200
201
202
203
204

            labels.append(labels_per_image)
            matched_gt_boxes.append(matched_gt_boxes_per_image)
        return labels, matched_gt_boxes

205
    def _get_top_n_idx(self, objectness: Tensor, num_anchors_per_level: List[int]) -> Tensor:
206
207
208
        r = []
        offset = 0
        for ob in objectness.split(num_anchors_per_level, 1):
209
            if torchvision._is_tracing():
eellison's avatar
eellison committed
210
                num_anchors, pre_nms_top_n = _onnx_get_num_anchors_and_pre_nms_top_n(ob, self.pre_nms_top_n())
211
212
            else:
                num_anchors = ob.shape[1]
eellison's avatar
eellison committed
213
                pre_nms_top_n = min(self.pre_nms_top_n(), num_anchors)
214
215
216
217
218
            _, top_n_idx = ob.topk(pre_nms_top_n, dim=1)
            r.append(top_n_idx + offset)
            offset += num_anchors
        return torch.cat(r, dim=1)

219
220
221
222
223
224
225
226
    def filter_proposals(
        self,
        proposals: Tensor,
        objectness: Tensor,
        image_shapes: List[Tuple[int, int]],
        num_anchors_per_level: List[int],
    ) -> Tuple[List[Tensor], List[Tensor]]:

227
228
        num_images = proposals.shape[0]
        device = proposals.device
229
        # do not backprop through objectness
230
231
232
233
        objectness = objectness.detach()
        objectness = objectness.reshape(num_images, -1)

        levels = [
234
            torch.full((n,), idx, dtype=torch.int64, device=device) for idx, n in enumerate(num_anchors_per_level)
235
236
237
238
239
240
        ]
        levels = torch.cat(levels, 0)
        levels = levels.reshape(1, -1).expand_as(objectness)

        # select top_n boxes independently per level before applying nms
        top_n_idx = self._get_top_n_idx(objectness, num_anchors_per_level)
eellison's avatar
eellison committed
241
242
243
244

        image_range = torch.arange(num_images, device=device)
        batch_idx = image_range[:, None]

245
246
247
248
        objectness = objectness[batch_idx, top_n_idx]
        levels = levels[batch_idx, top_n_idx]
        proposals = proposals[batch_idx, top_n_idx]

249
        objectness_prob = torch.sigmoid(objectness)
250

251
252
        final_boxes = []
        final_scores = []
253
        for boxes, scores, lvl, img_shape in zip(proposals, objectness_prob, levels, image_shapes):
254
            boxes = box_ops.clip_boxes_to_image(boxes, img_shape)
255
256

            # remove small boxes
257
258
            keep = box_ops.remove_small_boxes(boxes, self.min_size)
            boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep]
259
260
261
262
263
264

            # remove low scoring boxes
            # use >= for Backwards compatibility
            keep = torch.where(scores >= self.score_thresh)[0]
            boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep]

265
266
            # non-maximum suppression, independently done per level
            keep = box_ops.batched_nms(boxes, scores, lvl, self.nms_thresh)
267

268
            # keep only topk scoring predictions
269
            keep = keep[: self.post_nms_top_n()]
270
            boxes, scores = boxes[keep], scores[keep]
271

272
273
274
275
            final_boxes.append(boxes)
            final_scores.append(scores)
        return final_boxes, final_scores

276
277
278
    def compute_loss(
        self, objectness: Tensor, pred_bbox_deltas: Tensor, labels: List[Tensor], regression_targets: List[Tensor]
    ) -> Tuple[Tensor, Tensor]:
279
        """
280
        Args:
281
282
283
284
            objectness (Tensor)
            pred_bbox_deltas (Tensor)
            labels (List[Tensor])
            regression_targets (List[Tensor])
285
286
287

        Returns:
            objectness_loss (Tensor)
lambdaflow's avatar
lambdaflow committed
288
            box_loss (Tensor)
289
290
291
        """

        sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
292
293
        sampled_pos_inds = torch.where(torch.cat(sampled_pos_inds, dim=0))[0]
        sampled_neg_inds = torch.where(torch.cat(sampled_neg_inds, dim=0))[0]
294
295
296
297
298
299
300
301

        sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0)

        objectness = objectness.flatten()

        labels = torch.cat(labels, dim=0)
        regression_targets = torch.cat(regression_targets, dim=0)

302
303
304
305
306
307
308
309
        box_loss = (
            F.smooth_l1_loss(
                pred_bbox_deltas[sampled_pos_inds],
                regression_targets[sampled_pos_inds],
                beta=1 / 9,
                reduction="sum",
            )
            / (sampled_inds.numel())
310
311
        )

312
313
        objectness_loss = F.binary_cross_entropy_with_logits(objectness[sampled_inds], labels[sampled_inds])

314
315
        return objectness_loss, box_loss

316
317
    def forward(
        self,
318
319
320
321
322
        images: ImageList,
        features: Dict[str, Tensor],
        targets: Optional[List[Dict[str, Tensor]]] = None,
    ) -> Tuple[List[Tensor], Dict[str, Tensor]]:

323
        """
324
        Args:
325
            images (ImageList): images for which we want to compute the predictions
326
            features (Dict[str, Tensor]): features computed from the images that are
327
328
                used for computing the predictions. Each tensor in the list
                correspond to different feature levels
329
            targets (List[Dict[str, Tensor]]): ground-truth boxes present in the image (optional).
330
331
                If provided, each element in the dict should contain a field `boxes`,
                with the locations of the ground-truth boxes.
332
333

        Returns:
334
            boxes (List[Tensor]): the predicted boxes from the RPN, one Tensor per
335
                image.
336
            losses (Dict[str, Tensor]): the losses for the model during training. During
337
338
339
340
341
342
343
344
                testing, it is an empty dict.
        """
        # RPN uses all feature maps that are available
        features = list(features.values())
        objectness, pred_bbox_deltas = self.head(features)
        anchors = self.anchor_generator(images, features)

        num_images = len(anchors)
345
346
        num_anchors_per_level_shape_tensors = [o[0].shape for o in objectness]
        num_anchors_per_level = [s[0] * s[1] * s[2] for s in num_anchors_per_level_shape_tensors]
347
        objectness, pred_bbox_deltas = concat_box_prediction_layers(objectness, pred_bbox_deltas)
348
349
350
351
352
353
354
355
356
        # apply pred_bbox_deltas to anchors to obtain the decoded proposals
        # note that we detach the deltas because Faster R-CNN do not backprop through
        # the proposals
        proposals = self.box_coder.decode(pred_bbox_deltas.detach(), anchors)
        proposals = proposals.view(num_images, -1, 4)
        boxes, scores = self.filter_proposals(proposals, objectness, images.image_sizes, num_anchors_per_level)

        losses = {}
        if self.training:
eellison's avatar
eellison committed
357
            assert targets is not None
358
359
360
            labels, matched_gt_boxes = self.assign_targets_to_anchors(anchors, targets)
            regression_targets = self.box_coder.encode(matched_gt_boxes, anchors)
            loss_objectness, loss_rpn_box_reg = self.compute_loss(
361
362
                objectness, pred_bbox_deltas, labels, regression_targets
            )
363
364
365
366
367
            losses = {
                "loss_objectness": loss_objectness,
                "loss_rpn_box_reg": loss_rpn_box_reg,
            }
        return boxes, losses