AI Logic

Pooling

RoIAlign

Updated๏ผš

Diagram of RoIAlign. Left: the overall flow of Mask R-CNN, where RoIAlign extracts features from the backbone feature map for the candidate regions produced by the RPN and passes them to the class and box-regression head and the mask head. Right: a comparison on the same 7ร—7 feature map and the same RoI. RoI pooling on the left rounds the coordinates (1.25, 1.75) to (1, 2) and outputs the maxima 8, 9, 3, 6 of the 2ร—2 bins; RoIAlign on the right keeps the coordinates unrounded, places 4 points in each bin, and outputs the averages of the bilinearly interpolated values, 5.58, 5.05, 2, 4.35. Bottom: an example of computing the value of one point from the 4 surrounding cells

What is RoIAlign?

RoIAlign turns a candidate region (RoI) on a feature map into a feature of fixed size by dividing it into a fixed number of bins, without ever rounding coordinates to integers, computing the values at a few points placed in each bin by bilinear interpolation, and aggregating them. Its role is the same as RoI pooling, but it has no misalignment from rounding. It has no learnable parameters.

He et al. proposed it in 2017 as a component of Mask R-CNN, which predicts pixel-level masks in addition to object boxes. RoI pooling, the standard in object detection until then, rounds the region's coordinates and the bin boundaries to the grid of the feature map. The paper pointed out that this misalignment has little effect on classification, which is robust to small translations, but has a large negative effect on predicting pixel-accurate masks.

The change is small; in the paper's words, it simply "uses x/16x/16 instead of [x/16][x/16] (rounding)". Even so, mask accuracy improved by 10โ€“50% in relative terms, and the gains were larger for metrics that evaluate localization more strictly.

The top figure compares it with RoI pooling on the same feature map and the same RoI. RoI pooling rounds the coordinates (1.25, 1.75) to (1, 2), so it takes the maxima over a 4ร—4 cell area shifted from the true region (dashed line). RoIAlign uses (1.25, 1.75) as is, divides the true region into 2ร—2 bins, places 4 points in each bin, interpolates their values, and outputs the average.

Computation steps

Let the output be Hร—WH \times W (e.g. 7ร—7) and the points placed in each bin be Sร—SS \times S (4 points, 2ร—2, in the paper).

  1. Convert the RoI to feature map coordinates: Divide the image coordinates by the stride of the feature map (e.g. 16). Keep them as fractions without rounding.
  2. Divide the RoI evenly into Hร—WH \times W bins: The bin boundaries also stay fractional.
  3. Place Sร—SS \times S points regularly in each bin: Divide the bin into Sร—SS \times S sub-cells and put a point at the center of each.
  4. Compute each point's value by bilinear interpolation: Add the values of the 4 grid points (feature map cells) surrounding the point, weighted by their closeness to the point.
  5. Aggregate the Sร—SS \times S values in each bin: Take the average or the maximum. The paper found the results almost the same either way and uses the average.

For the bilinear interpolation in step 4, let (x0,y0)(x_0, y_0) be the top-left of the grid points surrounding the point (x,y)(x, y), with lx=xโˆ’x0l_x = x - x_0 and ly=yโˆ’y0l_y = y - y_0. Then:

f(x,y)=(1โˆ’ly)(1โˆ’lx)โ€‰f(x0,y0)+(1โˆ’ly)โ€‰lxโ€‰f(x0+1,y0)+ly(1โˆ’lx)โ€‰f(x0,y0+1)+lyโ€‰lxโ€‰f(x0+1,y0+1)f(x, y) = (1 - l_y)(1 - l_x)\, f(x_0, y_0) + (1 - l_y)\, l_x\, f(x_0 + 1, y_0) + l_y (1 - l_x)\, f(x_0, y_0 + 1) + l_y\, l_x\, f(x_0 + 1, y_0 + 1)

Closer grid points get larger weights, and the 4 weights sum to 1. In the example at the bottom of the top figure, the value of the point (1.688, 2.25) is obtained as 4.766 by multiplying the values 5, 4, 4, 8 of the 4 surrounding cells by the weights 0.203, 0.047, 0.609, 0.141 and adding them (each cell's value is assumed to lie at the cell's center).

The paper notes that changing the position or number of points makes little difference as long as nothing is rounded. What matters is "never rounding to integers anywhere", not the fine details of the interpolation.

Why not rounding makes a difference

Mask R-CNN predicts an mร—mm \times m (e.g. 28ร—28) mask for each RoI with a small fully convolutional network (FCN). Because an FCN maps input and output positions one to one, each cell of the feature extracted from the RoI must correspond correctly to a fixed position in the image. If RoI pooling shifts the feature by half a cell, that becomes an 8-pixel shift in the image for a feature map with stride 16, and the mask outline shifts by the same amount.

