Back to paper library
arXiv 2020ECCV 2020Object detectionPaper notes

DETR

A Cross-Domain Pioneer

Original paper

End-to-End Object Detection with Transformers

Paper authors

Nicolas Carion · Francisco Massa · Gabriel Synnaeve · Nicolas Usunier · Alexander Kirillov · Sergey Zagoruyko

Publication
ECCV 2020Conference
First submitted to arXiv
arXiv:2005.12872
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{objectdetectiondetr2020,
  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.12872}
}
On this page

Object detection has always been a core task in the field of computer vision.

Problem Definition

In object detection, anchor-based methods have long been popular. Faster R-CNN begins with proposals, while SSD and many YOLO variants use predefined anchors or grid locations, then classify and regress boxes from those starting points.

Although effective, this design introduces several problems:

  • The sizes and aspect ratios of anchors need to be manually designed based on the dataset characteristics, limiting generalization.
  • Multiple anchors correspond to each location, causing many redundant predictions that require Non-Maximum Suppression (NMS) to filter.
  • The alignment process between predicted boxes and ground truth is cumbersome, making the training pipeline highly coupled.

Not user-friendly?

What if we do not use anchors?

That is possible — anchor-free architectures have been developed for this purpose.

However, in practical scenarios, people want accuracy above all else! Users can tolerate a little delay (just a few seconds), and systems can be somewhat complex (after all, engineers handle that).

But if the model is inaccurate, I will complain!

Dropping anchors alone, though, does not settle which prediction should own each object, nor does it guarantee better accuracy on detection benchmarks.

Meanwhile, on the very same timeline, the neighboring field (NLP) has been vigorously advancing the latest Transformer architectures and achieving remarkable breakthroughs.

The authors of this paper propose:

Why don’t we discard these complicated mechanisms and try using Transformers together?

Solution

The overall architecture, as shown in the paper’s figure above, consists of three main modules:

  1. CNN Backbone: Extracts feature maps from the input image.
  2. Transformer Encoder-Decoder: Models the global context of the image and relationships between objects.
  3. Prediction Head (FFN): Outputs bounding boxes and classes.

Model Architecture

First, let’s look at the Backbone.

The Backbone takes an input image ximg∈R3×H0×W0x_{img} \in \mathbb{R}^{3 \times H_0 \times W_0} and outputs features f∈RC×H×Wf \in \mathbb{R}^{C \times H \times W} via a CNN backbone (e.g., ResNet-50, typically with C=2048C=2048, H≈H0/32H\approx H_0/32, and W≈W0/32W\approx W_0/32).

A 1×11 \times 1 convolution is applied to reduce the channel dimension to dd (e.g., d=256d=256), producing a feature map z0∈Rd×H×Wz_0 \in \mathbb{R}^{d \times H \times W}. This is then flattened into a sequence of length HWHW and fed into the Transformer encoder.

The Transformer Encoder uses the standard structure, with Multi-Head Self-Attention (MHSA) and a Feed-Forward Network (FFN) in each layer. Because the flattened tokens lack explicit spatial relationships, the authors use fixed two-dimensional sine/cosine encodings and add positional information in the attention layers.

Next is the Transformer Decoder. It produces NN prediction slots at once. This is not autoregressive: self-attention models the relationships among slots, then the set predictions are emitted in parallel.

Each output position corresponds to a learnable object query (∈Rd\in \mathbb{R}^d). The multiple decoder layers use self-attention and encoder-decoder attention to allow object queries to communicate with each other and align with image features. This enables the model to perform global reasoning across objects (e.g., considering relative object relations and overall distribution).

Finally, each of the NN decoder outputs uses shared prediction-head parameters: a linear layer for classification and a three-layer feed-forward network for box regression, producing:

  • Class probabilities (softmax over K+1K+1, where +1 denotes the "no object" class)
  • Bounding box coordinates (normalized center coordinates, width, and height)

