Techniqueadvanced
RoI pooling
Also called region of interest pooling, RoIAlign.
Turn the feature cells under a box into a fixed grid by max pooling over rounded bins. RoIAlign, with bilinear samples and no rounding, is the different step of Mask R-CNN.
RoI pooling turns the part of a convolutional feature map under one box into a grid of fixed size, cells per channel, so that the same fully connected layers can classify boxes of every size. Fast R-CNN introduced it to share one pass of the network over the whole image among all the object proposals, where R-CNN ran the network once per proposal. The layer rounds the box to feature cells, cuts it into bins of nearly equal size, and takes the maximum of each bin. Its backward pass sends each output gradient to the one input cell that gave the maximum. The rounding makes the output a step function of the box position. RoIAlign, the replacement in Mask R-CNN, is a different operation: it samples the map by bilinear interpolation at points with no rounding.
In plain words
A detector has computed a grid of features for the whole image, and it has a list of candidate boxes of all sizes. The classifier after it wants the same amount of input for every box. RoI pooling cuts the part of the feature grid under each box into, for example, 7 by 7 pieces. A big box gives big pieces, a small box gives small ones. From each piece it keeps only the largest value. So every box gives exactly 7 by 7 numbers per feature channel. The features are computed once for the image, and each box only reads its own part of them. The cost is that the box is first snapped to the coarse feature grid, so its position becomes a little inexact.
When it applies
The technique needs a feature map with channels and cells, computed from the image by layers whose stride is pixels per cell, so for the last convolution of VGG16. A box is in image pixels. The output size is fixed by the layers that follow.
It fits a two-stage detector, where a fixed set of boxes is given and each needs a fixed-size feature: Fast R-CNN with external proposals, and Faster R-CNN with its own proposals. With a feature pyramid network, each box is pooled from the level that fits its size. It fits less well when the exact position matters, for example for masks or for a high IoU threshold, since the rounding moves the box by up to half a cell.
The template
ROIPOOL(F, b, s, H, W) ▷ feature map F (C x h_F x w_F), box b in pixels, scale s- 1
(c_1, r_1, c_2, r_2) ← round(s · b) ▷ the box in cells, inclusive ends, halves away from 0 - 2
h ← max(r_2 - r_1 + 1, 1), w ← max(c_2 - c_1 + 1, 1) - 3
for each bin (p, q) with 0 ≤ p < H and 0 ≤ q < W - 4
rows ← [r_1 + ⌊p h / H⌋, r_1 + ⌈(p + 1) h / H⌉) clipped to [0, h_F] - 5
cols ← [c_1 + ⌊q w / W⌋, c_1 + ⌈(q + 1) w / W⌉) clipped to [0, w_F] - 6
for each channel c: Y[c][p][q] ← max of F[c] over rows x cols, S[c][p][q] ← its first argmax; 0 and none if the bin is empty - 7
return Y, S BACKWARD(dY, S) ▷ dY: the gradient of the loss with respect to Y- 8
dF[c][S[c][p][q]] += dY[c][p][q] for every c, p, q with a nonempty bin; all other dF are 0
Lines L4 and L5 follow the reference Caffe layer, which uses floor at the start and ceil at the end of each bin. So the bins of one box cover all its cells, next bins share at most one row or column, and every bin of a box inside the map has at least one cell, also when the box has fewer cells than bins. The forward pass is a maximum, and the backward pass is its gradient wherever each bin has one largest value: a small change of a cell that is the maximum of bins changes the loss by the sum of those output gradients, and a change of any other cell does nothing. These facts are proved in the proof page.
Cost. For one box, lines L4 to L6 read each cell of a bin once per channel, so the forward pass takes time, since the bins cover the box with at most one shared row or column between neighbors. The backward pass takes time. For boxes the forward pass is , and the network that makes runs once for the image, which is the saving over R-CNN. The network cost is outside this page.
Example. Take one channel with cells and the value at row and column , the scale , the box and a output. Line L1 gives rounded to , so the box covers rows 1 to 4 and columns 1 to 7, with and . The row ranges are and . The column ranges are and , so column 4 is in both. The four maxima are 10 at , 9 at , 10 at and 10 at again. With all output gradients equal to 1, the backward pass gives 2 at , 1 at and at , and 0 elsewhere. The box , one pixel higher, rounds to the same cells and gives the same output.
Implementation. The Python code has the forward pass with the rounding of the Caffe layer in exact integer form, the switches, the backward pass, and a helper for a list of boxes. It does not have RoIAlign. The tests check the example above, the C rounding of halves, the bin limits against floor and ceil on 300 random sizes, the outputs and switches against a brute force maximum, the backward pass against finite differences, the equality under a shift by whole cells, a one-pixel shift that the rounding hides, and empty and one-cell boxes.
Classic examples
- Fast R-CNN. RoI pooling on the conv5 map of VGG16 with and , for about 2000 selective search proposals per image. The paper reports a test time of about 0.3 seconds per image without the proposal step, against many seconds for R-CNN (benchmark results of the 2015 paper).
- Faster R-CNN. The same layer on the proposals of the region proposal network, so the two stages share one feature map.
- SPP-net. The forerunner of RoI pooling: a spatial pyramid of max pooling grids, for example , , and , on the region of each window. RoI pooling is the case of one level, and Fast R-CNN made the layer trainable end to end.
- Feature pyramid network. Each box is pooled from the pyramid level with and , so a small box reads a fine map.
Variations
- RoIAlign. Mask R-CNN keeps the box and the bin limits as real numbers, samples a few points in each bin by bilinear interpolation, and takes their average or maximum. The output is then a continuous function of the box, and the paper reports large gains in mask accuracy and gains in box accuracy (benchmark results).
- Precise RoI pooling. Integrates the bilinear interpolant over each bin, which makes the output differentiable in the box coordinates too.
- Position-sensitive RoI pooling. R-FCN pools bin from its own group of channels, so the per-box layers after the pooling are almost free.
- Average pooling. Takes the mean of each bin instead of the maximum; the backward pass then spreads the gradient evenly over the bin.
- Crop and resize. Some code crops the box from the map and resizes the crop to with bilinear interpolation, which is close to RoIAlign with one sample per bin.
Pitfalls
- Misalignment. Rounding the box to cells moves each side by up to half a cell, 8 pixels at , and the floor and ceil of the bins add up to one more cell. For a small box this is a large part of its size. It is the problem that RoIAlign solves.
- Inclusive ends. The Caffe layer counts cells. Code that uses pools a box one cell smaller, and trained weights do not carry over.
- Rounding rules. C
roundsends halves away from zero, Pythonroundsends them to the even integer, and floor and ceil computed in floating point can differ from the exact values at whole numbers. Each changes some boxes by a cell. - Empty bins. A box partly or fully outside the map has empty bins. The layer outputs 0 there and passes no gradient.
- No gradient for the box. The output is a step function of the box coordinates, so its derivative with respect to the box is 0 almost everywhere. Box quality can only be learned by the regression head, not through the pooling.
- Ties. With equal values in a bin, the switch is the first in row-major order, and the whole gradient goes to that one cell.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/roi-pooling/. The authors are listed in prov/BAJKQQ.jsonl.
"""RoI max pooling of Fast R-CNN, with the rounding of the original Caffe layer.
A feature map is a list of channels; a channel is a list of rows of numbers.
A box is (x1, y1, x2, y2) in image pixels, and scale is the ratio between the
feature map and the image (1/16 for VGG16 conv5). The box is rounded to
feature cells, with inclusive ends, and the H x W grid of bins uses floor for
the start and ceil for the end of each bin. The integer form below computes
floor(p h / H) and ceil((p + 1) h / H) exactly; the Caffe layer uses floats,
which can differ when p h / H is a whole number up to a rounding error.
Standard library only.
"""
def round_half_away(x):
"""C round(): halves go away from zero."""
return int(x + 0.5) if x >= 0 else -int(-x + 0.5)
def ceil_div(a, b):
return -((-a) // b)
def roi_box_cells(box, scale):
"""The box in feature cells: (c1, r1, c2, r2) with inclusive ends, and its size (h, w)."""
c1, r1 = round_half_away(box[0] * scale), round_half_away(box[1] * scale) # @line L1
c2, r2 = round_half_away(box[2] * scale), round_half_away(box[3] * scale)
h, w = max(r2 - r1 + 1, 1), max(c2 - c1 + 1, 1) # @line L2
return (c1, r1, c2, r2), (h, w)
def bins(box, scale, out_h, out_w, fh, fw):
"""For each bin (p, q), the half-open row range and column range it covers on the map."""
(c1, r1, _, _), (h, w) = roi_box_cells(box, scale)
out = {}
for p in range(out_h): # @line L3
for q in range(out_w):
rs = min(max(r1 + (p * h) // out_h, 0), fh) # @line L4
re = min(max(r1 + ceil_div((p + 1) * h, out_h), 0), fh)
cs = min(max(c1 + (q * w) // out_w, 0), fw) # @line L5
ce = min(max(c1 + ceil_div((q + 1) * w, out_w), 0), fw)
out[(p, q)] = (rs, re, cs, ce)
return out
def roi_pool(feat, box, scale, out_h, out_w):
"""Return (Y, S): pooled values and argmax switches (row, col), or None for an empty bin.
Ties go to the first cell in row-major order, as the strict > of the Caffe loop.
"""
fh, fw = len(feat[0]), len(feat[0][0])
grid = bins(box, scale, out_h, out_w, fh, fw)
y, s = [], []
for ch in feat:
yc = [[0.0] * out_w for _ in range(out_h)]
sc = [[None] * out_w for _ in range(out_h)]
for (p, q), (rs, re, cs, ce) in grid.items():
best, arg = None, None
for r in range(rs, re):
for c in range(cs, ce):
if best is None or ch[r][c] > best:
best, arg = ch[r][c], (r, c)
if arg is not None:
yc[p][q], sc[p][q] = best, arg # @line L6
y.append(yc)
s.append(sc)
return y, s # @line L7
def roi_pool_backward(dy, switches, fh, fw):
"""Gradient on the feature map: each bin sends its gradient to its argmax cell."""
out = []
for dyc, sc in zip(dy, switches):
g = [[0.0] * fw for _ in range(fh)]
for p, row in enumerate(sc):
for q, arg in enumerate(row):
if arg is not None:
g[arg[0]][arg[1]] += dyc[p][q] # @line L8
out.append(g)
return out
def roi_pool_many(feat, boxes, scale, out_h, out_w):
"""Pool every box of a list; the cost of each box is that of its own bins."""
return [roi_pool(feat, b, scale, out_h, out_w)[0] for b in boxes]
test_roi_pooling.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/roi-pooling/. The authors are listed in prov/BAJKQQ.jsonl.
import math
import random
from roi_pooling import (
bins,
roi_box_cells,
roi_pool,
roi_pool_backward,
roi_pool_many,
round_half_away,
)
FEAT = [[[(3 * r + 5 * c) % 11 for c in range(8)] for r in range(6)]]
BOX = (5, 3, 26, 17)
def test_page_example():
assert roi_box_cells(BOX, 0.25) == ((1, 1, 7, 4), (4, 7))
assert bins(BOX, 0.25, 2, 2, 6, 8) == {
(0, 0): (1, 3, 1, 5), (0, 1): (1, 3, 4, 8),
(1, 0): (3, 5, 1, 5), (1, 1): (3, 5, 4, 8),
}
y, s = roi_pool(FEAT, BOX, 0.25, 2, 2)
assert y == [[[10, 9], [10, 10]]]
assert s == [[[(2, 3), (2, 5)], [(4, 4), (4, 4)]]]
g = roi_pool_backward([[[1.0, 1.0], [1.0, 1.0]]], s, 6, 8)
assert g[0][4][4] == 2.0 and g[0][2][3] == 1.0 and g[0][2][5] == 1.0
assert sum(sum(row) for row in g[0]) == 4.0
def test_rounding():
assert [round_half_away(v) for v in (0.5, 1.5, 2.5, -0.5, -1.5, 0.49)] == [1, 2, 3, -1, -2, 0]
def brute_bins(h, w, out_h, out_w):
rows = [(math.floor(p * h / out_h), math.ceil((p + 1) * h / out_h)) for p in range(out_h)]
cols = [(math.floor(q * w / out_w), math.ceil((q + 1) * w / out_w)) for q in range(out_w)]
return rows, cols
def test_bins_cover_the_box():
rng = random.Random(1)
for _ in range(300):
h, w = rng.randint(1, 30), rng.randint(1, 30)
out_h, out_w = rng.randint(1, 8), rng.randint(1, 8)
rows, cols = brute_bins(h, w, out_h, out_w)
box = (0, 0, w - 1, h - 1)
got = bins(box, 1, out_h, out_w, 100, 100)
for p in range(out_h):
for q in range(out_w):
assert got[(p, q)] == (rows[p][0], rows[p][1], cols[q][0], cols[q][1])
# Every row of the box is in some bin, bins are in order, and next bins share at most one row.
assert rows[0][0] == 0 and rows[-1][1] == h
for p in range(out_h - 1):
assert rows[p][0] <= rows[p + 1][0] and rows[p + 1][0] <= rows[p][1] <= rows[p + 1][0] + 1
for p in range(out_h):
assert rows[p][1] - rows[p][0] >= 1
def test_against_brute_force_max():
rng = random.Random(2)
for _ in range(100):
fh, fw = rng.randint(3, 12), rng.randint(3, 12)
feat = [[[rng.randint(-20, 20) for _ in range(fw)] for _ in range(fh)] for _ in range(2)]
scale = rng.choice([1.0, 0.5, 0.25, 1 / 16])
x1, y1 = rng.uniform(-3, fw / scale), rng.uniform(-3, fh / scale)
box = (x1, y1, x1 + rng.uniform(0, fw / scale), y1 + rng.uniform(0, fh / scale))
out_h, out_w = rng.randint(1, 4), rng.randint(1, 4)
y, s = roi_pool(feat, box, scale, out_h, out_w)
grid = bins(box, scale, out_h, out_w, fh, fw)
for c in range(2):
for (p, q), (rs, re, cs, ce) in grid.items():
cells = [(feat[c][r][k], r, k) for r in range(rs, re) for k in range(cs, ce)]
if not cells:
assert y[c][p][q] == 0.0 and s[c][p][q] is None
else:
best = max(v for v, _, _ in cells)
first = next((r, k) for v, r, k in cells if v == best)
assert y[c][p][q] == best and s[c][p][q] == first
def test_backward_matches_finite_differences():
rng = random.Random(3)
fh, fw = 9, 11
for _ in range(10):
vals = rng.sample(range(10000), fh * fw)
feat = [[[vals[r * fw + c] / 100.0 for c in range(fw)] for r in range(fh)]]
box = (rng.uniform(0, 16), rng.uniform(0, 16), rng.uniform(20, 40), rng.uniform(20, 32))
dy = [[[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]]
_, s = roi_pool(feat, box, 0.25, 3, 3)
g = roi_pool_backward(dy, s, fh, fw)
def loss(f):
y, _ = roi_pool(f, box, 0.25, 3, 3)
return sum(y[0][p][q] * dy[0][p][q] for p in range(3) for q in range(3))
eps = 1e-4
for r in range(fh):
for c in range(fw):
plus = [[row[:] for row in feat[0]]]
minus = [[row[:] for row in feat[0]]]
plus[0][r][c] += eps
minus[0][r][c] -= eps
num = (loss(plus) - loss(minus)) / (2 * eps)
assert abs(num - g[0][r][c]) < 1e-6
def test_shift_by_whole_cells():
# Moving the box by whole cells and the content with it gives the same output.
rng = random.Random(4)
base = [[rng.randint(0, 99) for _ in range(20)] for _ in range(20)]
box = (13, 9, 50, 45)
y0, _ = roi_pool([base], box, 0.25, 7, 7)
shifted = [[base[(r - 2) % 20][(c - 3) % 20] for c in range(20)] for r in range(20)]
y1, _ = roi_pool([shifted], (box[0] + 12, box[1] + 8, box[2] + 12, box[3] + 8), 0.25, 7, 7)
assert y0 == y1
def test_quantization_hides_small_shifts():
# A shift of less than half a cell (2 pixels at scale 1/4) can leave the output unchanged.
moved = (BOX[0], BOX[1] - 1, BOX[2], BOX[3] - 1)
assert roi_box_cells(moved, 0.25) == roi_box_cells(BOX, 0.25)
y0 = roi_pool_many(FEAT, [BOX, moved], 0.25, 2, 2)
assert y0[0] == y0[1]
def test_empty_bins_and_outside_box():
y, s = roi_pool(FEAT, (100, 100, 120, 120), 0.25, 2, 2)
assert y == [[[0.0, 0.0], [0.0, 0.0]]] and s == [[[None, None], [None, None]]]
# A box of one cell with a 2 x 2 output: every bin is that cell.
y, _ = roi_pool(FEAT, (8, 8, 8, 8), 0.25, 2, 2)
assert y == [[[FEAT[0][2][2]] * 2] * 2]
Exercises
- Show that for the row ranges of line L4 (before the clipping) cover , that each is nonempty, and that their lengths sum to at most .
- A box has rows and the output has rows. List the row ranges of the seven bins. Which rows appear in two bins?
- Show that the backward pass of line L8 is the gradient of with respect to at any whose bins each have one largest value.
- At , find two boxes whose sides differ by 15 pixels and that give the same output on every feature map.
- Write RoIAlign with one sample at the center of each bin, and show that its output is a continuous function of the box coordinates.
Proof: The RoI pooling bins cover the box with nonempty, nearly disjoint ranges, the forward pass is the bin maximum, and the backward pass is its gradientfull
Fix a box with rows starting at row and an output height . For let and , so line L4 gives the rows before the clipping. The columns behave the same way with and .
Claim 1 (the bins). Before the clipping:
- every range is nonempty: ;
- the first range starts at and the last ends at : and ;
- next ranges leave no gap and share at most one row: ;
- the ranges cover , and their lengths sum to at most .
Proof. (1) Since , , so , and as both are integers. (2) and . (3) Let . Then and , and . (4) By (3) range starts no later than range ends, so by (2) the union of the ranges is with no gap. For the lengths, , by (2) and (3).
When a row can lie in more than two ranges; for and all three ranges are . The sum in item 4 gives the cost bound of the page. The clipping of line L4 to intersects each range with the rows of the map, which can only shrink the ranges, and makes a range empty only when it lies outside the map.
Claim 2 (forward). For every channel and bin with a nonempty clipped range , line L6 sets and to the first cell in row-major order where the maximum is attained.
Proof. The loop visits the cells of the bin in row-major order and replaces the current best only on a strictly larger value. After the loop the best value is the maximum of the visited values, and since later equal values do not replace it, the switch is the first cell with that value.
Claim 3 (backward). Let , a function of . At any where every nonempty bin of every channel has exactly one cell with the largest value, is differentiable in and over the bins with , which is the value of line L8.
Proof. In a bin with a unique largest value at cell , the gap between that value and the second largest is positive. If every cell changes by less than , the largest value stays at , so on a neighborhood of . Take the smallest over the finitely many bins. On that neighborhood is the linear function , and its partial derivative in is the sum of the whose switch is . Empty bins add the constant 0.
When a bin has a tie, may not be differentiable there; line L8 then returns one subgradient, the one that sends the gradient to the first cell.
Claim 4 (whole-cell shifts). Let for integers , and let be the box moved by pixels in and in . If both boxes have nonnegative coordinates and no clipping happens for either box, ROIPOOL(G, b') = ROIPOOL(F, b), and the switches move by .
Proof. With sending halves away from zero, for an integer whenever and . Under the stated conditions line L1 adds to and and to and , so and do not change, and every range of lines L4 and L5 moves by the same amount. Each bin of then holds the values of the same bin of .
The same argument shows the rounding error: line L1 moves each side by at most half a cell, that is, by at most pixels, and all boxes whose four sides round to the same cells give the same output.
References
- Ross Girshick, Fast R-CNN, ICCV 2015, 1440-1448, Section 2.1, The RoI pooling layer (an H x W grid of sub-windows of about h/H x w/W, max pooling in each, H = W = 7 for VGG16), and Section 2.3, Back-propagation through RoI pooling layers (Eq. 4)
- Ross Girshick, caffe-fast-rcnn, the RoI pooling layer of the reference Fast R-CNN code (MIT license), Forward_cpu (round of the box times spatial_scale, inclusive size, floor and ceil bin limits, clipping, empty bins set to 0, argmax switches)
- Kaiming He, Georgia Gkioxari, Piotr Dollar and Ross Girshick, Mask R-CNN, ICCV 2017, Section 3, paragraph RoIAlign (the misalignment from quantization, bilinear samples with no rounding)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag BAJKQQ Edit this page History Report an error Markdown