Algorithm Search⌘K

Algorithmadvanced

Fast R-CNN

Also called Fast RCNN.

Compute the CNN features of an image once, pool each proposal from them by RoI pooling, and classify and regress all proposals in one network.

Time
O(R c (m + H)^2 + K R^2) worst
Space
O(c H^2 + R K) extra
Where
H = the number of bins per side; K = the number of object classes; R = the number of RoIs; c = the number of channels; m = the largest side of an RoI in feature cells
Properties
deterministicnot exactofflineiterative
Origin
Ross Girshick, 2015

Fast R-CNN is the detector that fixed the speed problem of R-CNN. R-CNN ran a CNN on each of about 2000 warped proposals. Fast R-CNN runs the convolutional layers once on the whole image, and then cuts a fixed-size feature grid for each proposal out of the shared feature map with RoI pooling. Fully connected layers turn each grid into two outputs: a softmax over KK object classes and background, and four box offsets for each class, the encoding of bounding box regression. One multi-task loss, a log loss plus a smooth L1 box loss, trains the whole network at once, with gradients that flow back through RoI pooling. With VGG16 it trains 9 times faster than R-CNN and tests 213 times faster, at about 0.3 seconds per image, with a higher mAP. The proposals still come from outside, usually from selective search; Faster R-CNN moved them into the network.

In plain words

R-CNN looked at each candidate box of a photo on its own, so it read the same pixels again and again. Fast R-CNN reads the whole photo once and makes a map of features, a smaller grid where each cell describes a patch of the photo. For each candidate box it takes the part of the map under the box and squeezes it into a small grid of fixed size, say 7 by 7, by taking the largest value in each part. Then a small network looks at that grid and answers two questions at once: what is in the box, and how should the box move to fit the object. Both answers are learned together. Many boxes then land on the same object, so the best box is kept and the others are removed.

The problem

The input is an image, a set of proposals (RoIs) in image pixels, and a trained network in two parts: the convolutional layers, which give a feature map with cc channels at a stride of 1/scale1/\text{scale} pixels (16 for VGG16), and a head that maps an H×WH \times W grid of pooled features to K+1K + 1 class scores and 4K4K offsets. The output is a list of boxes with a class and a score. How good it is depends on the training and is measured by detection mean average precision. This page proves facts about the steps that are not learned, and leaves the network out.

The algorithm

  1. FAST-R-CNN-DETECT(I, RoIs, conv, head, τ)
  2. 1F ← conv(I scaled so that its shorter side is s) ▷ once per image, outside this page
  3. 2for each RoI r
  4. 3x_r ← ROI-POOL(F, r · scale) into H × W bins ▷ max over each bin
  5. 4(z_r, t_r) ← head(x_r); p_r ← softmax(z_r) ▷ K + 1 scores, 4K offsets
  6. 5for each class k = 1, ..., K
  7. 6B_{r,k} ← DECODE(r, t_r^k) for every r
  8. 7keep_k ← greedy NMS of the B_{r,k} with scores p_{r,k} at threshold τ
  9. 8return the detections (k, p_{r,k}, B_{r,k}) for r in keep_k, for every k

RoI pooling (line L3). The RoI is mapped to feature cells and split into H×WH \times W bins of about equal size, here 7×77 \times 7, and each bin takes the maximum of its cells in each channel. The output size does not depend on the RoI size, so the fully connected layers of a classification network fit on top. The exact rounding and the backward pass are on the RoI pooling page: the gradient of a bin goes to the cell that held its maximum, and a cell that is the maximum of several bins gets the sum.

The multi-task loss. For an RoI with true class uu (0 for background) and box target vv, with pp the softmax and tut^u the offsets for class uu,