Here, the model predicts a fixed-length set of candidate boxes, unlike traditional dense grids or anchor boxes. This design allows training via a set-based loss.

Loss Design

In past object detection training pipelines, the problem of "which ground truth should a predicted box align with?" is almost unavoidable.

For example, Faster R-CNN considers proposals with IoU > 0.5 as positive samples, and YOLO series assign predictions to the closest anchor box. These are all heuristic assignment rules, aiming to align predictions with ground truth to enable classification and regression training.

DETR, however, treats this as an optimization problem directly: it uses the Hungarian Algorithm for optimal one-to-one matching, so each real object trains one prediction and the remaining slots learn "no object." This discourages duplicate detections during training and removes the need for NMS in standard DETR inference.

  • Step 1: Optimal Matching (Bipartite Matching)

Suppose:

  • y={y1,y2,…,yM}y = \{ y_1, y_2, \dots, y_M \} is the set of ground truth objects, where each yi=(ci,bi)y_i = (c_i, b_i) includes class and bounding box.
  • y^={y^1,y^2,…,y^N}\hat{y} = \{ \hat{y}_1, \hat{y}_2, \dots, \hat{y}_N \} is the set of predictions from the decoder, where N≫MN \gg M, and y^j=(p^j,b^j)\hat{y}_j = (\hat{p}_j, \hat{b}_j).

To perform set matching, the authors pad yy with N−MN - M "no object" entries (denoted as ∅\varnothing) to equalize set lengths, then define a matching cost function LmatchL_{\text{match}} to compute errors between predictions and ground truth:

σ^=arg⁡min⁡σ∈SN∑i=1NLmatch(yi,y^σ(i))\hat{\sigma} = \arg\min_{\sigma \in S_N} \sum_{i=1}^N L_{\text{match}}(y_i, \hat{y}_{\sigma(i)})

Here, σ\sigma is a permutation of the NN predictions, searching for the best one-to-one alignment.

  • Step 2: Define Matching Cost

    The cost between a pair yi=(ci,bi)y_i = (c_i, b_i) and prediction y^j=(p^j(c),b^j)\hat{y}_j = (\hat{p}_j(c), \hat{b}_j) consists of two parts:

    • Classification cost: the smaller the predicted class probability p^j(ci)\hat{p}_j(c_i), the higher the cost.
    • Box cost: the larger the discrepancy between predicted box b^j\hat{b}_j and ground truth box bib_i, the higher the cost.

    Note: These losses apply only when ci≠∅c_i \neq \varnothing, i.e., for actual object matches.

    Formally:

    Lmatch(yi,y^j)=−1{ci≠∅}⋅p^j(ci)+1{ci≠∅}⋅Lbox(bi,b^j)L_{\text{match}}(y_i, \hat{y}_j) = -1_{\{c_i \neq \varnothing\}} \cdot \hat{p}_j(c_i) + 1_{\{c_i \neq \varnothing\}} \cdot L_{\text{box}}(b_i, \hat{b}_j)

    This matching cost uses the negative class probability, not its log. The authors report that it keeps the classification and box terms on more comparable scales and worked better empirically. The training loss below does use negative log probability.

  • Step 3: Calculate Final Loss (Hungarian Loss)

    After matching, the loss is computed as:

    LHungarian(y,y^)=∑i=1N[−log⁡p^σ^(i)(ci)+1{ci≠∅}Lbox(bi,b^σ^(i))]L_{\text{Hungarian}}(y, \hat{y}) = \sum_{i=1}^N \left[ -\log \hat{p}_{\hat{\sigma}(i)}(c_i) + 1_{\{c_i \neq \varnothing\}} L_{\text{box}}(b_i, \hat{b}_{\hat{\sigma}(i)}) \right]
    • The first term is the classification loss: lower predicted class probabilities for objects result in higher loss.
    • The second term is the box loss (explained below).
    • For ci=∅c_i = \varnothing (background), the classification loss is down-weighted by a factor of 0.1 to prevent background samples from overwhelming object signals (similar to subsampling in Faster R-CNN).
  • Step 4: Box Loss Design (LboxL_{\text{box}})

    Unlike anchor- or proposal-relative regression, DETR predicts image-normalized bounding box coordinates directly. While simple, this leaves a scale issue:

    For the same relative displacement, an ℓ1\ell_1 coordinate error is usually smaller for a small box than for a large one.

    To address this, the authors combine two losses:

    • ℓ1\ell_1 loss: directly measures coordinate difference, encouraging positional accuracy.
    • Generalized IoU (GIoU) loss: measures overlap quality between boxes, invariant to scale.

    The combined formula is:

    Lbox(bi,b^j)=λIoU⋅LGIoU(bi,b^j)+λℓ1⋅∥bi−b^j∥1L_{\text{box}}(b_i, \hat{b}_j) = \lambda_{\text{IoU}} \cdot L_{\text{GIoU}}(b_i, \hat{b}_j) + \lambda_{\ell_1} \cdot \| b_i - \hat{b}_j \|_1
    • λIoU\lambda_{\text{IoU}} and λℓ1\lambda_{\ell_1} are weight hyperparameters that require tuning.
    • All losses are normalized by the total number of objects per batch.

