Algorithm Search⌘K

Algorithmresearch

DETR

Also called detection transformer.

Predict a fixed set of boxes with a transformer and train by a Hungarian matching of predictions to objects, with no anchors and no non-maximum suppression.

Time
O(N C + N M^2) worst
Space
O(N M) extra
Where
C = the number of classes; M = the number of ground truth objects; N = the number of queries
Properties
deterministicnot exactofflineiterative
Origin
Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko, 2020

DETR, the detection transformer, treats object detection as the prediction of a set. A convolutional backbone computes a feature map, and a transformer encoder mixes the features of all positions. A transformer decoder then turns a fixed number NN of learned queries, 100 in the paper, into NN outputs. Each output is a class distribution over the CC classes and an extra "no object" class ∅\varnothing, plus one box. In training, the MM true objects are matched one to one to MM of the NN outputs by the Hungarian algorithm. The match is chosen to minimize a cost of class probability and box error. Every matched output learns its object, and every other output learns ∅\varnothing. Because the loss punishes two outputs for one object, the network learns not to make duplicates. So DETR has no anchors, no hand-made assignment rule, and no non-maximum suppression. With a ResNet-50 it reached 42.0 AP on COCO, close to a tuned Faster R-CNN. It was better on large objects and worse on small ones.

In plain words

DETR asks the network for a fixed list of 100 guesses. Each guess is a box and a class, or "nothing here". In training, the true objects are paired with the guesses in the cheapest way, one guess per object. The cost of a pair is low when the guess names the right class and its box is close. The paired guesses learn their objects, and all other guesses learn to say "nothing". Since only one guess can be paired with an object, a second guess on the same object is pushed to say "nothing". So the network learns to give each object once, and no step to remove near copies is needed. At test time, the guesses that name a class with enough confidence are the output.

The problem

The input is an image and a trained network that gives NN outputs (p^i,b^i)(\hat p_i, \hat b_i). Here p^i\hat p_i is a distribution over C+1C + 1 classes, and b^i=(cx,cy,w,h)\hat b_i = (c_x, c_y, w, h) is a box relative to the image size. In training, the ground truth is a set of M≤NM \le N objects (cj,bj)(c_j, b_j). The non-learned core is the set loss: find the one-to-one matching σ^\hat\sigma of the objects to the outputs of least total cost, then compute the loss under that matching. At test time the output is the set of non-∅\varnothing predictions above a threshold, judged by detection mean average precision. The network is outside the page.

The algorithm

  1. DETR-SET-LOSS(I, network, (c_j, b_j) for j = 1, ..., M)
  2. 1(p̂_i, b̂_i) for i = 1, ..., N ← network(I) ▷ outside
  3. 2cost[j][i] ← -p̂_i(c_j) + λ_L1 ‖b_j - b̂_i‖_1 + λ_iou (1 - GIoU(b_j, b̂_i)) for all j, i
  4. 3σ̂ ← the one-to-one map of the M truths to the N queries of least total cost ▷ Hungarian algorithm
  5. 4target_i ← c_j if σ̂(j) = i, else ∅
  6. 5L_cls ← the weighted mean of -log p̂_i(target_i), with weight 0.1 for ∅ and 1 otherwise
  7. 6L_box ← (1/M) Σ_j [λ_L1 ‖b_j - b̂_σ̂(j)‖_1 + λ_iou (1 - GIoU(b_j, b̂_σ̂(j)))]
  8. 7return L_cls + L_box

Matching cost. The paper uses λL1=5\lambda_{L1} = 5 and λiou=2\lambda_{iou} = 2. The class part of the cost is the probability −p^i(cj)-\hat p_i(c_j), not its log. The paper reports that this keeps the class and box parts on the same scale and works better. The generalized IoU of two boxes AA and BB, with HH the smallest box that holds both, is

GIoU(A,B)=IoU(A,B)−∣H∣−∣A∪B∣∣H∣∈(−1,1].\text{GIoU}(A, B) = \text{IoU}(A, B) - \frac{|H| - |A \cup B|}{|H|} \in (-1, 1].

Unlike the IoU, it still falls as two boxes that do not overlap move apart. The L1 term alone would weight large boxes more than small ones, and the GIoU term does not depend on scale.

