# End-to-End Object Detection with Transformers

Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko · arXiv · 2020-5-26

- **Problem** Modern detectors predict boxes through surrogate tasks such as proposals, anchors or window centers, and then need postprocessing such as NMS to remove duplicates. DETR asks whether detection can instead be posed as direct set prediction.
- **Method** A CNN backbone feeds a transformer encoder-decoder that decodes a fixed set of learned object queries in parallel. A Hungarian-matching set loss, with a classification term and a box term, trains the model end to end.
- **Results** DETR with a ResNet-50 backbone reaches 42.0 AP on the COCO validation set, against 40.2 AP for Faster RCNN-FPN, with a much higher AP L and a lower AP S. A simple mask head extends it to panoptic segmentation.

![Figure 2: DETR uses a conventional CNN backbone to learn a 2D representation of an input image. The model ﬂattens it and supplements it with a positional encod…](https://refivu.com/papers/8dd88d07-a896-4e8b-812e-b56f620aeed0/figures/figure-fbf0014fae396853aab207a8150f71e5.png?thumb=512)

**Fig. 2** : DETR uses a conventional CNN backbone to learn a 2D representation of an input image. The model ﬂattens it and supplements it with a positional encoding before passing it into a transformer encoder. A transformer decoder then takes as input a small ﬁxed number of learned positional embeddings, which we call object queries, and additionally attends to the encoder output. We pass each output embedding of the decoder to a shared feed forward network (FFN) that predicts either a detection (class and bounding box) or a “ no object ” class.

[Original paper](https://arxiv.org/abs/2005.12872v3) · [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/) · Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko · End-to-End Object Detection with Transformers · Original paper figure · Extracted the figure area from page 7 of the original PDF.

## Why detection is usually framed indirectly

The goal of object detection is to output a set of bounding boxes with category labels, one for each object of interest. Most detectors do not predict that set directly. They define regression and classification targets over many proposals, anchors or window centers, and the design of those targets shapes the result. Such detectors depend on postprocessing that collapses near-duplicate predictions, on the anchor design and on heuristics that match target boxes to anchors.

Set-level, end-to-end training is standard in structured prediction tasks such as machine translation and speech recognition, but earlier object detection attempts either added extra prior knowledge or did not match strong baselines on hard benchmarks. DETR is an attempt to close that gap by predicting the whole set directly, without surrogate tasks.

## Matching predictions to objects with a set loss

Training first searches for the permutation of the N predictions that has the lowest total matching cost, which is solved with the Hungarian algorithm. Each ground-truth element is a pair of a class label c\_i and a box b\_i in \[0, 1\]^4. The matching cost for a ground-truth element and the prediction at index σ(i) combines the predicted probability of the true class with the box loss, and it is only active when the class is not ∅.

Once the matching is fixed, the Hungarian loss sums a negative log-probability term over all N slots, and adds the box loss for the slots that have a real object. Written out, the loss is \\( \\mathcal{L}\_{\\text{Hungarian}}(y, \\hat{y}) = \\sum\_{i=1}^{N} \[ -\\log \\hat{p}\_{\\hat{\\sigma}(i)}(c\_i) + \\mathbb{1}\_{c\_i \\neq \\emptyset} \\mathcal{L}\_{\\text{box}}(b\_i, \\hat{b}\_{\\hat{\\sigma}(i)}) \] \\), where \\( \\hat{\\sigma} \\) is the optimal assignment from the matching step.

The log-probability term for the ∅ class is down-weighted by a factor of 10 to account for class imbalance, and the matching uses probabilities rather than log-probabilities so that the class term is on a scale comparable to the box term.

Because the matching is one-to-one, the loss does not depend on the order in which the predictions are listed. That property is what lets DETR emit all of its predictions in parallel.

## Box loss with scale invariance

DETR predicts boxes directly rather than as offsets from initial guesses. An L1 loss alone would weight large and small boxes differently even when their relative errors are similar. The box loss therefore combines a generalized IoU loss, which is scale-invariant, with an L1 loss on the box coordinates, using weights λ\_iou and λ\_L1.

## From image to parallel predictions

A conventional CNN backbone maps the input image to a lower-resolution activation map, with 2048 channels and height and width at 1/32 of the input in the typical setting. A 1x1 convolution reduces the channels to d, and the spatial grid is flattened into a sequence of HW tokens. Because attention is permutation-invariant, fixed positional encodings are added to the inputs of each attention layer.

Each encoder layer contains multi-head self-attention and a feed-forward network, which lets every image location attend to the whole image.

The decoder takes N learned object queries and attends both to them and to the encoder output. Since all N queries are decoded in one pass at every layer, the objects are produced in parallel instead of one at a time as in the original autoregressive transformer. Each output embedding goes through a shared feed-forward network that gives a normalized box and a class label.

The class is predicted with a softmax, and the no-object class is used for unused slots. Auxiliary losses with prediction heads after every decoder layer, sharing their parameters, help the model learn the correct number of objects per class.

## Training and evaluation setup

Experiments use COCO 2017 detection and panoptic annotations, with 118k training images and 5k validation images. AP is reported as bounding box AP unless stated otherwise. Two backbones are reported, ResNet-50 and ResNet-101. A dilated last stage raises the feature resolution, which the authors report helps small objects at about twice the computational cost.

Training uses multi-scale inputs and random crops in some iterations, which the authors report adds about 1 AP. The ablations use a 300-epoch schedule with a learning rate drop after 200 epochs, and the longer schedule used against Faster R-CNN runs for 500 epochs. The model uses 100 decoder query slots in all experiments.

## COCO comparison with Faster R-CNN

On the COCO validation set, the ResNet-50 DETR reaches 42.0 AP, against 40.2 AP for Faster RCNN-FPN with the same backbone. The authors also strengthen the Faster R-CNN baseline by adding a GIoU loss, the same random crop augmentation and a longer schedule. In that enhanced setting Faster RCNN-FPN+ reaches 42.0 AP.

The gap is uneven across object sizes. DETR scores 61.1 AP L against 52.0 for Faster RCNN-FPN, but 20.5 AP S against 24.2. The authors attribute the large-object gain to the global computation of the transformer, and they expect future work to close the small-object gap in the way FPN did for Faster R-CNN.

Table 1 places DETR and Faster R-CNN variants side by side with GFLOPS, FPS and parameter counts, which lets the cost of each entry be read with its accuracy.

## Encoder depth and the decoder stack

In the encoder-size ablation the decoder is fixed at six layers while the encoder varies. The baseline with six encoder layers reaches 40.6 AP, and removing all encoder layers drops AP to 36.7. That drop is 3.9 AP overall and 6.0 AP on large objects, which the authors read as evidence that global self-attention helps separate instances before decoding.

Figure 3 shows encoder self-attention for reference points, and the attention separates individual instances.

Auxiliary losses after each decoder layer let AP be measured at every decoding stage, and AP rises after each layer, with 8.2 AP gained between the first and the last layer. Applying NMS to the output of each decoder layer helps the first layer, where no cross-correlation between outputs has yet been computed, and it helps less as depth increases.

At the last layer, NMS removes some true positives and lowers AP slightly. The authors read this as evidence that self-attention in later decoder layers suppresses duplicates on its own, so the set loss does not need NMS.

Removing the feed-forward networks from the transformer cuts the parameter count from 41.3M to 28.7M and lowers AP by 2.3 points, which the authors use to argue that the FFNs matter.

## Positional encodings and loss components

Removing spatial positional encodings entirely while passing learned output encodings at the decoder input gives 32.8 AP, a drop of 7.8 AP from the baseline. Passing fixed sine encodings only once at the decoder input gives 39.2 AP, 1.4 below the baseline, which passes encodings to every attention layer. Removing spatial encodings only in the encoder costs 1.3 AP, and learned spatial encodings at the attention layers give similar results.

Training with only the classification term and the L1 loss gives 35.8 AP, while the classification term with GIoU alone gives 39.9 AP and the full combination gives 40.6 AP. The authors conclude that GIoU accounts for most of the model's performance, and that L1 alone gives poor results. They note that only the simple weighting was tried.

## Slot specialization and instance count

Figure 7 plots the boxes predicted by 20 of the 100 slots over the COCO 2017 validation images. Each slot shows several modes, each tied to particular areas and box sizes, and almost all slots predict image-wide boxes. The authors hypothesize that the image-wide boxes reflect the distribution of objects in COCO.

COCO has no image with more than 13 giraffes in the training set. A synthetic image with 24 giraffes is detected by DETR, which the authors take as evidence against strong class specialization in each query.

## Panoptic segmentation extension

Each mask is supervised with the DICE/F-1 loss and the focal loss. Training can be joint or two-stage, and the two-stage version freezes the detection weights and trains the mask head for 25 epochs. At inference, the final panoptic map is the pixel-wise argmax over mask scores, which removes overlaps without a separate heuristic.

With ResNet-101, DETR-R101 reaches 45.1 PQ, against 44.1 PQ for PanopticFPN++ with ResNet-101. The ResNet-50 DETR scores 43.4 PQ against 42.4 PQ for the ResNet-50 PanopticFPN++. The gain is largest on stuff classes, where DETR-R101 reaches 37.0 PQ st. The authors attribute this to the global reasoning of encoder attention, but for things the mask AP is up to 8 mAP below the baselines even though PQ th remains competitive.

## Limitations

DETR is weaker on small objects, and the authors name small-object performance and training as open challenges. DETR needs a much longer training schedule than the standard detectors, and the ablations rely on a 300-epoch schedule. The instance-count test shows saturation above 50 visible instances, so the behavior beyond the tested range is not characterized.

## Paper info

- **Authors**: Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko
- **Venue**: arXiv · Preprint
- **First published**: 2020-5-26
- **Added**: 2026-10-20
- **Updated**: 2020-5-28
- **Version**: v3
- **arXiv**: 2005.12872
- **Category**: cs.CV
- **Original paper terms**: [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/)
- **What we show**: Paper info, commentary and permitted figures from the original paper

[Original paper ↗](https://arxiv.org/abs/2005.12872v3) · [PDF ↗](https://arxiv.org/pdf/2005.12872v3)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko (2020). End-to-End Object Detection with Transformers. arXiv:2005.12872v3. https://arxiv.org/abs/2005.12872v3

**BibTeX**

```
@misc{carion2020object,
  title = {{End-to-End Object Detection with Transformers}},
  author = {Nicolas Carion and Francisco Massa and Gabriel Synnaeve and Nicolas Usunier and Alexander Kirillov and Sergey Zagoruyko},
  year = {2020},
  eprint = {2005.12872},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2005.12872v3}
}
```

## Other paper commentary

- [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://refivu.com/en/papers/d2c6b7fa-f256-44cf-9328-c55d713768da-swin-transformer-hierarchical-vision-transformer-using.md)
- [Learning Transferable Visual Models From Natural Language Supervision](https://refivu.com/en/papers/c2ad57ff-fd96-4ad1-af27-4195a16c557d-learning-transferable-visual-models-from-natural-language.md)
- [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://refivu.com/en/papers/8a112940-90e3-4c6b-8fa0-d576b3ebd5d1-an-image-is-worth-16x16-words-transformers-for.md)
- [Deep Residual Learning for Image Recognition](https://refivu.com/en/papers/19d6446d-fd9a-4e80-b535-a4e333cad216-deep-residual-learning-for-image-recognition.md)
- [ArcFace: Additive Angular Margin Loss for Deep Face Recognition](https://refivu.com/en/papers/c413067c-e2eb-43a0-8011-b952f120296a-arcface-additive-angular-margin-loss-for-deep-face.md)
- [Memory as Dynamics: Learning Reliability-Guided Predictive Models for Online Video Perception](https://refivu.com/en/papers/9edb7769-5017-4985-b695-21eab77d07d7-memory-as-dynamics-learning-reliability-guided-predictive.md)
- [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://refivu.com/en/papers/70da27bf-5c2f-4e05-bfe2-7c145011b0d9-distilbert-a-distilled-version-of-bert-smaller-faster.md)
- [QLoRA: Efficient Finetuning of Quantized LLMs](https://refivu.com/en/papers/27d2d955-4f1a-4d56-aef7-766870813fe4-qlora-efficient-finetuning-of-quantized-llms.md)
- [The Power of Scale for Parameter-Efficient Prompt Tuning](https://refivu.com/en/papers/b52e4465-a64e-4e31-94a8-52b414c956c9-the-power-of-scale-for-parameter-efficient-prompt.md)
- [ReAct: Synergizing Reasoning and Acting in Language Models](https://refivu.com/en/papers/332bb0c8-840f-4238-89c1-dfa32572b3d8-react-synergizing-reasoning-and-acting-in-language-models.md)
- [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://refivu.com/en/papers/7a3fbf64-0a8d-440d-a8cf-5d65c573adde-albert-a-lite-bert-for-self-supervised-learning.md)
- [Parameter-Efficient Transfer Learning for NLP](https://refivu.com/en/papers/617c096f-a488-458f-9a8f-89779c96eda7-parameter-efficient-transfer-learning-for-nlp.md)

## Terms in this paper

- [Transformer](https://refivu.com/en/terms/48e8be2570bc-transformer)
- [COCO](https://refivu.com/en/terms/41f3215c4f4a-coco)
- [ResNet](https://refivu.com/en/terms/ca7e0121c7a8-resnet)
- [Faster R-CNN](https://refivu.com/en/terms/6a6dc13482bb-faster-r-cnn)
- [AP](https://refivu.com/en/terms/476f7c8deadf-ap)
- [DETR](https://refivu.com/en/terms/86857f2f379d-detr)
- [Hungarian Algorithm](https://refivu.com/en/terms/0d512d80548f-hungarian-algorithm)
- [positional encodings](https://refivu.com/en/terms/3424fe16f570-positional-encodings)
- [panoptic segmentation](https://refivu.com/en/terms/0fdb08320aa0-panoptic-segmentation)
- [Non-maximal suppression](https://refivu.com/en/terms/9e5fcd39d0bf-non-maximal-suppression)
- [object queries](https://refivu.com/en/terms/59f62c82701a-object-queries)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/8dd88d07-a896-4e8b-812e-b56f620aeed0-end-to-end-object-detection-with-transformers)