To summarize the key points of this loss design:

  • One-to-one matching: each real object trains one prediction, discouraging duplicate boxes so standard DETR inference does not need NMS.
  • Simple background handling: background treated as ∅\varnothing class, no dense negative sampling required.
  • Combination of GIoU + ℓ1\ell_1 balances location and overlap learning.

This is the core reason why, despite its simple architecture, DETR can truly realize end-to-end object detection in training.

Dataset

Experiments used COCO 2017 for object detection and its panoptic annotations for the segmentation extension. The detection split contains about 118,000 training images and 5,000 validation images. On average, each image contains 7 object instances, with up to 63 in some cases. Object sizes vary widely, with a mix of small and large objects, posing a challenging setting.

Model performance is mainly evaluated by Average Precision (AP) on bounding boxes. When comparing with Faster R-CNN, the authors use validation results from the last training epoch; for ablation studies, median results over the last 10 epochs are reported.

Technical Details

The model is trained using the AdamW optimizer with an initial learning rate of 1×10−41 \times 10^{-4} for the Transformer and 1×10−51 \times 10^{-5} for the backbone, and weight decay set to 1×10−41 \times 10^{-4}. The main comparison trains for 500 epochs; the ablations use 300 epochs. Transformer weights are initialized with Xavier initialization, and the backbone uses ImageNet-pretrained ResNet models with frozen BatchNorm layers.

The authors evaluate several backbone variants, including standard ResNet-50 (DETR) and ResNet-101 (DETR-R101), as well as DC5 variants (DETR-DC5 and DETR-DC5-R101) that add dilation in the last layer to increase feature resolution. The DC5 design improves small object detection but increases self-attention computation in the encoder by 16 times, roughly doubling overall FLOPs.

Multi-scale augmentation is used during training by resizing the shorter image side between 480 and 800 pixels, while limiting the longer side to 1333 pixels. To enhance global relational learning, random cropping augmentation is applied with a 0.5 probability, cropping random patches then resizing back to original scale, yielding roughly +1 AP improvement.

Additionally, for slots whose top class is "no object," the paper uses the second-highest class and its score for AP evaluation rather than simply discarding those slots. The paper reports about 2 AP more than that filtering alternative. Dropout of 0.1 is used during training, with other hyperparameters detailed in Appendix A.4.

Discussion

How does it perform this time?

Small objects clearly lag: with ResNet-101, Faster R-CNN-R101-FPN+ scores 27.2 APSAP_S and DETR-DC5-R101 scores 23.7; with ResNet-50, Faster R-CNN-FPN+ scores 26.6 and DETR 20.5. Still, the overall performance seems reasonable.