Hungarian loss. The class term of the outputs matched to ∅\varnothing is down-weighted by a factor of 10, since most of the NN outputs are ∅\varnothing. The code takes the weighted mean over the queries and divides the box term by MM. The paper adds the same loss after each decoder layer, as auxiliary losses, with a matching for each layer.

Test time. For each query, take the most likely class other than ∅\varnothing and its probability. The output is the queries whose probability is above a threshold. There is no NMS. The paper reports that NMS helps the outputs of the first decoder layer, and that the gain goes away as the layers get deeper.

Example

Take two classes, cat (0) and dog (1), so each p^i\hat p_i is (cat, dog, ∅\varnothing). The truths are a cat at T1=(0.25,0.5,0.2,0.2)T_1 = (0.25, 0.5, 0.2, 0.2) and a dog at T2=(0.75,0.5,0.2,0.2)T_2 = (0.75, 0.5, 0.2, 0.2). There are three queries:

query p^i\hat p_i b^i\hat b_i
1 0.5, 0.1, 0.4 T1T_1
2 0.2, 0.3, 0.5 T2T_2
3 0.7, 0.1, 0.2 (0.3, 0.5, 0.2, 0.2)
  1. Query 3 is T1T_1 moved by 0.05. Its IoU with T1T_1 is 0.03/0.05=0.60.03/0.05 = 0.6, and the enclosing box is the union, so its GIoU is also 0.6. Its cost for the cat is −0.7+5⋅0.05+2⋅0.4=0.35-0.7 + 5 \cdot 0.05 + 2 \cdot 0.4 = 0.35.
  2. Query 1 has cost −0.5-0.5 for the cat, and query 2 has cost −0.3-0.3 for the dog, since their boxes are exact. The pairs across the image have costs above 4.9, because T1T_1 and T2T_2 are 0.5 apart with GIoU −3/7-3/7.
  3. The best matching is cat to query 1 and dog to query 2, with total −0.8-0.8. Matching the cat to query 3, the most confident cat, would cost 0.35−0.3=0.050.35 - 0.3 = 0.05.
  4. So query 3 gets the target ∅\varnothing, though it is the strongest cat guess. This is how the loss removes duplicates. The box loss is 0, and
L=−ln⁡0.5−ln⁡0.3−0.1ln⁡0.21+1+0.1≈0.980.L = \frac{-\ln 0.5 - \ln 0.3 - 0.1 \ln 0.2}{1 + 1 + 0.1} \approx 0.980.

At test time with a threshold of 0.45, these outputs give a cat from query 3 (0.7) and a cat from query 1 (0.5): two boxes for one object, which training on this loss pushes apart.

Correctness

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

  1. Matching. The Hungarian algorithm of the code returns a one-to-one map of the truths to the queries of least total cost. The tests compare it with all maps on small inputs.
  2. Order does not matter. When the matching of least cost is unique, the loss does not change when the queries or the truths are listed in another order. So the network is not tied to an order of the objects.
  3. GIoU. It lies in (−1,1](-1, 1], equals 1 only for equal boxes, and is symmetric.
  4. Duplicates cost. Each truth is matched to exactly one query. If several queries give copies of one object, all but one get the target ∅\varnothing, unless they are matched to other truths.
Proof: The Hungarian algorithm of the code finds a one-to-one matching of least cost, the set loss does not depend on the order of queries or truths when that matching is unique, and the generalized IoU lies in (-1, 1]full

The backbone and the transformer 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. The cost matrix cc has a row for each of the MM truths and a column for each of the N≥MN \ge M queries.

Claim 1 (optimal matching). The function hungarian returns a map σ\sigma of the rows to distinct columns that minimizes ∑jcjσ(j)\sum_j c_{j\sigma(j)} over all such maps.

Proof. The code keeps a potential uju_j for each row and viv_i for each column, and a partial matching pp from columns to rows. Call cˉji=cji−uj−vi\bar c_{ji} = c_{ji} - u_j - v_i the reduced cost. The rows are added one at a time. We show three invariants at the end of each phase, for the rows added so far:

  • (a) cˉji≥0\bar c_{ji} \ge 0 for every added row jj and every column ii;
  • (b) cˉji=0\bar c_{ji} = 0 when row jj is matched to column ii;
  • (c) vi≤0v_i \le 0 for every column, and vi=0v_i = 0 for every column that is not matched.

