AI Logic

Pooling

RoI Pooling

Updated๏ผš

Diagram of RoI pooling. Left: the overall flow of Fast R-CNN, where candidate regions (RoIs) are projected onto the feature map obtained by passing the whole image through the convolutional layers, then go through RoI pooling and two fully connected layers to output classes and box regression. Right: a numerical example on a 7ร—7 feature map, where the image RoI (20, 28)โ€“(76, 92) divided by 16 gives (1.25, 1.75)โ€“(4.75, 5.75), which is rounded to the grid as (1, 2)โ€“(5, 6), and the maxima 8, 9, 3, 6 of the 2ร—2 bins are output. The misalignment between the true RoI (dashed) and the rounded RoI is visible

What is RoI pooling?

RoI pooling divides rectangular regions of varying size on a feature map into a fixed number of bins and takes the maximum in each bin, producing small feature maps of the same size. An RoI (Region of Interest) is a candidate region likely to contain an object. The output size Hร—WH \times W (e.g. 7ร—7) is constant regardless of the region's size, so fully connected layers can follow it. It has no learnable parameters.

Girshick proposed it in 2015 as a component of the Fast R-CNN object detector. The earlier R-CNN cropped about 2,000 candidate regions from each image and passed them through a CNN one at a time, which made it very slow. SPP-net sped this up by computing the feature map of the whole image only once and extracting a feature for each region from it, but it could not update the convolutional layers when training for detection. With RoI pooling and a better training scheme, Fast R-CNN kept the speed while training everything, including the convolutional layers, jointly.

The paper describes RoI pooling as "a special case of the spatial pyramid pooling layer used in SPP-nets in which there is only one pyramid level". The way bins are divided is also the same as in SPP-net.

In the example in the top figure, the image RoI (20, 28)โ€“(76, 92) is divided by the feature map stride of 16 to give (1.25, 1.75)โ€“(4.75, 5.75), which is rounded to integers as the 4ร—4 cells (1, 2)โ€“(5, 6). This is divided into 2ร—2 bins, and their maxima 8, 9, 3, 6 form the output.

Computation steps

The Fast R-CNN paper defines an RoI as a rectangle (r,c,h,w)(r, c, h, w) on the feature map (top-left position, height and width).

  1. Project the RoI onto the feature map: Divide the image coordinates by the product of strides up to the feature map (16 for conv5 of VGG16) and round to integers.
  2. Divide the RoI into Hร—WH \times W bins: Each bin is roughly h/Hร—w/Wh/H \times w/W in size. When it does not divide evenly, the start of each bin is floored and the end is ceiled to integers, as in SPP-net.
  3. Take the maximum in each bin: As in max pooling, each channel is computed separately.
  4. The output is Cร—Hร—WC \times H \times W, flattened and passed to the fully connected layers.

Let yrjy_{rj} be the jj-th output of the rr-th RoI and R(r,j)\mathcal{R}(r, j) the set of input positions in that bin. The paper's formula is:

yrj=xiโˆ—(r,j),iโˆ—(r,j)=argmaxโกiโ€ฒโˆˆR(r,j)xiโ€ฒy_{rj} = x_{i^*(r, j)}, \qquad i^*(r, j) = \operatorname*{argmax}_{i' \in \mathcal{R}(r, j)} x_{i'}

HH and WW are chosen to match the first fully connected layer of the original network. In VGG16, the output of the last max pooling layer is 7ร—7, so replacing that layer with RoI pooling (H=W=7H = W = 7) allows the fully connected weights pretrained on ImageNet to be reused as is.

RoI pooling cuts out, for each region, a "small map of fixed shape" from the feature map of a single image. Because the map size (7ร—7) is fixed, one bin covers a wide area of the feature map for a large object's region and a narrow area for a small object's region.

Training: backpropagation through to the convolutional layers

Backpropagation through RoI pooling passes the gradient only to the position that gave the maximum, as in max pooling. The difference is that when RoIs overlap, a single input xix_i is used in the outputs of several RoIs, in which case the gradients are summed (Equation (4) of the paper).

