DETR

Also known as: Detection Transformer

On this page 7

DETR (Detection Transformer) is an object detection architecture that treats detection as direct set prediction: a convolutional backbone extracts image features, a transformer encoder-decoder reasons over them, and a fixed number of learned queries each output one class label and one bounding box. In computer vision, DETR was introduced in 2020 as the first widely adopted detector that removed hand-designed components such as anchor boxes, region proposals and non-maximum suppression.

The central idea is a bipartite matching loss. During training, every prediction is paired one-to-one with a ground-truth object, so the network learns to output each object exactly once. This design made DETR a foundation for a large family of transformer detectors used across artificial intelligence research and production systems.

How DETR turns an image into a set of objects

DETR processes an image in four stages that run end to end and are trained jointly. A CNN backbone, typically ResNet-50 or ResNet-101, reduces the image to a feature map at one thirty-second of the input resolution. A 1×1 convolution projects this map to a smaller channel dimension, usually 256, and the spatial grid is flattened into a sequence of tokens.

The transformer encoder applies self-attention across all tokens, so every image location can exchange information with every other location. Because attention is permutation-invariant, DETR adds fixed sine positional encodings to keep spatial layout. The transformer decoder then receives N learned embeddings called object queries, commonly 100, and refines them through self-attention among the queries and cross-attention to the encoded image.

Finally, a shared prediction head maps each decoder output to a class distribution and a normalized box given as center, width and height. A special no-object class absorbs the queries that do not correspond to any real object. The table below summarizes the role of each component.

ComponentFunctionTypical setting
CNN backboneExtracts visual featuresResNet-50, stride 32
Transformer encoderModels global context with self-attention6 layers, 8 heads
Object queriesLearned slots that each predict one object100 queries
Transformer decoderRefines queries using image features6 layers, 8 heads
Prediction headOutputs class and box per query3-layer MLP for boxes
Main components of the DETR pipeline

Bipartite matching and the set prediction loss

DETR trains with a one-to-one assignment computed by the Hungarian algorithm. For each image, the ground-truth set is padded with no-object entries to size N, and the algorithm finds the permutation of predictions that minimizes a total matching cost. Only after this matching is the loss computed, which means duplicate predictions are penalized directly during training.

The matching cost and the final loss combine three terms. Classification cost rewards a high probability for the correct class, the L1 box loss measures coordinate error, and the generalized IoU loss measures overlap in a way that is invariant to box scale. Auxiliary losses are also applied after every decoder layer, which stabilizes training of the deep decoder.

Loss termWhat it measuresTypical weight
Cross-entropyCorrect class or no-object1, with no-object down-weighted to 0.1
L1 box lossAbsolute coordinate error5
Generalized IoU lossScale-invariant box overlap2
Loss terms used by DETR

Because each object is claimed by exactly one query, DETR does not need non-maximum suppression at inference. The raw outputs, filtered only by a confidence threshold, are already the final detections.

How DETR compares with classic detectors

DETR differs from earlier detectors mainly in what it removes. Two-stage models such as Faster R-CNN generate region proposals with a region proposal network, and one-stage models such as YOLO, SSD and RetinaNet classify dense anchor grids. Both families produce many overlapping candidates and rely on post-processing heuristics to prune them.

PropertyDETRFaster R-CNNYOLO-style one-stage
Candidate generationLearned object queriesRegion proposals from anchorsDense anchor or grid cells
Duplicate removalLearned through matchingNon-maximum suppressionNon-maximum suppression
Global contextFull self-attentionLimited to local featuresLimited to receptive field
Training length on COCOAbout 500 epochsAbout 12 to 36 epochsAbout 100 to 300 epochs
Small object accuracyWeaker in original formStrong with feature pyramidModerate to strong
DETR compared with anchor-based detector families

On the COCO benchmark, the original DETR with ResNet-50 reached roughly 42 AP, comparable to a tuned Faster R-CNN with feature pyramid network. It performed better on large objects, thanks to global attention, and worse on small objects, because it uses only a single low-resolution feature map.

Variants that fixed the original weaknesses

The original DETR had two well-known weaknesses: slow convergence and weak small-object detection. Much of the follow-up work kept the set prediction framework while changing attention, queries or the assignment scheme. Several variants now reach over 60 AP on COCO with large backbones and extra data.

VariantMain changeEffect
Deformable DETRSparse attention over multi-scale featuresAbout 10x faster convergence, better small objects
Conditional DETRSpatial queries decoupled from contentFaster training
DAB-DETRQueries formulated as anchor boxesClearer query semantics
DN-DETRDenoising training with noisy ground truthMore stable matching
DINO (detector)Contrastive denoising and mixed query selectionState-of-the-art COCO accuracy
RT-DETREfficient hybrid encoderReal-time inference speed
Notable DETR variants and their main change

The same query-based design also extends beyond boxes. Panoptic segmentation heads attach mask predictions to each query, and later models such as Mask2Former generalize the idea to semantic, instance and panoptic segmentation within one architecture.

Practical use, limitations and common mistakes

DETR-style detectors are a good choice when a team wants a simple, end-to-end pipeline, strong performance on crowded or large objects, and easy extension to segmentation or open-vocabulary detection. For tight latency budgets, RT-DETR or a YOLO model is usually preferable to the original architecture.

  • Training budget is underestimated. The original model needs hundreds of epochs; using Deformable DETR or DINO cuts this substantially.
  • Too few object queries. N must exceed the maximum number of objects per image, or some objects can never be detected.
  • Small datasets without pretraining. Transformers need data; fine-tuning from COCO weights is strongly recommended.
  • Adding non-maximum suppression by habit. It is unnecessary and can remove correct overlapping detections.
  • Ignoring the no-object weight. Leaving it at 1.0 biases the model toward predicting background.

Memory use also deserves attention. Encoder self-attention grows quadratically with the number of tokens, so high-resolution inputs quickly become expensive unless sparse or deformable attention is used.

Understanding it simply

Imagine a team of 100 inspectors looking at one photo. Each inspector may point to one object at most. They talk to each other first, so two inspectors never point to the same car. Inspectors who find nothing simply say so.

That is how DETR works. It looks at the whole picture at once and gives a short, clean list of objects. Older systems guessed thousands of boxes and then deleted the extra ones. DETR learns to avoid duplicates from the start. The cost is that it takes longer to train.

Applied in practice

A logistics company wants to count parcels on a conveyor belt from overhead cameras. Parcels often touch and overlap, and its earlier anchor-based detector with non-maximum suppression merged adjacent boxes, which undercounted dense batches by roughly 4 percent.

The engineering team fine-tunes a Deformable DETR model pretrained on COCO, using about 6,000 labeled frames and 300 object queries, because a busy frame can hold more than 150 parcels. Training takes 50 epochs on four GPUs. Since no suppression step is needed, touching parcels keep separate boxes.

On a held-out test week, the counting error falls below 1 percent, and inference runs at about 20 frames per second, which is sufficient for the belt speed. The team later evaluates RT-DETR to free GPU capacity for a second camera line.