Search

Search papers and lessons

End-to-End Object Detection with Transformers

Nicolas Carion, Francisco Massa, Gabriel Synnaeve et al. · 2020

DETR detects objects by predicting the whole set of boxes in one pass, matching predictions to ground truth one-to-one, and removes the hand-designed anchors and non-maximum suppression of older detectors.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Architectures
  • Neural network basics
  • Linear algebra
  • Probability
  • ReadReady to readNot yet

TL;DR

DETR (DEtection TRansformer) finds objects in an image by predicting the whole set of boxes at once. A CNN extracts features, a transformer reads them, and a fixed number of learned slots each output one box and one class or "no object". A matching step pairs predictions with the true objects during training, so no duplicates are produced and no anchors or non-maximum suppression are needed.

Builds on: Transformer, Object Detection, Bipartite Matching · Leads to: Vision Transformer (ViT) (the same transformer-first approach to images, applied to classification and backbones)

Why it mattered

DETR showed that a detector could be built from a standard CNN and a standard transformer, with no custom layers. Before it, most detectors relied on anchors, proposals, and a post-processing step to remove overlapping boxes. DETR removed those pieces and matched a strong Faster R-CNN baseline on the COCO benchmark. Its design became a template for later transformer detectors that refine the same set-prediction idea. The paper also showed the one-to-one matching loss as a practical way to train set predictors, which has been reused in other tasks that output unordered sets.

The problem

Object detection asks for a set: for each object in an image, a box and a label, with the order of the objects not mattering. Most detectors do not learn this set directly. They define many surrogate problems, such as classifying many fixed boxes called anchors, or scoring region proposals, and then clean up the results. The clean-up is heuristic. Anchor sizes and aspect ratios must be chosen by hand, targets must be assigned to anchors by rules, and overlapping predictions of the same object must be removed with Non-Maximum Suppression.

Set prediction is hard for a neural network for a specific reason. Two predictions that are equally good for the same object must not both be trained to be the answer, or the detector will output duplicates. The loss has to pick exactly one prediction per object. The paper's goal is a loss that does this and an architecture where the predictions can interact, so that the model can decide that one object has already been claimed.

How it works

Follow one image through the network. Assume the input is 800 by 800 pixels and the scene has two objects, a cat and a dog.

flowchart LR
  A[Image 800 by 800] --> B[CNN backbone]
  B --> C[1 by 1 conv and flatten]
  C --> D[Transformer encoder]
  D --> E[Transformer decoder with 100 object queries]
  E --> F[Shared FFN per query]
  F --> G[100 boxes and class scores]
  G --> H[Bipartite matching with ground truth]
  H --> I[Loss on matched pairs]
  1. Take the image through a CNN. A ResNet-style backbone reduces resolution by a factor of 32. The 800 by 800 image becomes a 25 by 25 grid with 2048 channels. Each cell now summarises a patch of the image.
  2. Shrink the channels and flatten. A 1 by 1 convolution maps 2048 channels to a smaller width dd (256 in the ablations). The grid is flattened into a sequence of 25×25=62525 \times 25 = 625 tokens. Each token is one spatial cell.
  3. Add positions and encode. The transformer has no built-in sense of order, so a Positional Encoding is added to every token. The encoder's self-attention then lets each cell look at every other cell, which is how the model reasons about the whole image.
  4. Decode 100 object queries in parallel. The decoder has 100 learned input embeddings, called object queries. Each query attends to the encoder output and to the other queries. Because all queries run at once, the model can reason about how objects relate. A cat query and a dog query can see that they are separate, for example.
  5. Predict from each query. A small shared feed-forward network reads each query's output. It produces a class (cat, dog, or "no object") and a box given as centre, height and width, scaled to the image. Two of the 100 slots get the cat and dog. The other 98 say "no object".
  6. Match predictions to the truth. During training, the two real objects are matched to two of the 100 predictions. The matching chooses the assignment with the lowest total cost, which the Hungarian algorithm finds efficiently. The Hungarian algorithm is a standard method for finding the cheapest one-to-one pairing of two sets.
  7. Compute the loss on matched pairs. Matched pairs contribute a classification term and a box term. Unmatched slots contribute only a small "no object" term. At test time, step 6 is skipped: the 100 predictions are simply filtered by score, with no matching and no duplicate removal.

Check: 800 divided by 32 is 25, and 25 times 25 is 625 tokens. Each of the 100 queries produces exactly one output, so the model never produces more than 100 detections.

The math

Step 6 in symbols: the matching

Let the ground truth be a set y={yi}i=1Ny = \{y_i\}_{i=1}^{N}, padded with "no object" entries to length NN, where N=100N = 100 is the number of slots. Each entry is yi=(ci,bi)y_i = (c_i, b_i), a class cic_i and a box bi∈[0,1]4b_i \in [0,1]^4. The predictions are y^={y^i}i=1N\hat{y} = \{\hat{y}_i\}_{i=1}^{N}. The matching finds a permutation σ\sigma of the NN slots with the lowest total cost:

