DETR (DEtection TRansformer) is a method that treats object detection as a problem of directly predicting the set of detections, outputs a fixed number of predictions at once with a Transformer encoder-decoder, and trains by matching predictions to ground truth one-to-one via bipartite matching. It was proposed by Carion et al. at Facebook AI in 2020 (ECCV 2020).
Earlier detectors placed large numbers of "initial guesses" — region proposals, anchors or grid centers — and refined each by classification and regression, an indirect way of detecting. As a result, their performance depended heavily on hand-designed components such as non-maximum suppression (NMS) to remove duplicate predictions, anchor design, and rules for assigning ground truth to anchors. DETR removes these components and builds a detector from just a standard CNN and a Transformer.
The main results of the paper are:
On the COCO validation set, DETR with ResNet-50 reaches 42.0 AP, matching a Faster R-CNN + FPN tuned to a similar number of parameters (about 41M) at 42.0.
Its AP on large objects is 61.1, much higher than Faster R-CNN (53.4), while its AP on small objects is lower at 20.5 (Faster R-CNN: 26.6).
With the same idea, simply adding a mask head extends it to panoptic segmentation (the task of dividing every pixel of an image by object and region), where it outperformed the methods of the time.
The paper also shows that the inference code can be written in fewer than 50 lines of PyTorch, and cites as an advantage that no special layers or dedicated libraries are needed.
The problem: removing hand-designed components
DETR addresses the problem that detector performance depends heavily on components like anchors and non-maximum suppression, into which people have written task knowledge by hand.
Faster R-CNN and SSD place thousands of reference boxes on the image and decide "which box is responsible for which object" by rules such as IoU with the ground truth. Because several boxes hit the same object, non-maximum suppression removes duplicates at the end. In both cases, accuracy changes with fine settings of the rules, and neither training nor inference can be expressed by a single loss.
The paper observes that the output of detection is inherently a "set of objects", in which order and duplication carry no meaning. Predicting a set directly requires two things:
A loss that matches predictions to ground truth one-to-one: regardless of the order of predictions, each ground-truth object is assigned exactly one prediction. Of duplicate predictions, all but one learn "no object".
An architecture that outputs the set at once while looking at relations among predictions: if predictions can see each other, they can avoid hitting the same object twice.
For the former, the paper uses the long-established Hungarian algorithm (a method for finding the optimal bipartite matching); for the latter, Transformer self-attention, which can handle relations between all pairs of elements.
As an everyday analogy, a conventional detector is like "placing an usher at every seat in a hall, having each report nearby guests, and finally removing duplicate reports". DETR is like "100 ushers consulting each other to assign one usher per guest, with the leftover ushers answering 'no guest'".
Theory: set prediction and the bipartite matching loss
DETR always outputs N predictions per image, finds the optimal one-to-one matching with the ground-truth set, and then computes the loss for each matched pair. N is set much larger than the typical number of objects in an image; the paper uses N=100. The right side of the figure at the top of the article shows this training flow.
Training proceeds per image as follows:
The network outputs N predictions y^={y^i}i=1N. Each prediction consists of class probabilities p^i(c) and a box b^i.
The ground-truth set y is padded to N elements with the class ∅, meaning "no object". Each ground-truth element is yi=(ci,bi), where ci is the class (possibly ∅) and bi∈[0,1]4 gives the box center, height and width relative to the image size.
The Hungarian algorithm finds the permutation σ^ that minimizes the total matching cost (Eq. 1).
For each matched pair, the class loss and box loss are computed (Eq. 2).
σ^=σ∈SNargmini∑NLmatch(yi,y^σ(i))
The matching cost considers both the class prediction and box similarity:
This matching plays the same role as the rules that assign anchors or proposals to ground truth in Faster R-CNN. The difference is that it finds a one-to-one matching without duplicates.
Once the matching is fixed, the Hungarian loss is computed:
The class term is the negative log-likelihood (cross-entropy). Terms with ci=∅ are down-weighted by a factor of 10 to account for the imbalance caused by the much larger number of no-object predictions. The matching cost uses the probability p^ without the logarithm to make it commensurate with the box loss; according to the paper, this also worked better in experiments.
The box loss is a weighted sum of the L1 loss and the scale-invariant generalized IoU (GIoU) loss. Because DETR predicts boxes directly rather than offsets from anchors, an L1 loss alone would give larger boxes larger losses even with the same relative error.
∣⋅∣ denotes area, and B(b,b^) is the smallest box enclosing both boxes. The paper sets λL1=5 and λiou=2, and both losses are normalized by the number of objects in the batch.
Because the matching is one-to-one, if two predictions hit the same object, one is matched to the ground truth and the other to ∅. The other one learns "no object", so as training progresses duplicate predictions naturally disappear. Instead of removing duplicates afterwards with non-maximum suppression, the loss itself teaches the model not to duplicate.
Architecture: CNN, Transformer and prediction FFN
The DETR network consists of three components: a CNN that extracts features, an encoder-decoder Transformer, and a small FFN that outputs detections. The left side of the figure at the top of the article shows the overall flow.
A CNN (e.g. ResNet-50) turns the image x∈R3×H0×W0 into a feature map f∈RC×H×W with C=2048 channels at 1/32 of the height and width.
A 1×1 convolution reduces the channels to d (256 in the paper), and the spatial dimensions are flattened into a sequence of HW vectors of dimension d.
The sequence passes through the encoder. Each layer has the standard form of self-attention via multi-head attention and an FFN. Because the Transformer does not distinguish sequence order, fixed sinusoidal positional encodings extended to 2D are added to the input of every attention layer.
Nlearned positional embeddings, called object queries, are fed to the decoder. The decoder transforms the N queries in parallel through self-attention among queries and attention to the encoder output, rather than emitting them one by one as in the original Transformer.
Each decoder output passes through a prediction FFN shared by all queries. The FFN outputs the box center, height and width (as fractions of the image) with a 3-layer MLP using ReLU, and the class (including ∅) with a linear layer and softmax.
The paper's baseline has 6 encoder layers, 6 decoder layers, width 256 and 8 attention heads, with 41.3M parameters (23.5M in ResNet-50 and 17.8M in the Transformer).
Auxiliary losses: during training, the same (weight-shared) prediction FFN and Hungarian loss are also applied to the output of every decoder layer. According to the paper, this helped especially with outputting the correct number of objects of each class.
DC5 variant: using dilated convolution in the last ResNet stage and removing the stride from that stage's first convolution doubles the feature-map resolution. This improves accuracy on small objects, but the encoder's self-attention cost grows 16× and the overall computation roughly doubles.
The paper reports that in a trained DETR, the self-attention of the last encoder layer already seems to separate regions by object. The decoder's attention, on the other hand, concentrated on object extremities (such as heads and legs). The paper conjectures that the encoder separates objects by looking at the whole image, while the decoder looks at extremities to determine class and boundaries.
Why it predicts without duplicates
The reasons DETR produces detections with few duplicates without non-maximum suppression can be summarized from the paper's analysis (ResNet-50, COCO validation set) as follows:
Decoder self-attention suppresses duplicate predictions: when non-maximum suppression was applied to the output of each decoder layer, it raised AP for the first layer's output, because the first layer alone cannot compute relations between outputs and tends to hit the same object several times. From the second layer on, self-attention suppresses duplicates, and at the last layer non-maximum suppression actually removed correct predictions and lowered AP slightly. AP rises by 8.2 points from the first layer to the last.
Global attention in the encoder separates objects: with zero encoder layers, AP dropped by 3.9 points, and AP on large objects by 6.0 points.
The GIoU loss supports box accuracy: removing the GIoU loss dropped AP by 4.8 points, whereas removing the L1 loss cost only 0.7 points.
Without positional encodings, positions cannot be distinguished: using no spatial positional encodings at all dropped AP by 7.8 points.
The FFNs in the Transformer matter too: removing the FFNs inside the Transformer (parameters from 41.3M to 28.7M) dropped AP by 2.3 points.
Number of encoder layers (6 decoder layers)
Encoder layers
GFLOPS / FPS
Parameters
AP
AP (small)
AP (large)
0
76 / 28
33.4M
36.7
16.8
54.2
3
81 / 25
37.4M
40.1
18.5
58.6
6
86 / 23
41.3M
40.6
19.9
60.2
12
95 / 20
49.2M
41.6
19.8
61.9
Loss combinations (the class loss is always used)
Box loss
AP
AP50
AP (small)
AP (medium)
AP (large)
L1 only
35.8
57.3
13.7
39.8
57.9
GIoU only
39.9
61.6
19.9
43.2
57.9
L1 and GIoU
40.6
61.6
19.9
44.3
60.2
Each object query learned to specialize in particular areas and box sizes. The paper also confirmed that queries are not strongly biased toward specific classes: although no training image contains more than 13 giraffes, the model found all 24 giraffes in a synthetic image.
Experimental results
COCO validation set: comparison with Faster R-CNN (AP averaged over IoU 0.5–0.95; models without R101 in the name use ResNet-50)
Model
GFLOPS / FPS
Parameters
AP
AP50
AP75
Small
Medium
Large
Faster R-CNN-DC5
320 / 16
166M
39.0
60.5
42.3
21.4
43.5
52.5
Faster R-CNN-FPN
180 / 26
42M
40.2
61.0
43.8
24.2
43.5
52.0
Faster R-CNN-R101-FPN
246 / 20
60M
42.0
62.5
45.9
25.2
45.6
54.6
Faster R-CNN-DC5+
320 / 16
166M
41.1
61.4
44.3
22.9
45.9
55.0
Faster R-CNN-FPN+
180 / 26
42M
42.0
62.1
45.5
26.6
45.4
53.4
Faster R-CNN-R101-FPN+
246 / 20
60M
44.0
63.9
47.8
27.2
48.1
56.0
DETR
86 / 28
41M
42.0
62.4
44.2
20.5
45.8
61.1
DETR-DC5
187 / 12
41M
43.3
63.1
45.9
22.5
47.3
61.1
DETR-R101
152 / 20
60M
43.5
63.8
46.4
21.9
48.0
61.8
DETR-DC5-R101
253 / 10
60M
44.9
64.7
47.7
23.7
49.5
62.3
The top three rows are public Detectron2 models (3x schedule), and the three "+" rows are Faster R-CNN models with the GIoU loss, the same random crops, and a longer schedule (9x, about 109 epochs) added to make them comparable with DETR. DETR matches the AP of Faster R-CNN-FPN+ with a similar number of parameters, clearly outperforms it on large objects, and falls behind on small objects. The paper suggests that the strength on large objects comes from Transformer self-attention handling information from the whole image.
Panoptic segmentation (COCO validation set, PQ): a head that outputs a mask per object was added to DETR's outputs, and each pixel was assigned to the mask with the highest score. DETR-R101 reached 45.1 PQ, outperforming PanopticFPN (ResNet-101, 44.1) retrained with the same data augmentation. It was especially strong on regions not counted as objects (stuff), such as sky and road, and reached 46 PQ on the test data.
Practical notes
Keep the following points in mind when using DETR:
Training takes a very long time: even the paper's analysis setting uses 300 epochs (learning rate divided by 10 at epoch 200), taking 3 days on 16 V100 GPUs with batch size 64. For the comparison with Faster R-CNN it was trained for 500 epochs (learning rate lowered at epoch 400), which gave 1.5 more AP than 300 epochs.
Weak on small objects: the feature map is at 1/32 of the image resolution, and AP on small objects is lower than Faster R-CNN + FPN. The DC5 variant improves this but roughly doubles the computation. The paper expects future improvements to close the gap, just as FPN improved small-object accuracy for Faster R-CNN.
There is an upper limit on the number of objects: it cannot detect more objects than the number of object queries N (100 in the paper). In an experiment in the paper's appendix with images of identical objects in a grid, it found all of them up to 50, but missed more beyond that; with 100 objects it found only 30 on average.
Tune training settings for the Transformer: the paper uses AdamW with a learning rate of 10−4 for the Transformer, 10−5 for the backbone CNN, weight decay 10−4, and gradient clipping at 0.1. It notes that making the CNN learning rate an order of magnitude smaller was important for stable training, especially in the first few epochs. The weights and statistics of the CNN's Batch Normalization are frozen.
The losses are normalized by "the number of objects in the batch", but when training on multiple GPUs, do not normalize by each GPU's share alone. Because the number of objects differs across GPUs, the paper's appendix cautions that the total number of objects across all GPUs must be used. It also reports that at inference, replacing slots whose top prediction is "no object" with the second-highest class and its probability raised AP by 2 points. Be aware that the numbers depend on the evaluation procedure.
Comparison with other methods
DETR is a detector that predicts the set directly, without anchors or non-maximum suppression. Compared from the same perspective:
Good balance of speed and accuracy. Weak on small objects
DETR
Learned object queries (100)
Bipartite matching with the Hungarian algorithm (one-to-one)
Not needed (the loss suppresses duplicates)
Simple architecture, strong on large objects. Long training, weak on small objects
DETR and Mask R-CNN both extend a detector to segmentation by adding a mask head, but DETR handles objects (things) and regions (stuff) with the same mechanism and needs no post-processing to reconcile overlapping masks.
Rough guidelines for choosing:
Many small objects, or limited training compute: conventional detectors such as Faster R-CNN combined with FPN are a better fit.
Mainly large objects, with less post-processing and hand-crafted settings: DETR is a candidate.
Detection and panoptic segmentation in one mechanism: the DETR architecture extends to it just by adding a mask head.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
from torchvision.models import resnet50, ResNet50_Weights
from torchvision.ops import box_convert, generalized_box_iou
'''
A small implementation of DETR built from the inference code in the paper's appendix (Listing 1), with Hungarian matching and the loss (Eqs. 1 and 2) added.
As in Listing 1, for readability the positional encoding is a learned embedding added only once to the input
(the paper's actual setting adds fixed sin/cos encodings to every attention layer). torchvision has no built-in DETR model
'''
class DETR(nn.Module):
def __init__(self, num_classes, hidden_dim=256, nheads=8, num_encoder_layers=6, num_decoder_layers=6, num_queries=100):
super().__init__()
# Use only the conv layers of ResNet-50 (2048 channels, 1/32 height and width)
self.backbone = nn.Sequential(*list(resnet50(weights=ResNet50_Weights.IMAGENET1K_V1).children())[:-2])
self.conv = nn.Conv2d(2048, hidden_dim, 1) # Reduce to d = 256 with a 1x1 convolution
self.transformer = nn.Transformer(hidden_dim, nheads, num_encoder_layers, num_decoder_layers, dropout=0.1)
self.linear_class = nn.Linear(hidden_dim, num_classes + 1) # The last one is "no object" ∅
self.bbox_mlp = nn.Sequential( # Boxes: 3-layer MLP (ReLU)
nn.Linear(hidden_dim, hidden_dim), nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim), nn.ReLU(),
nn.Linear(hidden_dim, 4))
self.query_pos = nn.Parameter(torch.rand(num_queries, hidden_dim)) # Object queries (N = 100)
self.row_embed = nn.Parameter(torch.rand(50, hidden_dim // 2))
self.col_embed = nn.Parameter(torch.rand(50, hidden_dim // 2))
def forward(self, inputs): # inputs: (1, 3, H0, W0) (one image at a time, as in Listing 1)
h = self.conv(self.backbone(inputs))
H, W = h.shape[-2:]
pos = torch.cat([
self.col_embed[:W].unsqueeze(0).repeat(H, 1, 1),
self.row_embed[:H].unsqueeze(1).repeat(1, W, 1),
], dim=-1).flatten(0, 1).unsqueeze(1) # (HW, 1, d)
h = self.transformer(pos + h.flatten(2).permute(2, 0, 1), # To the encoder: sequence of HW
self.query_pos.unsqueeze(1)) # To the decoder: N queries in parallel
return self.linear_class(h)[:, 0], self.bbox_mlp(h).sigmoid()[:, 0] # (N, num_classes + 1), (N, 4) = (cx, cy, w, h)
@torch.no_grad()
def hungarian_match(logits, boxes, tgt_labels, tgt_boxes, l1_weight=5.0, giou_weight=2.0):
'''Eq. (1): one-to-one matching minimizing cost = −p̂(c) + 5 × L1 + 2 × (1 − GIoU)'''
prob = logits.softmax(-1) # The matching cost uses probabilities without the log
cost_class = -prob[:, tgt_labels] # (N, num_targets)
cost_l1 = torch.cdist(boxes, tgt_boxes, p=1)
cost_giou = 1 - generalized_box_iou(box_convert(boxes, 'cxcywh', 'xyxy'), box_convert(tgt_boxes, 'cxcywh', 'xyxy'))
cost = cost_class + l1_weight * cost_l1 + giou_weight * cost_giou
pred_idx, tgt_idx = linear_sum_assignment(cost.cpu().numpy()) # Hungarian algorithm
return torch.as_tensor(pred_idx), torch.as_tensor(tgt_idx)
def hungarian_loss(logits, boxes, tgt_labels, tgt_boxes, num_classes, eos_weight=0.1, l1_weight=5.0, giou_weight=2.0):
'''Eq. (2): class loss for every matched pair, box loss only for pairs with objects'''
pred_idx, tgt_idx = hungarian_match(logits, boxes, tgt_labels, tgt_boxes, l1_weight, giou_weight)
target_classes = torch.full((logits.shape[0],), num_classes, dtype=torch.long) # Unmatched slots are ∅
target_classes[pred_idx] = tgt_labels[tgt_idx]
class_weight = torch.ones(num_classes + 1)
class_weight[num_classes] = eos_weight # Weight of ∅ is 1/10
loss_class = F.cross_entropy(logits, target_classes, weight=class_weight)
num_objects = max(len(tgt_labels), 1) # Box losses are divided by the number of objects
src, tgt = boxes[pred_idx], tgt_boxes[tgt_idx]
loss_l1 = F.l1_loss(src, tgt, reduction='sum') / num_objects
loss_giou = (1 - torch.diag(generalized_box_iou(box_convert(src, 'cxcywh', 'xyxy'),
box_convert(tgt, 'cxcywh', 'xyxy')))).sum() / num_objects
return loss_class + l1_weight * loss_l1 + giou_weight * loss_giou
num_classes = 91 # COCO class ids (same as Listing 1)
model = DETR(num_classes)
# 1e-4 for the Transformer, 1e-5 for the backbone CNN, weight decay 1e-4 (Section 4, Appendix A.4)
param_groups = [
{'params': [p for n, p in model.named_parameters() if not n.startswith('backbone')], 'lr': 1e-4},
{'params': model.backbone.parameters(), 'lr': 1e-5},
]
optimizer = torch.optim.AdamW(param_groups, weight_decay=1e-4)
# Example of one step (data loading omitted). Target boxes are (cx, cy, w, h) relative to the image
image = torch.randn(1, 3, 800, 1066)
tgt_labels = torch.tensor([18, 17]) # Example: dog and cat
tgt_boxes = torch.tensor([[0.30, 0.55, 0.40, 0.60], [0.75, 0.50, 0.30, 0.45]])
model.train() # Transformer dropout 0.1 is active
logits, boxes = model(image)
loss = hungarian_loss(logits, boxes, tgt_labels, tgt_boxes, num_classes)
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.1) # Clip gradient norm at 0.1
optimizer.step()
model.eval() # Inference: no non-maximum suppression
with torch.no_grad():
logits, boxes = model(image)
prob = logits.softmax(-1)[:, :-1] # Class probabilities excluding ∅
keep = prob.max(-1).values > 0.7
print(prob[keep].argmax(-1), boxes[keep])
# Pretrained models released by the authors can be loaded from torch.hub
# detr = torch.hub.load('facebookresearch/detr:main', 'detr_resnet50', pretrained=True)
FAQ
Q. What are object queries?
A.
They are N learned embeddings (100 in the paper) fed to the decoder. Each acts as a "slot" for one prediction and, inside the decoder, is transformed into one object's (class, box) or "no object" while looking at the image features and the other queries. The paper shows that after training, each query specializes in particular areas and box sizes.
Q. Why does DETR not need non-maximum suppression?
A.
Because during training, predictions are matched to ground truth one-to-one by bipartite matching. If two predictions hit the same object, one has to learn "no object", so duplicates are penalized by the loss. In addition, decoder self-attention lets predictions see each other, so as training progresses the model stops producing duplicates. In the paper, applying non-maximum suppression to the output of the last decoder layer actually lowered AP slightly.
Q. What are DETR's weaknesses?
A.
There are two main ones. One is long training: the paper trains for 300–500 epochs. The other is weakness on small objects: AP on COCO's small objects was lower than a similarly sized Faster R-CNN + FPN. In addition, it cannot detect more objects than the number of object queries (100).