โˆ‚Lโˆ‚xi=โˆ‘rโˆ‘j[i=iโˆ—(r,j)]โˆ‚Lโˆ‚yrj\frac{\partial L}{\partial x_i} = \sum_r \sum_j \left[ i = i^*(r, j) \right] \frac{\partial L}{\partial y_{rj}}

[โ‹…][\cdot] is 1 if the condition inside holds and 0 otherwise.

Mathematically, the SPP-net layer can be backpropagated through in the same way, but the paper points out that the real reason SPP-net could not update its convolutional layers was how training samples were chosen. R-CNN and SPP-net took each RoI in a mini-batch from a different image. Since the receptive field of an RoI (the range of the input its features look at) often spans the whole image, training on each RoI required the convolution of an entire image, which is very inefficient.

Fast R-CNN builds mini-batches by sampling many RoIs from a small number of images. In the paper's setting, 64 RoIs are taken from each of 2 images, 128 RoIs in total. RoIs from the same image share computation and memory in the forward and backward passes, which makes it about 64 times faster than taking one RoI from each of 128 images. As for the concern that RoIs from the same image are correlated and might slow down training, the paper reports that this was not a problem in practice.

In addition, classification (softmax) and box regression are trained together with a single loss, which removes the stages in R-CNN and SPP-net of extracting features, saving them to disk, and training SVMs and box regressors separately.

Misalignment from rounding coordinates

RoI pooling rounds coordinates to integers twice.

  1. Rounding the RoI boundary: Image coordinates xx are turned into x/16x / 16 and then rounded to integers to fit the grid of the feature map.
  2. Rounding the bin boundaries: When dividing the RoI into Hร—WH \times W, the bin boundaries are also made integers.

One cell of the feature map corresponds to 16ร—16 pixels of the image, so a shift of 0.5 cells from rounding becomes an 8-pixel shift in the image. In the example in the top figure too, the true RoI (dashed) and the rounded RoI (thick line) are misaligned, and the rounded RoI includes cells outside the true region.

The Mask R-CNN paper pointed out that this misalignment has little effect on classification, which is robust to small translations, but has a large negative effect when predicting pixel-level masks. It then proposed RoIAlign, which removes rounding, and greatly improved mask accuracy.

Comparison of RoI pooling and RoIAlign on the same feature map and the same RoI. Left: RoI pooling rounds coordinates and takes the maximum of each 2ร—2 bin. Right: RoIAlign keeps coordinates unrounded and averages 4 bilinearly interpolated points in each bin

The figure above compares the two on the same feature map and the same RoI. RoI pooling takes maxima from a region rounded to the grid, while RoIAlign places points inside the true region and interpolates their values.

Experimental results

Comparison with R-CNN and SPP-net (VGG16, PASCAL VOC 2007, Table 4 of the Fast R-CNN paper)

MethodTraining timeTest time (per image)mAP
R-CNN84 hours47.0 s66.0%
SPP-net25 hours2.3 s63.1%
Fast R-CNN9.5 hours0.32 s66.9%

Fast R-CNN trains about 9 times faster and tests 146 times faster than R-CNN, while also being more accurate. Compared with SPP-net, it trains 2.7 times faster, tests 7 times faster, and has 3.8 points higher mAP. These results are with SPP-net using 5 scales and Fast R-CNN using only one scale.

Which layers to train (VGG16, VOC 2007 mAP, Table 5 of the paper)

Layers trainedmAP
Only fully connected layers (fc6) and above61.4%
conv3_1 and above66.9%
conv2_1 and above67.2%