σ^=arg min⁡σ∑i=1NLmatch(yi,y^σ(i)).\hat{\sigma} = \operatorname*{arg\,min}_{\sigma} \sum_{i=1}^{N} \mathcal{L}_{\text{match}}\big(y_i, \hat{y}_{\sigma(i)}\big).

Here Lmatch\mathcal{L}_{\text{match}} is the cost of pairing ground truth ii with prediction σ(i)\sigma(i). For a real object it is the negative probability of its class, plus a box cost. For a "no object" entry it is a constant.

Step 7 in symbols: the loss

With σ^\hat{\sigma} fixed, the Hungarian loss is

LHungarian(y,y^)=∑i=1N[−log⁡p^σ^(i)(ci)+1{ci≠∅} Lbox(bi,b^σ^(i))].\mathcal{L}_{\text{Hungarian}}(y, \hat{y}) = \sum_{i=1}^{N} \Big[ -\log \hat{p}_{\hat{\sigma}(i)}(c_i) + \mathbb{1}_{\{c_i \neq \varnothing\}}\, \mathcal{L}_{\text{box}}\big(b_i, \hat{b}_{\hat{\sigma}(i)}\big) \Big].

The indicator 1{ci≠∅}\mathbb{1}_{\{c_i \neq \varnothing\}} is 1 for real objects and 0 for "no object", so unmatched slots add only the class term. The paper multiplies the class term for "no object" by 0.1, because most slots are empty and would otherwise dominate training.

The box loss mixes an ℓ1\ell_1 distance with the generalised intersection over union (Intersection over Union) to be less sensitive to box size:

Lbox(b,b^)=λiouLiou(b,b^)+λL1∥b−b^∥1,\mathcal{L}_{\text{box}}(b, \hat{b}) = \lambda_{\text{iou}} \mathcal{L}_{\text{iou}}(b, \hat{b}) + \lambda_{\text{L1}} \lVert b - \hat{b} \rVert_1,

where λiou\lambda_{\text{iou}} and λL1\lambda_{\text{L1}} are weights. The ℓ1\ell_1 term alone would give large boxes much bigger errors than small boxes of the same relative accuracy.

Step 4 in symbols: the decoder

Each object query qjq_j is a learned vector. The decoder maps the NN queries and the encoder output EE to NN output embeddings. Each output is then read by a shared network FFN\text{FFN}:

y^j=FFN(Decoder(q1,…,qN; E)j),j=1,…,N.\hat{y}_j = \text{FFN}\big(\text{Decoder}(q_1, \dots, q_N;\, E)_j\big), \qquad j = 1, \dots, N.

Because every query is decoded at the same time, permuting the queries permutes the outputs in the same way. The matching step then picks whichever query ends up on each object, so the order in which the queries are listed does not change what the model can predict.

Worked examples

Example
Example 1: a tiny matching with three predictions

Two real objects, a cat and a dog, and three predictions, p1,p2,p3p_1, p_2, p_3. The matching cost of each pairing is given in this table. Lower is better.

p1p_1p2p_2p3p_3
cat0.20.90.5
dog0.70.30.4
  1. Each real object must go to a different prediction. The cat can take p1p_1, p2p_2 or p3p_3, and the dog can take any of the other two.
  2. Try the six valid pairings and add the two costs. Cat to p1p_1 and dog to p2p_2 gives 0.2+0.3=0.50.2 + 0.3 = 0.5.
  3. Cat to p1p_1 and dog to p3p_3 gives 0.2+0.4=0.60.2 + 0.4 = 0.6. Cat to p3p_3 and dog to p2p_2 gives 0.5+0.3=0.80.5 + 0.3 = 0.8. The other pairings cost more.
  4. The minimum is 0.5, at cat to p1p_1 and dog to p2p_2. The slot p3p_3 is unmatched, so it is trained to say "no object".
  5. Interpretation: each object gets exactly one slot, and no two slots are trained to find the same cat. This is why no non-maximum suppression is needed.
Example
Example 2: the loss for that matching

Using the matching from Example 1, suppose the cat's slot gives probability 0.8 to the cat class, and the unmatched slot p3p_3 gives probability 0.9 to "no object". Ignore the box terms for this trace.

  1. The cat term is −log⁡0.8=ln⁡(1.25)≈0.223-\log 0.8 = \ln(1.25) \approx 0.223.
  2. The unmatched slot's "no object" term is −log⁡0.9≈0.105-\log 0.9 \approx 0.105.
  3. The paper down-weights that term by 0.1, giving 0.1×0.105≈0.0110.1 \times 0.105 \approx 0.011.
  4. Total class loss for these two slots is 0.223+0.011≈0.2340.223 + 0.011 \approx 0.234.
  5. Interpretation: most of the loss comes from the real object. The empty slot is still pushed toward "no object", but gently, so the rare positives are not drowned out.