Carefully comparing DETR and Faster R-CNN training conditions and model performances reveals several key points:

  1. Fundamental Differences in Training Strategies

    DETR uses a Transformer architecture trained with AdamW, a longer schedule and dropout. The paper also notes that Transformers commonly use Adam or Adagrad.

    In contrast, traditional Faster R-CNN typically uses SGD with more conservative data augmentation. Conceptually, their design philosophies diverge significantly.

  2. Adjustments for Fair Comparison

    To ensure Faster R-CNN competes fairly, the authors applied enhancements including:

    • Adding generalized IoU to the box loss;
    • Applying the same random cropping data augmentation as DETR;
    • Extending training cycles to 9× (109 epochs).

    Together, these modifications add about 1–2 AP. The Faster R-CNN+ baseline trains for 109 epochs, while the main DETR comparison uses 500 epochs; the schedules are not the same.

  3. Model Design and Parameter Alignment

    DETR uses 6 encoder and 6 decoder layers, width 256 and 8 attention heads. Its roughly 41.3M parameters are close to Faster R-CNN + FPN; 23.5M belong to the ResNet-50 backbone and 17.8M to the Transformer. This aligns parameter count, not training or computational cost.

  4. Experimental Results and Key Observations

  • Overall performance: With ResNet-50, DETR reaches 42.0 AP on COCO validation, matching Faster R-CNN-FPN+.
  • Large object detection (APLAP_L): DETR scores 61.1, versus 53.4 for Faster R-CNN-FPN+, a 7.7-point gap from the table; the paper's prose calls it 7.8.
  • Small object detection (APSAP_S): DETR scores 20.5, versus 26.6, a 6.1-point deficit from the table; the paper's prose calls it 5.5, which does not match the table.
  • Higher-resolution variant (DETR-DC5): Despite improved total AP, it still fails to surpass Faster R-CNN on small objects.
  • Backbone variations: Using ResNet-101 backbone, the trends remain consistent across both models, indicating robustness of comparison.

Overall, DETR, under long training and high-resolution settings, can truly compete with Faster R-CNN at similar parameter counts.

However, it still lags on small objects. The original paper does not attribute that gap entirely to global attention or resolution; it leaves room for later architectures such as Deformable DETR to explore improvements.

Component Analysis of the Model

The authors thoroughly investigate the importance of each DETR component:

  1. Effect of Encoder Layers

    Removing the encoder eliminates image-level global self-attention. In the 300-epoch ablation, the six-layer baseline's 40.6 AP falls to 36.7, and APLAP_L falls from 60.2 to 54.2.

    The authors suggest that global encoder information helps distinguish objects in the scene. The attention examples below show some reference points attending to individual instances.

  2. Decoder Layers and NMS Relationship

    The DETR decoder has auxiliary supervision at every layer, so each layer is trained to produce object predictions. In the figure's long-schedule model, AP increases with depth; first to last layer differs by +8.2 AP and +9.5 AP50AP_{50}.

    Early layers suffer from duplicated predictions due to lack of context interaction. Applying traditional NMS after the first layer significantly reduces duplicates. However, as layers deepen, the model learns to suppress duplicates internally, making NMS benefit diminish, and even cause true positive removals in the final layer, reducing AP.

    Attention visualizations show decoder attention is relatively local, often focusing on object extremities (e.g., heads and feet). The authors infer that the encoder first distinguishes instances using global information and the decoder then gathers local evidence useful for classification and localization.

  3. Role of FFN in Transformer

    The feed-forward network (FFN) inside each Transformer block acts like a channel-wise 1×1 convolution. Removing those FFNs reduces the whole model from 41.3M to 28.7M parameters, as reported in the paper.

    However, this causes a 2.3 AP drop, indicating FFNs, despite structural simplicity, contribute substantially to semantic separation and feature transformation.

  4. Positional Encoding Design and Alternatives

    DETR uses two positional encodings:

    • Spatial positional encoding: input image position information.
    • Output positional encoding: embedded vectors for object queries.

    Output encoding is essential and cannot be removed. For spatial encoding, several variants were tested:

    • Removing spatial encoding entirely drops AP by 7.8 but still achieves over 32, showing some robustness.
    • Fixed sine encoding added only at the inputs lowers AP by 1.4; learned encoding added in each attention layer lowers it by 1.0.
    • Removing spatial encoding only from the encoder lowers AP by 1.3. Against the 7.8-point drop when all spatial encoding is removed, decoder spatial information matters more in this ablation.

    These results confirm that although Transformers naturally model sequences, explicit spatial cues remain indispensable for learning object positions and boundaries in vision tasks.

  5. Decomposing Loss Contributions

    DETR’s training loss consists of three parts:

    • Classification loss
    • Bounding box L1 loss
    • Generalized IoU (GIoU) loss

    Classification loss is indispensable. The authors tested ablations turning off L1 or GIoU losses:

    • Classification plus GIoU, without L1, gives 39.9 AP, 0.7 below the complete loss's 40.6.
    • Classification plus L1, without GIoU, gives 35.8 AP, 4.8 below the complete loss.

    The combined design remains the most stable configuration.

    This validates DETR’s core loss design philosophy: rather than relying on complex post-processing, incorporate spatial and semantic metrics directly into cost calculation and loss backpropagation.