L(p,u,tu,v)=−log⁡pu+λ[u≥1]∑i∈{x,y,w,h}smooth⁡L1(tiu−vi),smooth⁡L1(x)={0.5x2∣x∣<1∣x∣−0.5otherwise.L(p, u, t^u, v) = -\log p_u + \lambda [u \ge 1] \sum_{i \in \{x, y, w, h\}} \operatorname{smooth}_{L_1}(t^u_i - v_i), \qquad \operatorname{smooth}_{L_1}(x) = \begin{cases} 0.5 x^2 & |x| < 1 \\ |x| - 0.5 & \text{otherwise.} \end{cases}

The paper uses λ=1\lambda = 1 and normalizes the targets vv to zero mean and unit variance, so decoding first undoes that normalization. Background RoIs have no box loss. The smooth L1 term is the Huber loss with threshold 1: its gradient has absolute value at most 1, so a far-off target cannot make the gradient explode, which the L2 loss of R-CNN could.

Mini-batches. SGD uses N=2N = 2 images and R=128R = 128 RoIs per batch, so 64 RoIs per image. Up to 25 percent are foreground, RoIs with IoU at least 0.5 with a ground truth box, which take that box's class. The rest are background, RoIs whose largest IoU is in [0.1,0.5)[0.1, 0.5). The lower limit 0.1 acts as a simple form of hard example mining. Since the RoIs of one image share their feature map, a batch of 128 RoIs from 2 images costs about as much as 2 images, not 128.

Truncated SVD. At test time the fully connected layers take a large part of the time, since they run once per RoI. Fast R-CNN replaces a layer WW with the two smaller layers of its rank-tt truncated singular value decomposition UtΣtVtTU_t \Sigma_t V_t^T, which cuts the cost from uvuv to t(u+v)t(u + v) for a u×vu \times v matrix.

Example

One ground truth box g=(0,0,10,10)g = (0, 0, 10, 10) of class 1 and five RoIs:

RoI box IoU with gg role
r1r_1 (0, 0, 10, 8) 4/5 foreground, class 1
r2r_2 (0, 0, 10, 6) 3/5 foreground, class 1
r3r_3 (6, 0, 16, 10) 1/4 background
r4r_4 (9, 0, 19, 10) 1/19 not used, below 0.1
r5r_5 (30, 30, 40, 40) 0 not used

A batch of 4 RoIs from this image takes one foreground RoI (25 percent of 4) at random and fills the rest with background; only r3r_3 qualifies, so the batch has 2 RoIs. Say the network gives r1r_1 the softmax (0.2,0.8)(0.2, 0.8) and the offsets t1=(0.5,−2,0,0.1)t^1 = (0.5, -2, 0, 0.1), and its target is v=0v = 0. The loss is

−log⁡0.8+(0.125+1.5+0+0.005)≈0.223+1.630=1.853.-\log 0.8 + (0.125 + 1.5 + 0 + 0.005) \approx 0.223 + 1.630 = 1.853.

The second offset is in the linear part of smooth L1, so it adds 2−0.5=1.52 - 0.5 = 1.5 and not 0.5⋅4=20.5 \cdot 4 = 2. For a background RoI only −log⁡p0-\log p_0 counts, whatever the offsets.

For RoI pooling, the check value of the RoI pooling page applies: on the map (3r+5c) mod 11(3r + 5c) \bmod 11 of 6×86 \times 8 cells, the box (5,3,26,17)(5, 3, 26, 17) at scale 1/41/4 pools to [[10,9],[10,10]][[10, 9], [10, 10]] on a 2×22 \times 2 grid.

Correctness

The network has no correctness theorem; its accuracy is measured. For the steps that are not learned, the proof page shows:

  1. RoI pooling and its gradient. Each bin outputs the maximum of its cells, and where the maximum is unique the backward pass is the exact gradient of the pooled output with respect to the feature map.
  2. Loss. Smooth L1 is continuous with a continuous derivative of absolute value at most 1, and the loss has no box term for background RoIs.
  3. Decoding. Decoding with the normalization undone inverts the encoding.
  4. Sampling. Every sampled foreground RoI has IoU at least 0.5 with the box whose class it takes, every background RoI has largest IoU in [0.1,0.5)[0.1, 0.5), and there are at most round⁡(0.25⋅batch)\operatorname{round}(0.25 \cdot \text{batch}) foreground RoIs.
  5. NMS. The kept boxes of a class overlap by at most τ\tau, and each dropped box overlaps a kept box of at least the same score by more than τ\tau.

The tests check all five, the first by finite differences.

Proof: RoI pooling outputs bin maxima with the argmax rule as its gradient, smooth L1 has a bounded gradient, decoding inverts the encoding, and the RoI sampling and NMS follow their rulesfull

The convolutional layers and the head are learned and outside the claims. The claims are about the steps of the page that are not learned, as the Python code does them.

Claim 1 (RoI pooling and its gradient). Fix an RoI and let RpqR_{pq} be the cells of bin (p,q)(p, q) after rounding and clipping. For every channel, line L3 sets Ypq=max⁡(r,k)∈RpqFrkY_{pq} = \max_{(r, k) \in R_{pq}} F_{rk} when RpqR_{pq} is not empty, and 0 otherwise. If every nonempty bin has a unique maximum cell apqa_{pq}, then for any weights ww the gradient of ∑pqwpqYpq\sum_{pq} w_{pq} Y_{pq} with respect to FrkF_{rk} is ∑pq:apq=(r,k)wpq\sum_{pq : a_{pq} = (r, k)} w_{pq}, which is what the backward pass returns.

Proof. The loop visits every cell of RpqR_{pq} and replaces the current value only when the new one is larger, or when the bin has no value yet, so it ends with the maximum and the first cell where it is reached. If the maximum is unique there is a gap δ>0\delta > 0 between FapqF_{a_{pq}} and every other cell of the bin. A change of the map smaller than δ/2\delta / 2 in every cell keeps the same argmax, so near FF the output YpqY_{pq} equals FapqF_{a_{pq}}, a linear function of the map with gradient 1 at apqa_{pq} and 0 elsewhere. Summing over the bins with the weights gives the claim. The backward pass adds wpqw_{pq} to the cell apqa_{pq} for every bin, which is the same sum. Empty bins are constant and add nothing. □\square

When a maximum is not unique the function is not differentiable there, and the code sends the gradient to the first cell, as the original layer does. The bin layout itself is proved on the RoI pooling page: the bins of a row cover the RoI with no gap, and next bins share at most one row or column.

Claim 2 (smooth L1). smooth⁡L1(x)=x2/2\operatorname{smooth}_{L_1}(x) = x^2/2 for ∣x∣<1|x| < 1 and ∣x∣−1/2|x| - 1/2 otherwise is continuous and has the continuous derivative g(x)=xg(x) = x for ∣x∣<1|x| < 1 and sign⁡(x)\operatorname{sign}(x) otherwise, with ∣g(x)∣≤1|g(x)| \le 1.

Proof. At ∣x∣=1|x| = 1 both pieces give 1/21/2, and both derivatives give ±1\pm 1, so the function and its derivative are continuous. Inside (−1,1)(-1, 1), ∣g(x)∣=∣x∣<1|g(x)| = |x| < 1, and outside ∣g(x)∣=1|g(x)| = 1. □\square

So the box term of the loss changes each offset gradient by at most λ\lambda, however far the target is, while the L2 loss x2/2x^2/2 has gradient xx, which grows without bound. For u=0u = 0 the factor [u≥1][u \ge 1] is zero and the loss is −log⁡p0-\log p_0 alone, whatever the offsets.

Claim 3 (decoding). Let enc⁡\operatorname{enc} map an RoI rr and a box gg to d=((gx−rx)/rw,(gy−ry)/rh,log⁡(gw/rw),log⁡(gh/rh))d = ((g_x - r_x)/r_w, (g_y - r_y)/r_h, \log(g_w / r_w), \log(g_h / r_h)) and then to ti=(di−μi)/σit_i = (d_i - \mu_i)/\sigma_i with σi>0\sigma_i > 0. Then DECODE⁡(r,enc⁡(r,g))=g\operatorname{DECODE}(r, \operatorname{enc}(r, g)) = g.

Proof. Decoding first computes tiσi+μi=dit_i \sigma_i + \mu_i = d_i. Then it puts the center at rx+rw(gx−rx)/rw=gxr_x + r_w (g_x - r_x)/r_w = g_x and the width at rwelog⁡(gw/rw)=gwr_w e^{\log(g_w / r_w)} = g_w, and the same for yy and hh. The center and the size fix the box. □\square

Claim 4 (sampling). Let a batch have size bb. Each RoI ii gets the largest IoU oio_i over the ground truth boxes, and the first box jij_i that reaches it. The code returns at most round⁡(b/4)\operatorname{round}(b/4) foreground entries, each (i,class of ji,ji)(i, \text{class of } j_i, j_i) with oi≥0.5o_i \ge 0.5, and background entries (i,0)(i, 0) with 0.1≤oi<0.50.1 \le o_i < 0.5, all for distinct RoIs, at most bb in total.

Proof. The loop puts each RoI in at most one of the two lists, by oio_i, with the class of jij_i for the foreground list. It then samples without replacement min⁡(∣fg∣,round⁡(b/4))\min(|\text{fg}|, \operatorname{round}(b/4)) foreground entries and at most bb minus that number of background entries. Sampling without replacement from lists of distinct RoIs gives distinct RoIs. □\square

RoIs with oi<0.1o_i < 0.1 are in neither list and are never used, which is the rule of the paper.

Claim 5 (NMS). For one class, the kept boxes have pairwise IoU at most τ\tau, and every candidate that is not kept has IoU above τ\tau with a kept box of at least the same score.

Proof. The code visits the candidates by score, best first, and keeps a box only if its IoU with every box kept so far is at most τ\tau. Any two kept boxes were compared when the later one was visited. A box that was not kept failed that test against a box kept earlier, which has a score at least as high. □\square

The detections of different classes are computed apart, so one class never removes a box of another.

Complexity

The convolutional layers run once per image and the head once per RoI; both are outside this page. RoI pooling of an RoI with at most mm cells per side into H×HH \times H bins reads at most (m+H−1)2(m + H - 1)^2 cells per channel, since next bins share at most one row or column, so it costs O(c(m+H)2)O(c (m + H)^2). The softmax and the decoding cost O(K)O(K) per RoI, and NMS costs O(KR2)O(K R^2) in the worst case. In total, O(Rc(m+H)2+KR2)O(R c (m + H)^2 + K R^2) time and O(cH2+RK)O(c H^2 + RK) extra space beyond the feature map. In the paper, with VGG16 and about 2000 proposals, detection takes about 0.3 seconds per image on a GPU, the proposals not included.

Properties

  • Shared computation. The cost of the convolutional layers does not grow with the number of proposals.
  • One-stage training. Classification and box regression are learned together, and all layers can be fine-tuned, unlike in SPPnet, which could not update the layers below its pooling.
  • No disk cache. R-CNN stored the features of every proposal for SVM training; Fast R-CNN trains from images.
  • Deterministic at test time given the proposals; not exact, since it is a learned method.
  • Still two stages. The proposals come from a separate method, and with selective search they take more time than the detector itself.

Variants and improvements

  • Single scale or image pyramid. The paper tests one scale, s=600s = 600 for the shorter side, against a pyramid of five scales; the pyramid helps only a little and costs much more time, so one scale is the default.
  • Softmax or SVMs. The paper compares the softmax of the network with SVMs trained as in R-CNN and finds that the softmax is slightly better, so the SVM stage is dropped.
  • Faster R-CNN. A region proposal network on the same feature map replaces selective search; see Faster R-CNN.
  • RoIAlign. Mask R-CNN replaces the rounding of RoI pooling with bilinear samples, which matters for masks and small objects.
  • Feature pyramids. With a feature pyramid network, each RoI is pooled from the level that matches its size.

When to use it

Use Fast R-CNN when good proposals are already at hand, for example from a different sensor, a tracker or a fixed set of regions, and a detector must classify and refine them. As a full detector it is replaced by Faster R-CNN, which needs no outside proposals. Its parts, RoI pooling and the multi-task loss, are still the head of most two-stage detectors.

Pitfalls

  • Wrong scale. RoIs are in image pixels of the scaled image; mapping them with the wrong scale, or forgetting the resize of line L1, puts every pooled grid in the wrong place.
  • Normalized targets. If training normalizes the targets, test-time decoding must undo it with the same mean and deviation.
  • Background range. RoIs with IoU below 0.1 are not used as background in the paper; using all of them gives many easy negatives.
  • Class-specific offsets. The offsets of class kk are tkt^k; decoding all classes with the offsets of the best class is a different, weaker variant.
  • Ties in max pooling. Equal values in a bin send the whole gradient to one cell; the choice must match between the forward and the backward pass.
  • Proposal time. The 0.3 seconds do not include selective search, which takes seconds per image on a CPU.

Implementations

The network is outside this page: the Python code takes the feature map and the head as inputs, and the tests build both by hand on tiny maps. The code implements RoI pooling with the rounding of the original Caffe layer and its backward pass, the softmax, the decoding with target normalization, NMS for each class, the sampling of a mini-batch of RoIs, and the multi-task loss with smooth L1. The tests check the example above, the RoI pooling check value, the backward pass against finite differences on random maps, decoding against the encoding, a small detection run, the sampling rules on random boxes, and the smooth L1 function and its gradient.

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.

fast_r_cnn.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-r-cnn/. The authors are listed in prov/CTWF7A.jsonl.
"""Fast R-CNN around a given network.

The convolutional layers and the head are not part of this file. The caller
passes the feature map of the image (a list of channels, each a list of rows)
and `head`, a function from the pooled features of one RoI to the class
logits (K + 1 numbers, class 0 is background) and the box offsets (K lists of
4 numbers). The tests build both by hand. This file has the parts that are
not learned: RoI max pooling with its backward pass, the softmax, the
class-specific decoding, NMS for each class, the sampling of RoIs for a
mini-batch, and the multi-task loss with the smooth L1 term.

Boxes are (x1, y1, x2, y2) in image pixels; `scale` maps image pixels to
feature cells (1/16 for VGG16). Standard library only.
"""

import math
from fractions import Fraction


def area(b):
    return max(0, b[2] - b[0]) * max(0, b[3] - b[1])


def iou(a, b):
    """Intersection over union; exact Fractions on integer boxes."""
    iw = min(a[2], b[2]) - max(a[0], b[0])
    ih = min(a[3], b[3]) - max(a[1], b[1])
    if iw <= 0 or ih <= 0:
        return 0
    inter = iw * ih
    union = area(a) + area(b) - inter
    if isinstance(inter, int) and isinstance(union, int):
        return Fraction(inter, union)
    return inter / union


def _round(x):
    return int(x + 0.5) if x >= 0 else -int(-x + 0.5)


def roi_pool(feat, box, scale, out_h, out_w):
    """Max pool the cells under the box into out_h x out_w bins (the Caffe rounding).
    Returns (Y, S) with S the argmax cell of each bin, or None for an empty bin (value 0)."""
    fh, fw = len(feat[0]), len(feat[0][0])
    c1, r1 = _round(box[0] * scale), _round(box[1] * scale)
    c2, r2 = _round(box[2] * scale), _round(box[3] * scale)
    h, w = max(r2 - r1 + 1, 1), max(c2 - c1 + 1, 1)
    ys, ss = [], []
    for ch in feat:
        y = [[0.0] * out_w for _ in range(out_h)]
        s = [[None] * out_w for _ in range(out_h)]
        for p in range(out_h):
            rs = min(max(r1 + p * h // out_h, 0), fh)
            re = min(max(r1 - (-(p + 1) * h // out_h), 0), fh)
            for q in range(out_w):
                cs = min(max(c1 + q * w // out_w, 0), fw)
                ce = min(max(c1 - (-(q + 1) * w // out_w), 0), fw)
                for r in range(rs, re):
                    for c in range(cs, ce):
                        if s[p][q] is None or ch[r][c] > y[p][q]:
                            y[p][q], s[p][q] = ch[r][c], (r, c)
        ys.append(y)
        ss.append(s)
    return ys, ss


def roi_pool_backward(dy, switches, fh, fw):
    """Each bin sends its gradient to its argmax cell; gradients of several bins add up."""
    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]
        out.append(g)
    return out


def softmax(z):
    m = max(z)
    e = [math.exp(v - m) for v in z]
    s = sum(e)
    return [v / s for v in e]


def decode(r, t, mean=(0.0, 0.0, 0.0, 0.0), std=(1.0, 1.0, 1.0, 1.0)):
    """Undo the target normalization, then apply the offsets to the RoI r."""
    d = [ti * si + mi for ti, si, mi in zip(t, std, mean)]
    w, h = r[2] - r[0], r[3] - r[1]
    x, y = r[0] + w / 2, r[1] + h / 2
    gx, gy, gw, gh = x + w * d[0], y + h * d[1], w * math.exp(d[2]), h * math.exp(d[3])
    return (gx - gw / 2, gy - gh / 2, gx + gw / 2, gy + gh / 2)


def encode(r, g, mean=(0.0, 0.0, 0.0, 0.0), std=(1.0, 1.0, 1.0, 1.0)):
    w, h = r[2] - r[0], r[3] - r[1]
    gw, gh = g[2] - g[0], g[3] - g[1]
    d = ((g[0] + g[2] - r[0] - r[2]) / 2 / w, (g[1] + g[3] - r[1] - r[3]) / 2 / h,
         math.log(gw / w), math.log(gh / h))
    return tuple((di - mi) / si for di, mi, si in zip(d, mean, std))


def greedy_nms(boxes, scores, thr):
    order = sorted(range(len(boxes)), key=lambda i: (-scores[i], i))
    keep = []
    for i in order:
        if all(iou(boxes[i], boxes[k]) <= thr for k in keep):
            keep.append(i)
    return keep


def detect(feat, rois, scale, head, out_h=7, out_w=7, nms_thr=0.3, score_thr=0.0,
           mean=(0.0, 0.0, 0.0, 0.0), std=(1.0, 1.0, 1.0, 1.0)):
    """Fast R-CNN test time on a given feature map. Returns {class: [(score, box, roi index)]}."""
    # feat is the output of the convolutional layers, given by the caller.
    probs, offs = [], []  # @line L1
    for r in rois:  # @line L2
        pooled, _ = roi_pool(feat, r, scale, out_h, out_w)  # @line L3
        logits, t = head(pooled)  # @line L4
        probs.append(softmax(logits))
        offs.append(t)
    out = {}
    for k in range(1, len(probs[0]) if probs else 1):  # @line L5
        cand = [i for i in range(len(rois)) if probs[i][k] > score_thr]
        boxes = [decode(rois[i], offs[i][k - 1], mean, std) for i in cand]  # @line L6
        scores = [probs[i][k] for i in cand]
        keep = greedy_nms(boxes, scores, nms_thr)  # @line L7
        out[k] = [(scores[j], boxes[j], cand[j]) for j in keep]
    return out  # @line L8


def sample_rois(rois, gts, gt_classes, batch, rng, fg_fraction=0.25, fg_thr=0.5, bg_lo=0.1,
                bg_hi=0.5):
    """Pick a mini-batch of RoIs from one image: foreground (IoU >= fg_thr with its best
    truth) up to fg_fraction of the batch, the rest background (IoU in [bg_lo, bg_hi)).
    Returns a list of (roi index, class, truth index or None)."""
    fg, bg = [], []
    for i, r in enumerate(rois):
        best, j = 0, None
        for k, g in enumerate(gts):
            o = iou(r, g)
            if o > best:
                best, j = o, k
        if best >= fg_thr:
            fg.append((i, gt_classes[j], j))
        elif bg_lo <= best < bg_hi:
            bg.append((i, 0, None))
    n_fg = min(len(fg), int(round(fg_fraction * batch)))
    fg = rng.sample(fg, n_fg)
    bg = rng.sample(bg, min(len(bg), batch - n_fg))
    return fg + bg


def smooth_l1(x):
    a = abs(x)
    return 0.5 * x * x if a < 1 else a - 0.5


def smooth_l1_grad(x):
    return x if abs(x) < 1 else (1.0 if x > 0 else -1.0)


def multitask_loss(p, u, t_u, v, lam=1.0):
    """L = -log p_u + lam [u >= 1] sum_i smooth_L1(t_u[i] - v[i]) for one RoI."""
    loss = -math.log(p[u])
    if u >= 1:
        loss += lam * sum(smooth_l1(a - b) for a, b in zip(t_u, v))
    return loss
test_fast_r_cnn.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-r-cnn/. The authors are listed in prov/CTWF7A.jsonl.

import math
import random
from fractions import Fraction

from fast_r_cnn import (
    decode,
    detect,
    encode,
    iou,
    multitask_loss,
    roi_pool,
    roi_pool_backward,
    sample_rois,
    smooth_l1,
    smooth_l1_grad,
    softmax,
)


def test_page_example_loss():
    truth = [(0, 0, 10, 10)]
    rois = [(0, 0, 10, 8), (0, 0, 10, 6), (6, 0, 16, 10), (9, 0, 19, 10), (30, 30, 40, 40)]
    assert [iou(r, truth[0]) for r in rois] == [Fraction(4, 5), Fraction(3, 5), Fraction(1, 4),
                                               Fraction(1, 19), 0]
    # A batch of 4 takes one of the two foreground RoIs (25 percent) and the one background RoI.
    for seed in range(5):
        picked = sorted(sample_rois(rois, truth, [1], 4, random.Random(seed)), key=lambda x: x[0])
        assert picked in ([(0, 1, 0), (2, 0, None)], [(1, 1, 0), (2, 0, None)])
    picked = sample_rois(rois, truth, [1], 8, random.Random(0))
    assert sorted(picked, key=lambda x: x[0]) == [(0, 1, 0), (1, 1, 0), (2, 0, None)]
    loss = multitask_loss([0.2, 0.8], 1, (0.5, -2.0, 0.0, 0.1), (0.0, 0.0, 0.0, 0.0))
    assert abs(loss - (-math.log(0.8) + 0.125 + 1.5 + 0.0 + 0.005)) < 1e-12
    assert abs(multitask_loss([0.7, 0.3], 0, (9.0, 9.0, 9.0, 9.0), (0, 0, 0, 0)) + math.log(0.7)) < 1e-12


def test_roi_pool_check_value():
    feat = [[[(3 * r + 5 * c) % 11 for c in range(8)] for r in range(6)]]
    y, s = roi_pool(feat, (5, 3, 26, 17), 0.25, 2, 2)
    assert y == [[[10, 9], [10, 10]]]
    for (p, q) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
        r, c = s[0][p][q]
        assert feat[0][r][c] == y[0][p][q]


def test_roi_pool_backward_is_the_gradient():
    rng = random.Random(1)
    fh, fw = 9, 11
    for _ in range(10):
        feat = [[[rng.random() for _ in range(fw)] for _ in range(fh)] for _ in range(2)]
        x1, y1 = rng.randint(0, 20), rng.randint(0, 16)
        box = (x1, y1, x1 + rng.randint(4, 24), y1 + rng.randint(4, 20))
        wts = [[[rng.uniform(-1, 1) for _ in range(3)] for _ in range(2)] for _ in range(2)]

        def f(m):
            y, _ = roi_pool(m, box, 0.5, 2, 3)
            return sum(wts[k][p][q] * y[k][p][q] for k in range(2) for p in range(2) for q in range(3))

        _, s = roi_pool(feat, box, 0.5, 2, 3)
        g = roi_pool_backward(wts, s, fh, fw)
        eps = 1e-7
        for k in range(2):
            for r in range(fh):
                for c in range(fw):
                    old = feat[k][r][c]
                    feat[k][r][c] = old + eps
                    up = f(feat)
                    feat[k][r][c] = old - eps
                    dn = f(feat)
                    feat[k][r][c] = old
                    assert abs((up - dn) / (2 * eps) - g[k][r][c]) < 1e-6


def test_decode_inverts_encode_with_normalization():
    rng = random.Random(2)
    mean, std = (0.01, -0.02, 0.05, 0.0), (0.1, 0.1, 0.2, 0.2)
    for _ in range(100):
        r = (rng.uniform(0, 40), rng.uniform(0, 40))
        r = r + (r[0] + rng.uniform(2, 30), r[1] + rng.uniform(2, 30))
        g = (rng.uniform(0, 40), rng.uniform(0, 40))
        g = g + (g[0] + rng.uniform(2, 30), g[1] + rng.uniform(2, 30))
        assert all(abs(a - b) < 1e-9 for a, b in zip(decode(r, encode(r, g, mean, std), mean, std), g))


def test_detect_on_a_hand_built_head():
    # One channel, 8 x 8 cells, scale 1/4: a bright 3 x 3 patch of cells at rows 2..4, columns 2..4.
    feat = [[[1.0 if 2 <= r <= 4 and 2 <= c <= 4 else 0.0 for c in range(8)] for r in range(8)]]

    def head(pooled):
        vals = [v for row in pooled[0] for v in row]
        m = sum(vals) / len(vals)
        # Class 1 likes a fully bright RoI; class 2 likes a dark one. No box offsets.
        return [0.0, 6 * m - 3, 3 - 6 * m], [(0.0, 0.0, 0.0, 0.0), (0.0, 0.0, 0.0, 0.0)]

    rois = [(8, 8, 20, 20), (8, 8, 24, 20), (24, 0, 32, 8), (24, 24, 32, 32), (4, 8, 20, 20)]
    out = detect(feat, rois, 0.25, head, out_h=2, out_w=2, nms_thr=0.3, score_thr=0.5)
    # RoIs 1 and 4 score as high as RoI 0 but overlap it by IoU 3/4, so NMS removes them.
    assert [i for _, _, i in out[1]] == [0]
    assert [i for _, _, i in out[2]] == [2, 3]
    probs = softmax([0.0, 3.0, -3.0])
    assert abs(out[1][0][0] - probs[1]) < 1e-12 and out[1][0][1] == (8.0, 8.0, 20.0, 20.0)


def test_sampling_rules():
    rng = random.Random(3)

    def rbox():
        x, y = rng.randint(0, 40), rng.randint(0, 40)
        return (x, y, x + rng.randint(2, 20), y + rng.randint(2, 20))

    for _ in range(40):
        gts = [rbox() for _ in range(rng.randint(1, 3))]
        cls = [rng.randint(1, 3) for _ in gts]
        rois = [rbox() for _ in range(40)] + [(g[0] + 1, g[1], g[2] + 1, g[3]) for g in gts]
        batch = 16
        picked = sample_rois(rois, gts, cls, batch, rng)
        assert len(picked) <= batch and len({i for i, _, _ in picked}) == len(picked)
        n_fg = sum(1 for _, c, _ in picked if c > 0)
        assert n_fg <= 4
        for i, c, j in picked:
            best = max(iou(rois[i], g) for g in gts)
            if c > 0:
                assert best >= Fraction(1, 2) and iou(rois[i], gts[j]) == best and cls[j] == c
            else:
                assert Fraction(1, 10) <= best < Fraction(1, 2)


def test_smooth_l1():
    assert smooth_l1(0.5) == 0.125 and smooth_l1(-2.0) == 1.5 and smooth_l1(1.0) == 0.5
    for x in [-3.0, -1.0, -0.4, 0.0, 0.3, 0.999, 2.5]:
        assert abs(smooth_l1_grad(x)) <= 1
        eps = 1e-6
        if abs(abs(x) - 1) > 1e-3:
            assert abs((smooth_l1(x + eps) - smooth_l1(x - eps)) / (2 * eps) - smooth_l1_grad(x)) < 1e-6
    # The loss is continuous at |x| = 1.
    assert abs(smooth_l1(1 - 1e-12) - smooth_l1(1 + 1e-12)) < 1e-9

History

R-CNN (2014) was accurate but slow, since it ran the network once per proposal. He, Zhang, Ren and Sun's SPPnet (2014) shared the convolutional layers and pooled each proposal with a spatial pyramid, but kept the multi-stage training of R-CNN and could not fine-tune the layers below the pooling. Girshick's Fast R-CNN, on arXiv in April 2015 and at ICCV 2015, used a single-level pyramid, the RoI pooling layer, trained everything in one network with a multi-task loss, and reached 66.9 percent mAP on VOC 2007. It was released with open Caffe code, and later in 2015 Ren, He, Girshick and Sun added the region proposal network to make Faster R-CNN.

References

  1. Ross Girshick, Fast R-CNN, ICCV 2015, 1440-1448, Section 2.1, The RoI pooling layer (H = W = 7 for VGG16); Section 2.3, Fine-tuning for detection (multi-task loss with smooth L1 and lambda = 1, mini-batches of N = 2 images and R = 128 RoIs, 25 percent foreground at IoU 0.5 or more, background in [0.1, 0.5), back-propagation through RoI pooling); Section 2.4, Scale invariance (s = 600); Section 3, Fast R-CNN detection and Section 3.1, Truncated SVD; Section 4, Main results
  2. Ross Girshick, Fast R-CNN, arXiv 1504.08083, the same sections; the abstract gives 9 times faster training and 213 times faster testing than R-CNN with VGG16
  3. Ross Girshick, Jeff Donahue, Trevor Darrell and Jitendra Malik, Rich feature hierarchies for accurate object detection and semantic segmentation, CVPR 2014, 580-587, Section 2, the R-CNN pipeline that Fast R-CNN replaces
  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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example