As an analogy, think of tracing a region from a map drawn on graph paper. RoI pooling snaps the corners of the region to the nearest grid lines before tracing, so the traced map is slightly off. RoIAlign uses the region as is and estimates values between grid lines from the surrounding grid.

The paper showed that rounding is the decisive factor by comparing with RoIWarp. RoIWarp (Dai et al., 2016) also uses bilinear interpolation, but rounds the RoI coordinates just like RoI pooling. As a result, RoIWarp's accuracy was almost the same as RoI pooling and far below RoIAlign. What helps is not interpolation itself but aligning positions correctly.

Gradients flow to the 4 grid points used to interpolate each point, in proportion to the interpolation weights. Compared with RoI pooling, which passes the gradient only to the single position of the maximum, gradients reach many positions within the region.

Experimental results

Mask AP by RoI extraction method (COCO, ResNet-50-C4 (feature map stride 16), Table 2c of the paper)

MethodNo roundingBilinear interpolationAggregationAPAP50AP75
RoI poolingMax26.948.826.4
RoIWarpโœ“Max27.249.227.1
RoIWarpโœ“Average27.148.927.1
RoIAlignโœ“โœ“Max30.251.031.8
RoIAlignโœ“โœ“Average30.351.231.5

RoIAlign raised AP by about 3 points over RoI pooling, and AP75, which judges localization strictly, by about 5 points. RoIWarp, which interpolates but still rounds, is almost the same as RoI pooling.

Effect on a feature map with a large stride (ResNet-50-C5 (stride 32), Table 2d of the paper)

MethodMask APMask AP75Box APBox AP75
RoI pooling23.621.628.226.9
RoIAlign30.932.134.036.4

With a stride of 32, the rounding misalignment also grows in image space, so the gap widened to 7.3 points (mask AP). With RoIAlign, the stride-32 feature map (30.9) even achieves higher accuracy than the stride-16 feature map (30.3).

Other results

  • It helps box detection alone too. Replacing RoI pooling with RoIAlign in Faster R-CNN (ResNet-101-FPN) raised box AP by 1.1 points (explanation of Table 3 in the paper).
  • Even with FPN, which has finer-stride features, mask AP rose by 1.5 points and box AP by 0.5 points.
  • For human keypoint detection (ResNet-50-FPN), which needs even finer localization, AP rose from 59.8 to 64.2 (Table 6 of the paper).

Caveats

The aligned argument of torchvision's roi_align defaults to False. False is the legacy implementation, which treats each cell's value as lying at the cell's corner rather than its center, so the sampled positions are shifted by half a cell. True subtracts 0.5 from the coordinates to align them correctly with cell centers (the form used by Detectron2). Use aligned=True when training a new model; when using a model trained with False, match the setting used in training. torchvision's Mask R-CNN implementation uses the default False.

  • Set spatial_scale to the inverse of the feature map stride: Pass boxes in image coordinates; they are multiplied by spatial_scale to get feature map coordinates. Use 1/16 for stride 16, and when using several feature maps as in FPN, match each one's stride (torchvision's MultiScaleRoIAlign chooses the feature map according to the RoI size).
  • sampling_ratio sets the number of points per bin: A positive value places sampling_ratio ร— sampling_ratio points in each bin. With the default -1 (0 or less), the number becomes ceil(RoI width / output width) depending on the RoI size, so larger RoIs get more points and more computation. To use 4 points as in the paper, set sampling_ratio=2 (torchvision's Mask R-CNN also uses this value).
  • Aggregation is the average: torchvision's roi_align averages the point values. In the paper, max and average gave almost the same results.
  • Output size: Mask R-CNN uses 7ร—7 RoIAlign for the class and box head and 14ร—14 for the mask head (Figure 4 of the paper, FPN case).
  • Shape of boxes: 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.
  • 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 RoI, from the same viewpoints.

MethodRoI boundaryBin boundariesHow values are obtainedAggregationMain use
Spatial pyramid poolingRoundedRounded (grids at several levels)Grid values as isMaxSPP-net
RoI poolingRoundedRoundedGrid values as isMaxFast R-CNN, Faster R-CNN
RoIWarpRoundedNot roundedBilinear interpolationMax or averageMNC (Dai et al., 2016)
RoIAlignNot roundedNot roundedBilinear interpolationAverage (max also possible)Mask R-CNN and many later two-stage detectors

There is also deformable RoI pooling, proposed in the deformable convolution paper, which shifts the positions of the RoI itself through learning.

Rough guidelines for choosing:

  • Tasks where pixel-level positions matter, such as masks and keypoints: Use RoIAlign. This is where the paper found the largest difference.
  • Object detection with boxes only: Use RoIAlign for new models. It costs slightly more computation than RoI pooling but also improves box accuracy.
  • Reproducing the original results of Fast R-CNN or Faster R-CNN: Use RoI pooling, as in the original papers.

PyTorch example

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

# Same feature map (1 image, 1 channel, 7 ร— 7) and RoI (image coordinates, feature map stride 16) as the top figure
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 = torch.tensor([[0, 20., 28., 76., 92.]])  # [image index in the batch, x1, y1, x2, y2]

# RoIAlign: no rounding; place 2 ร— 2 = 4 points per bin, interpolate bilinearly, and average
out = roi_align(feat, boxes, output_size=(2, 2),
                spatial_scale=1 / 16,   # Image coordinates โ†’ feature map coordinates
                sampling_ratio=2,       # 2 ร— 2 points per bin (as in the paper). -1 chooses automatically from the RoI size
                aligned=True)           # Put each cell's value at the cell center (default is False)
print(out)  # [[5.58, 5.05], [2.00, 4.35]] (same as the top figure)

# With aligned=False (legacy implementation), sampling is shifted by half a cell, so the values change
print(roi_align(feat, boxes, output_size=2, spatial_scale=1 / 16, sampling_ratio=2, aligned=False))
# [[6.39, 4.49], [1.96, 3.52]]

# For comparison: RoI pooling (rounds coordinates and takes the max)
print(roi_pool(feat, boxes, output_size=2, spatial_scale=1 / 16))  # [[9, 9], [6, 7]]


# Entry points to the two heads of Mask R-CNN (example with a stride-16 feature map and 256 channels)
box_pool = RoIAlign(output_size=(7, 7), spatial_scale=1 / 16, sampling_ratio=2, aligned=True)
mask_pool = RoIAlign(output_size=(14, 14), spatial_scale=1 / 16, sampling_ratio=2, aligned=True)

mask_head = nn.Sequential(  # Figure 4 of the paper (FPN): four 3ร—3 convolutions โ†’ upsample 2ร— โ†’ per-class masks
  *[m for _ in range(4) for m in (nn.Conv2d(256, 256, 3, padding=1), nn.ReLU())],
  nn.ConvTranspose2d(256, 256, 2, stride=2), nn.ReLU(),
  nn.Conv2d(256, 80, 1),    # 80 COCO classes, 28 ร— 28
)

features = torch.randn(2, 256, 50, 68)                        # Feature maps of 2 images (about 800 ร— 1088)
rois = [torch.tensor([[100., 120., 400., 500.]]),             # RoI of the 1st image (image coordinates)
        torch.tensor([[30., 40., 200., 180.], [500., 300., 900., 700.]])]  # 2nd image
print(box_pool(features, rois).shape)                         # torch.Size([3, 256, 7, 7])
masks = mask_head(mask_pool(features, rois))
print(masks.shape)                                            # torch.Size([3, 80, 28, 28])

FAQ

Q. How much does the computational cost of RoIAlign differ from RoI pooling?
A.

RoIAlign places several points in each bin (4 in the paper) and interpolates each from 4 grid points, so it costs more than RoI pooling, which only takes the maximum of the values in a bin. The number of points is set by sampling_ratio; with the default -1, larger RoIs get more points, so fix it to a value such as 2 to keep computation down.

Q. Should `aligned` be True or False?
A.

Use True when training a new model. False treats each cell's value as lying at its corner, so the sampled positions are shifted by half a cell. When using a model trained with False (such as torchvision's Mask R-CNN), however, keep False as in training. Changing it midway feeds in features from different positions than those seen during training.

Q. Is RoIAlign worth using for object detection (boxes only)?
A.

Yes. In the Mask R-CNN paper, simply replacing RoI pooling with RoIAlign in Faster R-CNN, which does not predict masks, raised box AP by 1.1 points. The difference is especially noticeable when the feature map stride is large.

References

  1. K. He, G. Gkioxari, P. Dollรกr, and R. Girshick, "Mask R-CNN," ICCV, 2017.
  2. R. Girshick, "Fast R-CNN," ICCV, 2015.
  3. J. Dai, K. He, and J. Sun, "Instance-aware Semantic Segmentation via Multi-task Network Cascades," CVPR, 2016.
  4. torchvision Documentation, "torchvision.ops.roi_align."