In the phase of row rr, the code keeps a set of used columns, starting with a dummy column 0 matched to rr. The used rows are the rows matched to used columns. For each unused column ii, the value minvi\mathit{minv}_i is the least reduced cost from a used row to ii, and wayi\mathit{way}_i is the used column whose row gives it. Each round takes δ=min⁡iminvi\delta = \min_i \mathit{minv}_i over the unused columns, adds δ\delta to uu of the used rows and subtracts it from vv of the used real columns, and makes the column i∗i^* of least minv\mathit{minv} used.

In the first round, the only used row is rr and the only used column is the dummy. So the update changes only uru_r, to the least reduced cost in row rr. After it, every reduced cost of row rr is non-negative, and those of the other rows are unchanged. In later rounds every used row is an added row or rr, so all their reduced costs are non-negative, and δ≥0\delta \ge 0. The update does not change cˉ\bar c between a used row and a used column. It lowers cˉ\bar c by δ\delta between a used row and an unused column, which stays non-negative by the choice of δ\delta. It raises cˉ\bar c by δ\delta between an unused row and a used column. So (a) holds through the phase, also for row rr. Every matched pair has both ends used or both unused, so (b) is kept. vv only falls, and only for used columns. A used real column is matched, or it is the last column of the phase, which the augmentation matches. So (c) is kept.

The round makes cˉ\bar c zero on the edge from the row of wayi∗\mathit{way}_{i^*} to i∗i^*. Both ends are used from then on, so the edge stays at zero. If i∗i^* is matched, its row becomes used and the rounds go on. If i∗i^* is free, the phase ends: the code walks back along way\mathit{way} and moves each column on the path to the row of the column before it. Every new matched edge is one of these zero edges, which keeps (b). The old matched edges off the path are not changed, and each row on the path changes its column. So after the phase, rr and all earlier rows are matched to distinct columns. A free column always exists, since fewer than M≤NM \le N rows are matched during the phase. Each round uses one more column, so a phase has at most NN rounds.

At the end every row is matched. By (b), the cost of σ\sigma is ∑juj+∑i matchedvi\sum_j u_j + \sum_{i \text{ matched}} v_i, which by (c) is ∑juj+∑ivi\sum_j u_j + \sum_i v_i. For any other map τ\tau of the rows to distinct columns, (a) gives ∑jcjτ(j)≥∑juj+∑jvτ(j)≥∑juj+∑ivi\sum_j c_{j\tau(j)} \ge \sum_j u_j + \sum_j v_{\tau(j)} \ge \sum_j u_j + \sum_i v_i, where the last step uses vi≤0v_i \le 0 for the columns that τ\tau leaves out. So no map costs less than σ\sigma. □\square

The tests compare the cost of the result with the least cost over all one-to-one maps, on random matrices of up to 5×65 \times 6, half of them with integer costs and many ties.

Claim 2 (order). Let the matching of least cost be unique. If the queries or the truths are listed in another order, the set loss does not change.

Proof. A reordering of the queries permutes the columns of the cost matrix, and a reordering of the truths permutes its rows, with the same entries. One-to-one maps of the two matrices correspond, with the same costs, so the unique optimal maps correspond. Under that map, each query has the same target as before, and the loss is a sum over the queries of a term that depends only on the output of the query and its target. The weights and the box sum over the matched pairs are also the same. So the loss is the same. □\square

If two matchings tie for the least cost, they can give different losses, since the loss uses −log⁡p^-\log \hat p and the cost uses −p^-\hat p. Ties then decide which one the solver returns. For outputs with random real values, ties have probability zero, as in the test.

Claim 3 (generalized IoU). For boxes AA and BB of positive area, GIoU(A,B)∈(−1,1]\text{GIoU}(A, B) \in (-1, 1]. It is symmetric, and it equals 1 if and only if A=BA = B.

Proof. Let U=∣A∪B∣>0U = |A \cup B| > 0 and let HH be the area of the smallest box that holds both, so H≥UH \ge U. Then GIoU=IoU−(H−U)/H\text{GIoU} = \text{IoU} - (H - U)/H, with 0≤IoU≤10 \le \text{IoU} \le 1 and 0≤(H−U)/H<10 \le (H - U)/H < 1. So −1<GIoU≤1-1 < \text{GIoU} \le 1. Both parts are symmetric in AA and BB. GIoU=1\text{GIoU} = 1 needs IoU=1\text{IoU} = 1, so ∣A∩B∣=∣A∪B∣|A \cap B| = |A \cup B| and A=BA = B. Conversely A=BA = B gives IoU=1\text{IoU} = 1 and H=UH = U. □\square

Claim 4 (loss). The code returns ∑iwi(−log⁡p^i(ti))∑iwi+1max⁡(1,M)∑jLbox(b^σ(j),bj)\frac{\sum_i w_i(-\log \hat p_i(t_i))}{\sum_i w_i} + \frac{1}{\max(1, M)}\sum_j L_{box}(\hat b_{\sigma(j)}, b_j). Here tit_i is the class of the truth matched to query ii, or ∅\varnothing, and wiw_i is 0.1 for ∅\varnothing and 1 otherwise. Each truth gives exactly one query its class, and every other query has the target ∅\varnothing. With no truths, the loss is the mean of −log⁡p^i(∅)-\log \hat p_i(\varnothing).

Proof. Lines L4 to L7 of the code compute exactly these sums from the map of Claim 1, which is one to one. With M=0M = 0, every target is ∅\varnothing, all weights are 0.1 and cancel in the mean, and the box sum is empty. □\square

Complexity

The network is outside. The cost matrix has MNMN entries and costs O(MN)O(MN) to fill, after O(NC)O(NC) to read the outputs. The Hungarian algorithm with potentials assigns the MM rows one at a time. Each row takes at most O(M)O(M) rounds of O(N)O(N) work, so the total is O(M2N)O(M^2 N). The loss is O(N+M)O(N + M) after that. The test-time output costs O(NC)O(NC) and a sort. The extra space is O(NM)O(NM) for the matrix. The transformer encoder over HWHW feature positions costs O((HW)2)O((HW)^2) per layer, which limits the feature resolution and is one reason why small objects are harder.

Properties

  • End to end. One loss from the image to the set of boxes, with no anchors, no assignment by IoU thresholds and no NMS.
  • Set loss. The loss does not depend on the order of the queries or the objects.
  • Global reasoning. The decoder attends to all queries and all positions, so the outputs can take each other into account.
  • Slow training. The paper trains for hundreds of epochs, far more than Faster R-CNN needs, and the matching can change from step to step early in training.
  • Weaker on small objects. The feature map has stride 32 in the base model, and there is no feature pyramid.
  • Deterministic at test time; not exact, since it is a learned method.

Variants and improvements

  • Deformable DETR. Attention to a few sampled points on several feature levels, in the spirit of the feature pyramid network. This gives faster training and better results on small objects.
  • Conditional, DAB, DN and DINO DETR. Queries tied to anchor points or boxes, and denoising training with noisy truth boxes. They make the matching more stable and shorten training.
  • Panoptic DETR. A mask head on the decoder outputs gives panoptic segmentation with the same matching, extended to stuff classes.
  • Set prediction elsewhere. The same Hungarian loss trains keypoint, tracking and segmentation models. One-to-one assignment has also been added to convolutional detectors to drop NMS.

When to use it

Use DETR or one of its descendants when an end-to-end detector without NMS and anchors is wanted, when objects overlap heavily so that NMS hurts, or when detection is one part of a larger set prediction. Use a detector with a feature pyramid when training time is short or small objects dominate. For a fast detector on a small device, a one-stage convolutional detector is still the usual choice.

Pitfalls

  • Log-probabilities in the matching. The paper uses probabilities in the cost and log-probabilities in the loss. Using the log in the cost changes its scale against the box terms.
  • Box format. The L1 term is on (cx,cy,w,h)(c_x, c_y, w, h) relative to the image, and the GIoU needs corners. Mixing the formats or pixels gives wrong costs.
  • Degenerate boxes. GIoU divides by the enclosing area. Boxes of zero width early in training need a guard.
  • The no-object weight. Most of the NN targets are ∅\varnothing. The paper down-weights them by 10 for this class imbalance, much as two-stage detectors sample their negatives.
  • NN too small. If an image has more objects than queries, the matching cannot cover them. NN must be well above the usual number of objects.
  • Matching on a greedy basis. Matching each truth to its best query in turn is not optimal and can give a query to the wrong object, as in the example. Use an exact assignment solver.

Implementations

The network is outside this page. The Python code takes the class probabilities and boxes of the NN queries as inputs, and the tests build them by hand or with a fixed seed. The code implements the generalized IoU, the matching cost, the Hungarian algorithm with potentials for a rectangular cost matrix, the set loss of lines L1 to L7, and the test-time output without NMS. The tests check GIoU values and bounds, the Hungarian algorithm against all one-to-one maps on random matrices with ties, the example above, the loss with no truths, the invariance of the loss under reordering of the queries and the truths, and that the output keeps duplicates.

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.

detr.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/detr/. The authors are listed in prov/WE3F6C.jsonl.
"""DETR around given network outputs.

The backbone and the transformer are not part of this file. The caller passes
the N query outputs: for each query a list of C + 1 class probabilities, with
the no-object class last, and a box (cx, cy, w, h) relative to the image. The
tests build them by hand or with a fixed seed. This file has the parts that are
not learned: the generalized IoU, the matching cost, the Hungarian algorithm
for the optimal one-to-one matching of truths to queries, the set loss, and
the test-time output without non-maximum suppression.

Standard library only.
"""

import math

L1_WEIGHT = 5.0
GIOU_WEIGHT = 2.0
NO_OBJECT_WEIGHT = 0.1


def to_corners(b):
    return (b[0] - b[2] / 2, b[1] - b[3] / 2, b[0] + b[2] / 2, b[1] + b[3] / 2)


def giou(a, b):
    """Generalized IoU of two corner boxes of positive area: IoU - |C \\ (A u B)| / |C|,
    where C is the smallest box that holds both."""
    iw = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
    ih = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
    inter = iw * ih
    union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    hull = (max(a[2], b[2]) - min(a[0], b[0])) * (max(a[3], b[3]) - min(a[1], b[1]))
    return inter / union - (hull - union) / hull


def box_loss(b, t):
    """lambda_L1 ||b - t||_1 + lambda_iou (1 - GIoU(b, t)) for boxes (cx, cy, w, h)."""
    l1 = sum(abs(x - y) for x, y in zip(b, t))
    return L1_WEIGHT * l1 + GIOU_WEIGHT * (1 - giou(to_corners(b), to_corners(t)))


def match_cost(probs, box, cls, tbox):
    """The matching cost of the paper: -p(class of the truth) + L_box."""
    return -probs[cls] + box_loss(box, tbox)


def hungarian(cost):
    """Minimum-cost assignment of the n rows to distinct columns of an n x m matrix,
    n <= m, by the Hungarian algorithm with potentials in O(n^2 m) time.
    Returns col[r], the column of row r."""
    n = len(cost)
    if n == 0:
        return []
    m = len(cost[0])
    assert n <= m
    inf = float("inf")
    u, v = [0.0] * (n + 1), [0.0] * (m + 1)
    p, way = [0] * (m + 1), [0] * (m + 1)
    for i in range(1, n + 1):
        p[0], j0 = i, 0
        minv, used = [inf] * (m + 1), [False] * (m + 1)
        while True:
            used[j0] = True
            i0, delta, j1 = p[j0], inf, 0
            for j in range(1, m + 1):
                if not used[j]:
                    cur = cost[i0 - 1][j - 1] - u[i0] - v[j]
                    if cur < minv[j]:
                        minv[j], way[j] = cur, j0
                    if minv[j] < delta:
                        delta, j1 = minv[j], j
            for j in range(m + 1):
                if used[j]:
                    u[p[j]] += delta
                    v[j] -= delta
                else:
                    minv[j] -= delta
            j0 = j1
            if p[j0] == 0:
                break
        while j0:
            j1 = way[j0]
            p[j0] = p[j1]
            j0 = j1
    col = [-1] * n
    for j in range(1, m + 1):
        if p[j]:
            col[p[j] - 1] = j - 1
    return col


def set_loss(probs, boxes, gt_classes, gt_boxes):
    """The DETR set loss on given outputs. Returns (loss, sigma), where sigma[j]
    is the query matched to truth j.

    The class term is the weighted mean of -log p_i(target_i), with weight 0.1
    for the no-object target; the box term is summed over the matched pairs and
    divided by the number of truths."""
    # probs and boxes are the outputs of the network for the N queries.
    n, no_obj = len(probs), len(probs[0]) - 1  # @line L1
    cost = [[match_cost(probs[i], boxes[i], c, t) for i in range(n)]
            for c, t in zip(gt_classes, gt_boxes)]  # @line L2
    sigma = hungarian(cost)  # @line L3
    target = [no_obj] * n
    for j, i in enumerate(sigma):
        target[i] = gt_classes[j]  # @line L4
    w = [NO_OBJECT_WEIGHT if target[i] == no_obj else 1.0 for i in range(n)]
    cls = sum(-w[i] * math.log(probs[i][target[i]]) for i in range(n)) / sum(w)  # @line L5
    box = sum(box_loss(boxes[i], gt_boxes[j]) for j, i in enumerate(sigma))
    box /= max(1, len(gt_boxes))  # @line L6
    return cls + box, sigma  # @line L7


def detect(probs, boxes, score_thr=0.7):
    """Test-time output: for each query, its best class other than no-object and
    the probability of it; queries above the threshold are returned as
    (score, class, corner box), best first. There is no NMS."""
    out = []
    for p, b in zip(probs, boxes):
        c = max(range(len(p) - 1), key=lambda k: (p[k], -k))
        if p[c] > score_thr:
            out.append((p[c], c, to_corners(b)))
    out.sort(key=lambda d: (-d[0], d[1]))
    return out
test_detr.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/detr/. The authors are listed in prov/WE3F6C.jsonl.

import itertools
import math
import random

from detr import detect, giou, hungarian, match_cost, set_loss, to_corners

T1, T2 = (0.25, 0.5, 0.2, 0.2), (0.75, 0.5, 0.2, 0.2)
PAGE_PROBS = [[0.5, 0.1, 0.4], [0.2, 0.3, 0.5], [0.7, 0.1, 0.2]]
PAGE_BOXES = [T1, T2, (0.3, 0.5, 0.2, 0.2)]


def brute_force(cost):
    n, m = len(cost), len(cost[0])
    return min(sum(cost[r][c] for r, c in enumerate(cols)) for cols in itertools.permutations(range(m), n))


def test_giou_values():
    a = to_corners(T1)
    assert abs(giou(a, a) - 1) < 1e-12
    assert abs(giou(a, to_corners(T2)) - (-3 / 7)) < 1e-12
    assert abs(giou(a, to_corners(PAGE_BOXES[2])) - 0.6) < 1e-12
    rng = random.Random(10)
    for _ in range(200):
        x, y = rng.random(), rng.random()
        p = (x, y, x + rng.uniform(0.01, 1), y + rng.uniform(0.01, 1))
        x, y = rng.random(), rng.random()
        q = (x, y, x + rng.uniform(0.01, 1), y + rng.uniform(0.01, 1))
        g = giou(p, q)
        assert -1 < g <= 1 and abs(g - giou(q, p)) < 1e-12


def test_hungarian_matches_brute_force():
    rng = random.Random(11)
    for _ in range(300):
        n = rng.randint(1, 5)
        m = rng.randint(n, 6)
        if rng.random() < 0.5:
            cost = [[rng.randint(-3, 3) for _ in range(m)] for _ in range(n)]
        else:
            cost = [[rng.uniform(-2, 5) for _ in range(m)] for _ in range(n)]
        col = hungarian(cost)
        assert len(set(col)) == n and all(0 <= c < m for c in col)
        assert abs(sum(cost[r][c] for r, c in enumerate(col)) - brute_force(cost)) < 1e-9
    assert hungarian([]) == []