Example
Example 3: the cost of the dilated encoder

The paper's DC5 variant removes a stride from the last backbone stage, so the feature map is twice as fine. Use an 800 by 800 input.

  1. The standard backbone uses stride 32, giving a 25 by 25 map and 625625 tokens.
  2. The dilated variant uses stride 16, giving a 50 by 50 map and 25002500 tokens.
  3. Self-attention compares every pair of tokens, so its cost grows with the square of the token count. Standard: 6252=390,625625^2 = 390{,}625 pairs. Dilated: 25002=6,250,0002500^2 = 6{,}250{,}000 pairs.
  4. The ratio is 6,250,000/390,625=166{,}250{,}000 / 390{,}625 = 16, so the encoder's self-attention costs 16 times more.
  5. Interpretation: finer features help small objects, but the quadratic attention cost is the price, and it is paid on every forward pass.

Results

The paper evaluates on COCO object detection and reports box average precision (AP) against Faster R-CNN with a feature pyramid (FPN) baseline. The headline comparison is close: with a ResNet-50 backbone, DETR is ahead of the plain Faster R-CNN baseline by under two AP points, and a Faster R-CNN given the same training improvements ties it. The best DETR variant, which uses a dilated last stage (DC5) and a ResNet-101 backbone, is slightly ahead of the matching Faster R-CNN. The paper's own conclusion is that DETR is competitive with a well-tuned detector and simpler to build, not that it is uniformly better.

The pattern across sizes is consistent with the mechanism above. DETR does better on large objects, which span many cells that the global attention can relate, and worse on small ones, which depend on fine detail that the coarse feature map loses. Read the paper's table for exact per-size numbers rather than trusting a figure given here.

Ablations in the paper show that the encoder layers help, that the positional encodings matter a lot, and that auxiliary losses on every decoder layer help training. Limits, stated by the authors: training is long, with hundreds of epochs, and small objects remain weaker than in the best Faster R-CNN.

Reading guide

The paper is read in this order. Each section names the lessons it needs.

  1. Section 1 (Introduction). Needs Object Detection for the task and Non-Maximum Suppression for the post-processing it removes.
  2. Section 2 (Related work). Needs Recurrent Neural Network and Autoregressive Model, because prior set predictors decoded one element at a time.
  3. Section 3.1 (Set prediction loss). Needs Bipartite Matching, Cross-Entropy Loss, Intersection over Union and Bounding-Box Regression. This is the core of the paper.
  4. Section 3.2 (Architecture). Needs Convolutional Neural Network, Positional Encoding, Multi-Head Attention, Encoder-Decoder Architecture and Feedforward Neural Network.
  5. Section 4 (Experiments). Needs Dropout and AdamW Optimizer for the training setup, and the AP metric from Object Detection.
  6. Appendix. Read the attention details there if Multi-Head Attention is unfamiliar.

Check yourself

QuestionWhy does DETR need a bipartite matching step during training, and what would go wrong with a one-to-many assignment?Show answer

Each real object should be explained by exactly one prediction. If several predictions were trained to match the same object, the network would learn to output duplicates, and the detector would need a post-processing step to remove them. Bipartite matching gives a one-to-one assignment, so duplicates are not rewarded and no non-maximum suppression is needed.

QuestionTwo objects, a cat and a dog, and two predictions p1p_1 and p2p_2. The costs are: cat to p1p_1 = 0.4, cat to p2p_2 = 0.1, dog to p1p_1 = 0.2, dog to p2p_2 = 0.6. Which pairing is chosen, and what is its cost?Show answer

There are two one-to-one pairings. Cat to p1p_1 and dog to p2p_2 costs 0.4+0.6=1.00.4 + 0.6 = 1.0. Cat to p2p_2 and dog to p1p_1 costs 0.1+0.2=0.30.1 + 0.2 = 0.3. The cheaper one is chosen: cat to p2p_2 and dog to p1p_1, with total cost 0.3.

QuestionThe decoder uses 100 object queries, but a typical COCO image has about 7 objects. What does the model do with the extra slots?Show answer

Each unused slot is trained to output "no object", with its class loss down-weighted by a factor of 10 to account for the imbalance. The slots still produce a box output, but the box loss is applied only to matched slots, so the boxes of empty slots are not trained.

QuestionWhy does DETR tend to be better on large objects and worse on small ones than Faster R-CNN with FPN?Show answer

Transformer self-attention lets each token look at the whole image, which helps with large objects that span many cells. Small objects depend on fine local detail, and the standard DETR works on a coarse 32-times-downsampled map, so it has less detail to work with.

Sources

Read the full paper

Nicolas Carion, Francisco Massa, Gabriel Synnaeve et al., 2020. arXiv:2005.12872