Training only the fully connected layers (a setting that emulates SPP-net's training at a single scale) lowered mAP by 5.5 points. For deep networks, training the convolutional layers through RoI pooling is important. On the other hand, not all convolutional layers need to be trained: training from conv2_1 made a difference of only 0.3 points and slowed training by 1.3 times. The paper trains conv3_1 and above.

Comparison with RoIAlign (COCO mask AP, Table 2c of the Mask R-CNN paper)

With ResNet-50-C4 (feature map stride 16), mask AP was 26.9 for RoI pooling and 30.2 for RoIAlign (when aggregating with max). On AP75, which judges localization accuracy strictly, the gap widens further: 26.4 versus 31.8.

Caveats

Because coordinates are rounded, the extracted features are misaligned with the true region. The RoI boundary alone can shift by up to half a cell (8 image pixels at stride 16), and rounding the bin boundaries shifts it further. Even if the effect is small for detection with boxes only, accuracy drops for tasks that need fine positions, such as pixel-level masks (instance segmentation) and keypoints. For new models, it is common to use RoIAlign, which does not round.

  • Set spatial_scale to the inverse of the feature map stride: torchvision's roi_pool takes boxes in image coordinates and multiplies them by spatial_scale to get feature map coordinates. For a feature map with stride 16, use 1/16. The default is 1.0 (coordinates used as is), so forgetting to set it points outside the feature map.
  • Mind the shape of boxes: Coordinates are in the order (x1, y1, x2, y2); for a Tensor[K, 5], the first column holds the index of the image within the batch. A per-image list List[Tensor[L, 4]] is also accepted.
  • torchvision includes the end cell: roi_pool counts the cells from the rounded start to the end inclusive at both ends (width = end โˆ’ start + 1). So even for the same RoI as the top figure's example (4ร—4 cells), it takes 5ร—5 cells, and adjacent bins overlap by one row. This is why the values in the implementation example below differ from the top figure.
  • Empty bins become 0: When an RoI extends beyond the feature map and a bin contains no positions, the output is 0 and no gradient flows.
  • Behavior is the same in training and inference: There are no parameters and no randomness, so model.train() and model.eval() give the same result.

Comparison with other methods and how to choose

The table lists methods that extract a fixed-size feature for each region, from the same viewpoints.

MethodGrid levelsCoordinate roundingAggregationTrains conv layersMain use
R-CNN croppingNone (image warped to 227ร—227)None (crops the image)Passes through the CNN as isYes (but slow, since each region goes through the CNN)R-CNN
Spatial pyramid poolingSeveral (e.g. 6ร—6, 3ร—3, 2ร—2, 1ร—1)YesMaxNo (only fully connected layers in the paper)SPP-net
RoI poolingOne (e.g. 7ร—7)YesMaxYesFast R-CNN, Faster R-CNN
RoIAlignOne (e.g. 7ร—7, 14ร—14)No (bilinear interpolation)Average (or max)YesMask R-CNN

As a way to learn where to read according to the object's position, the deformable convolution paper also proposes a deformable variant of RoI pooling whose bin positions can be shifted.

Rough guidelines for choosing:

  • To reproduce box-based object detection exactly as in existing Fast R-CNN or Faster R-CNN implementations: Use RoI pooling.
  • To build a new detector, or to also predict masks or keypoints: Use RoIAlign. The computational cost is almost the same, and there is no misalignment.
  • To get a fixed length for the whole image rather than for regions: Use spatial pyramid pooling or global average pooling.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torchvision
from torchvision.ops import roi_pool, RoIPool

# Same feature map as the top figure (1 image, 1 channel, 7 ร— 7). Shape is [batch, channels, height, width]
feat = torch.tensor([[[[1., 3, 2, 0, 1, 2, 0],
                       [2, 5, 4, 1, 0, 3, 1],
                       [0, 4, 8, 6, 2, 1, 0],
                       [1, 2, 7, 9, 5, 2, 1],
                       [0, 1, 3, 6, 4, 3, 2],
                       [2, 0, 1, 2, 3, 7, 1],
                       [1, 2, 0, 1, 2, 1, 0]]]])

# boxes are image coordinates (x1, y1, x2, y2). For Tensor[K, 5], the first column is the image index in the batch
boxes = torch.tensor([[0, 20., 28., 76., 92.]])

# spatial_scale: image coordinates โ†’ feature map coordinates (1/16 for stride 16). The default 1.0 points outside the feature map
out = roi_pool(feat, boxes, output_size=(2, 2), spatial_scale=1 / 16)
print(out)  # [[9, 9], [6, 7]]
# Differs from the top figure (8, 9 / 3, 6) because torchvision also counts the rounded end cell (takes 5 ร— 5 cells)

# A per-image list also works (List[Tensor[L, 4]])
out2 = roi_pool(feat, [torch.tensor([[20., 28., 76., 92.]])], output_size=2, spatial_scale=1 / 16)
print(torch.equal(out, out2))  # True


# Fast R-CNN head: replace the last max pooling of VGG16 with RoI pooling (7 ร— 7)
class FastRCNNHead(nn.Module):
  def __init__(self, num_classes=20):
    super().__init__()
    vgg = torchvision.models.vgg16(weights=None)    # In practice, use weights pretrained on ImageNet
    self.backbone = vgg.features[:-1]               # Drop the last MaxPool2d (up to conv5_3, stride 16)
    self.roi_pool = RoIPool(output_size=(7, 7), spatial_scale=1 / 16)
    self.fc = nn.Sequential(                        # fc6, fc7 (same shape as VGG16, so weights can be reused)
      nn.Flatten(), nn.Linear(512 * 7 * 7, 4096), nn.ReLU(), nn.Dropout(),
      nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(),
    )
    self.cls = nn.Linear(4096, num_classes + 1)    # K classes + background
    self.bbox = nn.Linear(4096, 4 * num_classes)   # Per-class box regression

  def forward(self, images, rois):
    feat = self.backbone(images)                    # Only once for the whole image
    x = self.fc(self.roi_pool(feat, rois))          # [number of RoIs, 4096]
    return self.cls(x), self.bbox(x)


model = FastRCNNHead()
images = torch.randn(2, 3, 600, 800)               # The paper uses mini-batches of 2 images
rois = torch.tensor([[0, 50., 60., 300., 400.],    # RoIs of the 1st image
                     [0, 10., 10., 120., 90.],
                     [1, 200., 100., 700., 500.]])  # RoI of the 2nd image
model.train()  # RoI pooling itself is the same in train/eval (switch because of Dropout)
scores, deltas = model(images, rois)
print(scores.shape, deltas.shape)  # torch.Size([3, 21]) torch.Size([3, 80])

FAQ

Q. How does RoI pooling differ from spatial pyramid pooling (SPP)?
A.

Computationally, RoI pooling is the special case of SPP with a single level (e.g. 7ร—7). The major difference is training: SPP-net updated only the fully connected layers when training for detection, while Fast R-CNN sampled many RoIs from each image so that the convolutional layers could be trained efficiently through RoI pooling.

Q. How should the output size (7ร—7) be chosen?
A.

Match it to the input of the fully connected layers that follow. Fast R-CNN replaced the last max pooling layer of VGG16, so it uses the same 7ร—7 as that layer's output, which allows the fully connected weights pretrained on ImageNet to be reused as is.

Q. Should I use RoI pooling or RoIAlign?
A.

For new models, RoIAlign is the common choice. RoI pooling rounds coordinates to integers, so the extracted features are misaligned with the true region. In the Mask R-CNN paper, mask AP rose from 26.9 with RoI pooling to 30.2 with RoIAlign. Use RoI pooling when you want to reproduce existing Fast R-CNN results.

References

  1. R. Girshick, "Fast R-CNN," ICCV, 2015.
  2. K. He, X. Zhang, S. Ren, and J. Sun, "Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition," ECCV, 2014 / IEEE TPAMI, 2015.
  3. R. Girshick, J. Donahue, T. Darrell, and J. Malik, "Rich feature hierarchies for accurate object detection and semantic segmentation," CVPR, 2014.
  4. K. He, G. Gkioxari, P. Dollรกr, and R. Girshick, "Mask R-CNN," ICCV, 2017.
  5. torchvision Documentation, "torchvision.ops.roi_pool."