Algorithm Search⌘K

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, H×WH \times W 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 H×WH \times W 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 FF with CC channels and hF×wFh_F \times w_F cells, computed from the image by layers whose stride is 1/s1/s pixels per cell, so s=1/16s = 1/16 for the last convolution of VGG16. A box is (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) in image pixels. The output size H×WH \times W 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

  1. ROIPOOL(F, b, s, H, W) ▷ feature map F (C x h_F x w_F), box b in pixels, scale s
  2. 1(c_1, r_1, c_2, r_2) ← round(s · b) ▷ the box in cells, inclusive ends, halves away from 0
  3. 2h ← max(r_2 - r_1 + 1, 1), w ← max(c_2 - c_1 + 1, 1)
  4. 3for each bin (p, q) with 0 ≤ p < H and 0 ≤ q < W
  5. 4rows ← [r_1 + ⌊p h / H⌋, r_1 + ⌈(p + 1) h / H⌉) clipped to [0, h_F]
  6. 5cols ← [c_1 + ⌊q w / W⌋, c_1 + ⌈(q + 1) w / W⌉) clipped to [0, w_F]
  7. 6for 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
  8. 7return Y, S
  9. BACKWARD(dY, S) ▷ dY: the gradient of the loss with respect to Y
  10. 8dF[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 kk bins changes the loss by the sum of those kk 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 O(C(h+H)(w+W))O(C (h + H)(w + W)) time, since the bins cover the box with at most one shared row or column between neighbors. The backward pass takes O(CHW)O(C H W) time. For RR boxes the forward pass is O(C∑r(hr+H)(wr+W))O(C \sum_r (h_r + H)(w_r + W)), and the network that makes FF runs once for the image, which is the saving over R-CNN. The network cost is outside this page.

Example. Take one channel with 6×86 \times 8 cells and the value (3r+5c) mod 11(3r + 5c) \bmod 11 at row rr and column cc, the scale s=1/4s = 1/4, the box (5,3,26,17)(5, 3, 26, 17) and a 2×22 \times 2 output. Line L1 gives (1.25,0.75,6.5,4.25)(1.25, 0.75, 6.5, 4.25) rounded to (1,1,7,4)(1, 1, 7, 4), so the box covers rows 1 to 4 and columns 1 to 7, with h=4h = 4 and w=7w = 7. The row ranges are [1,3)[1, 3) and [3,5)[3, 5). The column ranges are [1,1+⌈3.5⌉)=[1,5)[1, 1 + \lceil 3.5 \rceil) = [1, 5) and [1+⌊3.5⌋,8)=[4,8)[1 + \lfloor 3.5 \rfloor, 8) = [4, 8), so column 4 is in both. The four maxima are 10 at (2,3)(2, 3), 9 at (2,5)(2, 5), 10 at (4,4)(4, 4) and 10 at (4,4)(4, 4) again. With all output gradients equal to 1, the backward pass gives 2 at (4,4)(4, 4), 1 at (2,3)(2, 3) and at (2,5)(2, 5), and 0 elsewhere. The box (5,2,26,16)(5, 2, 26, 16), 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 H=W=7H = W = 7 and s=1/16s = 1/16, 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 1×11 \times 1, 2×22 \times 2, 3×33 \times 3 and 6×66 \times 6, 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 PkP_k with k=⌊k0+log⁡2(wh/224)⌋k = \lfloor k_0 + \log_2(\sqrt{wh}/224) \rfloor and k0=4k_0 = 4, 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 (p,q)(p, q) 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 H×WH \times W 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 s=1/16s = 1/16, 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 c2−c1+1c_2 - c_1 + 1 cells. Code that uses c2−c1c_2 - c_1 pools a box one cell smaller, and trained weights do not carry over.
  • Rounding rules. C round sends halves away from zero, Python round sends 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.

roi_pooling.pyI0RawGitHub
# 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

  1. Show that for h≥1h \ge 1 the row ranges of line L4 (before the clipping) cover [r1,r1+h)[r_1, r_1 + h), that each is nonempty, and that their lengths sum to at most h+H−1h + H - 1.
  2. A box has h=5h = 5 rows and the output has H=7H = 7 rows. List the row ranges of the seven bins. Which rows appear in two bins?
  3. Show that the backward pass of line L8 is the gradient of ∑c,p,qdY[c][p][q] Y[c][p][q]\sum_{c, p, q} dY[c][p][q] \, Y[c][p][q] with respect to FF at any FF whose bins each have one largest value.
  4. At s=1/16s = 1/16, find two boxes whose sides differ by 15 pixels and that give the same output on every feature map.
  5. 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 h≥1h \ge 1 rows starting at row r1r_1 and an output height H≥1H \ge 1. For 0≤p<H0 \le p < H let ap=⌊ph/H⌋a_p = \lfloor p h / H \rfloor and ep=⌈(p+1)h/H⌉e_p = \lceil (p + 1) h / H \rceil, so line L4 gives the rows [r1+ap,r1+ep)[r_1 + a_p, r_1 + e_p) before the clipping. The columns behave the same way with ww and WW.

Claim 1 (the bins). Before the clipping:

  1. every range is nonempty: ap<epa_p < e_p;
  2. the first range starts at r1r_1 and the last ends at r1+hr_1 + h: a0=0a_0 = 0 and eH−1=he_{H-1} = h;
  3. next ranges leave no gap and share at most one row: ap+1≤ep≤ap+1+1a_{p+1} \le e_p \le a_{p+1} + 1;
  4. the ranges cover [r1,r1+h)[r_1, r_1 + h), and their lengths sum to at most h+H−1h + H - 1.

Proof. (1) Since h≥1h \ge 1, (p+1)h/H>ph/H(p + 1)h/H > p h / H, so ep≥(p+1)h/H>ph/H≥ape_p \ge (p + 1) h / H > p h / H \ge a_p, and ap<epa_p < e_p as both are integers. (2) a0=⌊0⌋=0a_0 = \lfloor 0 \rfloor = 0 and eH−1=⌈h⌉=he_{H-1} = \lceil h \rceil = h. (3) Let z=(p+1)h/Hz = (p + 1) h / H. Then ap+1=⌊z⌋a_{p+1} = \lfloor z \rfloor and ep=⌈z⌉e_p = \lceil z \rceil, and ⌊z⌋≤⌈z⌉≤⌊z⌋+1\lfloor z \rfloor \le \lceil z \rceil \le \lfloor z \rfloor + 1. (4) By (3) range p+1p + 1 starts no later than range pp ends, so by (2) the union of the ranges is [r1,r1+h)[r_1, r_1 + h) with no gap. For the lengths, ∑p=0H−1(ep−ap)=(eH−1−a0)+∑p=0H−2(ep−ap+1)≤h+(H−1)\sum_{p=0}^{H-1} (e_p - a_p) = (e_{H-1} - a_0) + \sum_{p=0}^{H-2} (e_p - a_{p+1}) \le h + (H - 1), by (2) and (3). □\square

When h<Hh < H a row can lie in more than two ranges; for h=1h = 1 and H=3H = 3 all three ranges are [r1,r1+1)[r_1, r_1 + 1). The sum in item 4 gives the cost bound of the page. The clipping of line L4 to [0,hF][0, h_F] 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 cc and bin (p,q)(p, q) with a nonempty clipped range Rp×QqR_p \times Q_q, line L6 sets Y[c][p][q]=max⁡(r,k)∈Rp×QqF[c][r][k]Y[c][p][q] = \max_{(r, k) \in R_p \times Q_q} F[c][r][k] and S[c][p][q]S[c][p][q] 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. □\square

Claim 3 (backward). Let L=∑c,p,qdY[c][p][q] Y[c][p][q]L = \sum_{c, p, q} dY[c][p][q] \, Y[c][p][q], a function of FF. At any FF where every nonempty bin of every channel has exactly one cell with the largest value, LL is differentiable in FF and ∂L/∂F[c][r][k]=∑dY[c][p][q]\partial L / \partial F[c][r][k] = \sum dY[c][p][q] over the bins (p,q)(p, q) with S[c][p][q]=(r,k)S[c][p][q] = (r, k), which is the value of line L8.

Proof. In a bin with a unique largest value at cell xx, the gap δ\delta between that value and the second largest is positive. If every cell changes by less than δ/2\delta/2, the largest value stays at xx, so Y[c][p][q]=F[c][x]Y[c][p][q] = F[c][x] on a neighborhood of FF. Take the smallest δ\delta over the finitely many bins. On that neighborhood LL is the linear function ∑dY[c][p][q] F[c][S[c][p][q]]\sum dY[c][p][q] \, F[c][S[c][p][q]], and its partial derivative in F[c][r][k]F[c][r][k] is the sum of the dY[c][p][q]dY[c][p][q] whose switch is (r,k)(r, k). Empty bins add the constant 0. □\square

When a bin has a tie, LL 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 G[c][r][k]=F[c][r−Δr][k−Δk]G[c][r][k] = F[c][r - \Delta_r][k - \Delta_k] for integers Δr,Δk\Delta_r, \Delta_k, and let b′b' be the box bb moved by Δk/s\Delta_k / s pixels in xx and Δr/s\Delta_r / s in yy. If both boxes have nonnegative coordinates and no clipping happens for either box, ROIPOOL(G, b') = ROIPOOL(F, b), and the switches move by (Δr,Δk)(\Delta_r, \Delta_k).

Proof. With round⁡\operatorname{round} sending halves away from zero, round⁡(t+n)=round⁡(t)+n\operatorname{round}(t + n) = \operatorname{round}(t) + n for an integer nn whenever t≥0t \ge 0 and t+n≥0t + n \ge 0. Under the stated conditions line L1 adds Δk\Delta_k to c1c_1 and c2c_2 and Δr\Delta_r to r1r_1 and r2r_2, so hh and ww do not change, and every range of lines L4 and L5 moves by the same amount. Each bin of GG then holds the values of the same bin of FF. □\square

The same argument shows the rounding error: line L1 moves each side by at most half a cell, that is, by at most 1/(2s)1/(2s) pixels, and all boxes whose four sides round to the same cells give the same output.

References

  1. 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)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/BAJKQQ/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises