Understanding DETR: How Transformers Revolutionized Object Detection

DETR uses pure Transformer for end-to-end object detection, abandoning anchors and NMS with fixed-number predictions and set loss.
Based on a Bilibili creator's explanation, this article systematically breaks down DETR's core ideas and implementation details. It first reviews the pain points of traditional object detection relying on anchors and NMS, pointing out efficiency bottlenecks; then introduces how DETR uses a standard Transformer encoder-decoder architecture to completely abandon both and achieve end-to-end detection. It focuses on DETR's fixed-number prediction design (default 100 boxes), object query mechanism, and training via set prediction loss and bipartite matching. Finally, it discusses DETR's advantages in end-to-end simplicity, as well as limitations such as slow convergence and mediocre small-object performance, and mentions subsequent improvements like Deformable DETR.
The field of object detection has long been dominated by anchor-based methods, from Faster R-CNN to the YOLO series, all of which rely on non-maximum suppression (NMS) for post-processing. However, the emergence of DETR (Detection Transformer) broke this paradigm—it achieves end-to-end object detection using a pure Transformer architecture, completely abandoning anchors and NMS. Based on a Bilibili creator's explanation, this article takes a deep dive into DETR's core ideas and implementation details.
Pain Points of Traditional Object Detection: Anchor and NMS
Looking back at the development of object detection, Faster R-CNN emerged around 2015 as a pioneering work; its region proposal-based approach laid the foundation for two-stage detection. Subsequently, the YOLO series quickly gained popularity after 2016, simplifying detection into a single-stage regression problem. Although both have continuously evolved in speed and accuracy, the underlying logic has remained unchanged: preset a large number of anchors on the feature map, and filter out boxes containing objects through classification and regression.

This anchor-based route inevitably leads to a problem: a large number of overlapping candidate boxes are generated around the same object. To obtain the final result, non-maximum suppression (NMS) must be used to filter out redundant boxes. Although NMS is effective, it is inefficient, especially when the number of candidate boxes is huge, speed becomes a bottleneck. The Bilibili creator admitted in the video: "There's no way around it now—all the most popular object detection algorithms are based on Anchor, and in the end they all have to use NMS to filter."
Anchor refers to reference boxes pre-laid on the feature map at different scales and aspect ratios. Detection models do not directly regress object coordinates; instead, they predict the offset of each anchor relative to the ground-truth box and whether it contains an object. Faster R-CNN introduced the anchor mechanism in its region proposal network, while YOLO directly associates anchors on the grid; both rely on this design to cover targets of different sizes and shapes. The number of anchors is usually far greater than the actual number of objects (several to dozens per pixel), thus generating a large number of redundant candidates—this is the fundamental reason why NMS is subsequently necessary.
Non-Maximum Suppression (NMS) is a post-processing algorithm: it sorts candidate boxes by confidence, keeps the highest-scoring box, and suppresses the rest whose intersection-over-union (IoU) with it exceeds a threshold, iterating until all boxes are processed. NMS can effectively remove duplicate detections, but its computational cost is approximately linear in the number of candidate boxes, making it significantly time-consuming when anchors are dense; meanwhile, the IoU threshold is a manually set hyperparameter that is difficult to adapt to crowded object scenes. One of DETR's core motivations is precisely to eliminate dependence on both from the architecture level.
DETR's Disruptive Design: No Anchor or NMS Needed
DETR's breakthrough lies in completely discarding anchors and NMS, directly using Transformer's encoder-decoder architecture to output detection results. This is a thorough end-to-end application of Transformer in vision tasks—not only using the encoder to extract features but also using the decoder to generate predictions.

The Bilibili creator emphasized: "DETR doesn't need NMS, nor does it need to be based on Anchor, yet it can still perform object detection." This design makes DETR a typical representative of Transformer in the CV field; it could even be said that DETR is what made Transformer "take off" in detection tasks. Previously, Transformer was mostly used as a backbone for feature extraction, but DETR proved that Transformer can independently complete downstream tasks.
Overall Architecture: From CNN to Transformer
DETR's pipeline can be summarized as: the input image first passes through a CNN backbone to extract features, then the feature map is flattened into a sequence and fed into the Transformer encoder. The encoder is responsible for capturing global context information and outputs a set of feature vectors. Unlike the original Transformer, DETR does not adopt Swin Transformer's window hierarchical structure but directly uses the standard Transformer.

The encoder part is familiar to readers who know Transformer, but DETR's focus is on the decoder. The decoder receives the encoder's output and generates predictions through object queries. The Bilibili creator pointed out: "Previously when we talked about Transformer, the focus was on the encoder, but DETR's decoder needs to output detection results—this is what we'll focus on today."
Core Mechanism: Fixed Number of Prediction Boxes
A key design of DETR is that regardless of how many objects are in the image, the model predicts a fixed number (default 100) of bounding boxes. The Bilibili creator explained: "An image typically has only a few, a dozen, or at most twenty or thirty objects—it's impossible to exceed one hundred." Therefore, DETR sets an upper limit N=100; for each image, the decoder outputs N prediction boxes.

Among these N prediction boxes, only some correspond to real objects (positive samples), while the rest are marked as "no object" (negative samples). For example, if there are only two ducks in the image, then only 2 of the 100 prediction boxes are positive samples, and the remaining 98 are background. This design may seem redundant, but through set prediction loss and bipartite matching, DETR can learn the responsibility of each prediction box.
Set Prediction Loss is the core of DETR training. Since the model outputs N unordered prediction boxes and the number of ground-truth boxes M is usually much smaller than N, directly computing loss position-by-position would fail due to inconsistent ordering. DETR adopts bipartite matching: first compute the matching cost between all prediction boxes and ground-truth boxes (a weighted sum of classification probability and box coordinates), then use the Hungarian algorithm to find the optimal one-to-one matching that minimizes the total cost. After matching, classification and regression losses are computed only for the matched positive samples, while the remaining prediction boxes are supervised as the "no object" class. This mechanism ensures that each real object is assigned to exactly one prediction box, thereby naturally suppressing duplicate predictions during training and replacing the role of NMS.
Decoder and Object Queries
The decoder's input includes the encoder output and a set of learnable object queries. Each query corresponds to a prediction box; through self-attention, it interacts with the encoder output and finally outputs the class and coordinates for each box. The Bilibili creator focused on explaining the decoder's working mechanism in the video. Although the transcript did not elaborate in detail, it can be inferred that its core lies in the iterative optimization of queries.
DETR's decoder is similar to the encoder but adds a masked attention mechanism to ensure each query only attends to a specific region. During training, the Hungarian algorithm is used to optimally match prediction boxes with ground-truth boxes and compute the loss. During inference, N boxes are directly output without NMS.
Object Queries are the learnable inputs to DETR's decoder, typically N fixed-length vectors (e.g., 100), each eventually corresponding to a prediction box. They do not come from image features; instead, as "slots," they gradually learn priors for different positions and scales during training: some queries tend to detect large objects, while others focus on small objects or specific regions. In the decoder, queries communicate with each other via self-attention to avoid duplicate predictions, and then extract image features relevant to themselves from the encoder output via cross-attention. This design enables DETR to generate diverse candidate boxes without anchors; the queries themselves act as learnable "soft anchors." However, their initialization and training strategy significantly affect convergence speed, which has also been a key focus of subsequent improvements.
Advantages and Limitations
DETR's advantages are obvious: end-to-end training, no need for hand-designed anchors, no NMS post-processing—simplifying the detection pipeline. But its limitations cannot be ignored: slow training convergence, mediocre performance on small objects, and high computational complexity. The Bilibili creator did not discuss these in depth in the video, but from industry practice, subsequent improvements such as Deformable DETR precisely target these issues.
Deformable DETR is an improvement addressing the original DETR's two major weaknesses: slow convergence and weak small-object detection. Its core is Deformable Attention: each query no longer computes attention with all positions on the feature map but samples only a small number (e.g., 4) of key points, whose positions are dynamically predicted from the query content. This greatly reduces computational complexity, enabling the model to use multi-scale feature maps and thus improve small-object detection; meanwhile, sparse sampling allows each query to focus on the target region faster, reducing training epochs to about one-tenth of the original. Subsequent works such as DAB-DETR and DN-DETR further accelerate convergence from the perspectives of query modeling and denoising training, together forming an important evolution path of the DETR series.
Conclusion
DETR redefined object detection with a pure Transformer architecture. Its core ideas—fixed-number prediction and set loss—opened up new directions for subsequent research. The Bilibili creator's explanation starts from the pain points of traditional methods and gradually reveals DETR's design motivations and implementation details, suitable for readers who want to understand Transformer applications in CV. Although the video is based on an earlier version, the principles still apply.
Related articles

n8n's Open-Source AI Agent Nod: Self-Hostable, Model-Optional
n8n launches Nod, an open-source AI agent supporting self-hosting, any model choice (including local models), proactive background execution, broad app connections, and excellent secure defaults with a built-in vault for passwords and credit card info.

Clay Builds a Sales Growth Engine with Codex and ChatGPT
Clay builds a self-learning revenue engine with GPT-6 Sol and Astra, using Codex to orchestrate GTM plays and enrich leads so reps focus on high-value conversations.

Deep Learning for Graduate Students: A Six-Step Method to Get Past Training Pipeline Roadblocks
Stuck on getting your deep learning training pipeline to run? This six-step method covers neural network basics, PyTorch, CNN, Transformer, paper reproduction, and experiment design.