Model Behavior Analysis

In the figure above, the authors visualize predictions across the COCO 2017 validation set. They show 20 of the 100 object-query slots and analyze the distributions of those slots' predicted boxes by position and size.

Each predicted box is represented by its normalized center coordinates in the [0, 1] × [0, 1] space, and color-coded according to its shape: green denotes small boxes, red indicates large horizontal boxes, and blue represents large vertical boxes.

The results show that each slot does not operate indistinctly, but naturally develops several preference patterns:

  • Some slots focus on specific spatial regions (e.g., top-left corner, center),
  • Some tend to predict boxes of particular scales or shapes,
  • Almost all slots have a mode that predicts a box close to the full image size; the authors suggest this may reflect the object distribution in COCO.

This spatial and scale specialization is not given through explicit slot-position labels; it is observed after training. The authors interpret the distributions as evidence that query slots learned different preferences.

Without relying on anchors or region proposals, each query slot effectively “attends” to specific regions or object scales, a unique behavior of set-based approaches.

Generalization to Unseen Object Counts

Most COCO images contain a limited number of objects per class. For instance, the training set never contains more than 13 giraffes appearing simultaneously. To test whether DETR can generalize to such extreme cases, the authors created a synthetic image containing 24 giraffes.

DETR finds all 24 instances in this synthetic image. As an out-of-distribution example, it supports two observations:

  • DETR’s object queries are not hard-coded to specific classes;
  • The model operates by flexibly assigning queries to objects based on the entire image, rather than binding classes to specific slots.

This echoes the earlier design philosophy: object queries are not bound to predefined classes at the start. The synthetic image supports generalization to 24 instances of one class.

Conclusion

No technique is perfect.

DETR clearly exhibits a bottleneck in small object detection, as confirmed by experimental data and visual analysis. Even with long training schedules and increased resolution, it still lags behind traditional methods on the APS_S metric. Compared to the well-established and engineering-mature Faster R-CNN, DETR only achieves comparable performance in certain scenarios, reminding us that it is not yet a universal solution for all tasks.

However, DETR’s value lies not in outright performance superiority, but in the new conceptual and architectural possibilities it opens.

DETR became an influential demonstration that a Transformer architecture can work competitively for object detection. It replaces anchors, proposals and NMS in its standard detection pipeline with set prediction and Hungarian matching. Its end-to-end design sends CNN image features through parallel Transformer decoding to a set of outputs, giving a once-complex pipeline conceptual clarity and room to extend.

Follow-up works based on this architecture number at least a hundred, making this a classic paper well worth multiple readings.