def test_page_example():
    costs = [[match_cost(PAGE_PROBS[i], PAGE_BOXES[i], c, t) for i in range(3)]
             for c, t in [(0, T1), (1, T2)]]
    assert abs(costs[0][0] + 0.5) < 1e-12 and abs(costs[1][1] + 0.3) < 1e-12
    assert abs(costs[0][2] - 0.35) < 1e-12
    loss, sigma = set_loss(PAGE_PROBS, PAGE_BOXES, [0, 1], [T1, T2])
    assert sigma == [0, 1]
    want = (-math.log(0.5) - math.log(0.3) - 0.1 * math.log(0.2)) / 2.1
    assert abs(loss - want) < 1e-12
    # Matching by class probability alone would give the first truth to query 2.
    assert max(range(3), key=lambda i: PAGE_PROBS[i][0]) == 2


def test_no_truths():
    loss, sigma = set_loss(PAGE_PROBS, PAGE_BOXES, [], [])
    assert sigma == []
    assert abs(loss - (-(math.log(0.4) + math.log(0.5) + math.log(0.2)) / 3)) < 1e-12


def test_loss_ignores_the_order_of_queries():
    rng = random.Random(12)
    for _ in range(30):
        n, c, m = 6, 3, rng.randint(1, 4)
        probs = []
        for _ in range(n):
            z = [rng.random() + 0.01 for _ in range(c + 1)]
            probs.append([v / sum(z) for v in z])
        boxes = [(rng.uniform(0.2, 0.8), rng.uniform(0.2, 0.8), rng.uniform(0.05, 0.4), rng.uniform(0.05, 0.4))
                 for _ in range(n)]
        gts = [(rng.uniform(0.2, 0.8), rng.uniform(0.2, 0.8), rng.uniform(0.05, 0.4), rng.uniform(0.05, 0.4))
               for _ in range(m)]
        labels = [rng.randrange(c) for _ in range(m)]
        loss, sigma = set_loss(probs, boxes, labels, gts)
        assert len(set(sigma)) == m
        perm = list(range(n))
        rng.shuffle(perm)
        loss2, _ = set_loss([probs[i] for i in perm], [boxes[i] for i in perm], labels, gts)
        assert abs(loss - loss2) < 1e-9
        order = list(range(m))
        rng.shuffle(order)
        loss3, _ = set_loss(probs, boxes, [labels[j] for j in order], [gts[j] for j in order])
        assert abs(loss - loss3) < 1e-9


def test_detect_has_no_nms():
    out = detect(PAGE_PROBS, PAGE_BOXES, score_thr=0.45)
    assert [(s, c) for s, c, _ in out] == [(0.7, 0), (0.5, 0)]
    assert detect(PAGE_PROBS, PAGE_BOXES) == []

History

Earlier detectors turned set prediction into many separate problems: score each anchor or proposal, label it by an IoU rule, and remove duplicates by NMS. Set losses with a bipartite matching had been used before, for example by Stewart, Andriluka and Ng for people in crowds (2016), with recurrent networks. Carion, Massa, Synnaeve, Usunier, Kirillov and Zagoruyko put DETR on arXiv in May 2020 and presented it at ECCV 2020. They joined the matching loss with a transformer encoder and decoder and reached the accuracy of Faster R-CNN on COCO. Its slow training and weak small-object results led to Deformable DETR and a long line of descendants, such as DINO, which are among the strongest detectors on COCO.

References

  1. Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov and Sergey Zagoruyko, End-to-end object detection with transformers, ECCV 2020, LNCS 12346, 213-229, Section 3.1, Object detection set prediction loss (the matching cost -p(c) + L_box with probabilities rather than log-probabilities, the Hungarian loss, the no-object term down-weighted by a factor 10, the box loss lambda_iou L_iou + lambda_L1 L1 with the generalized IoU); Section 3.2, DETR architecture (N object queries, auxiliary decoding losses); Section 4, Experiments (lambda_L1 = 5, lambda_iou = 2, N = 100; Table 1: AP 42.0 for DETR and 43.5 for DETR-R101 on COCO)
  2. Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov and Sergey Zagoruyko, End-to-end object detection with transformers, arXiv 2005.12872, the same sections
  3. Harold W. Kuhn, The Hungarian method for the assignment problem, Naval Research Logistics Quarterly 2(1-2), 1955, 83-97, the assignment algorithm that computes the matching
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.3, Object detection

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