TT Lab
Blog

한국어 English 日本語 中文

Get started
Blog

Blog

DETR: Detection as Set Prediction with Hungarian Matching and Anchor-Free Detection

Status: Draft (2026-10-13), partially measured. The Hungarian and GIoU examples are values run directly on a notebook CPU (code/08_hungarian.py, under 1 second). Paper figures were taken from the original text along with their conditions, and hardware is noted by tier. Writing rules: Measured data is the baseline, and unmeasured items are marked as "Unmeasured".

Table of Contents

1. Hand-Crafted Components

Detectors in parts 5 and 6 relied on many human-designed components: anchor sizes and ratios, IoU thresholds for assigning positive/negative labels to anchors, and NMS with its threshold for removing duplicates. While these components work when tuned properly, they must be readjusted when the data changes, and poor tuning quietly introduces blind spots ("0 positives" and "NMS removing player B" from part 5).

DETR (DEtection TRansformer) by Carion et al. changes the question. The ground truth of detection is a set of boxes. It has no order and no duplicates. If so, why not train the model to output a set right from the start, eliminating the need for both anchors and NMS?

2. Architecture: N Query Slots

DETR: 질의 N개가 상자를 내고, 정답과 1:1 로 짝짓는다 CNN 몸통 특징 지도 트랜스포머 인코더 · 디코더 질의 슬롯 N=100개 슬롯 0: 선수 슬롯 1: 없음 슬롯 2: 공 슬롯 3: 없음 슬롯 4: 선수 슬롯 5: 없음 선수 A 선수 B 공 짝이 없는 슬롯(1·3·5)은 「물체 없음」을 배운다. 짝짓기: 비용(클래스 확률 + L1 + GIoU)의 합이 가장 작게(헝가리안). 짝이 하나뿐이라 NMS 가 필요 없다. → 학습 때만 정답과 짝짓기, 추론 때는 「없음」이 아닌 슬롯을 그대로 출력
Figure: DETR, where query slots passing through a CNN backbone and Transformer each output boxes and are matched 1:1 with ground truth during training
  1. CNN backbone(such as ResNet-50) generates a feature map.
  2. Transformer encodermixes relationships between positions in the feature map using self-attention (Part 7).
  3. Transformer decoderreceives learned N=100 query slots. Each slot views the encoder output via cross-attention and each other via self-attention.
  4. A small MLP per slot outputs a class (including "no object") and a single box.

The fact that slots attend to one another is crucial. Since the network can learn that "another slot is handling that object, so I will handle something else," the NMS step for removing duplicates becomes unnecessary. In fact, the paper reported that applying NMS to the final layer output actually slightly decreases AP.

3. Training: 1:1 Matching

There are 100 outputs and usually a few ground-truth items. Which outputs should be compared against which ground-truth items to calculate the loss? DETR finds the 1:1 match with the lowest cost.

짝 비용(정답 i, 슬롯 j) = −p_j(정답 i 의 클래스) + 5 · L1(상자) + 2 · (1 − GIoU(상자))

(Weights λ_L1 = 5, λ_iou = 2 are paper values.) Once matches are determined, matched slots learn the target class and box, while unmatched slots learn "no object." Because "no object" applies to the vast majority of slots, its loss is scaled down by a factor of 10 (addressing the imbalance issue similar to focal loss in Part 4). Auxiliary losses are also applied to all decoder layer outputs.

This matching is the classic assignment problem, solved using Kuhn's Hungarian algorithmfrom 1955.

GIoU: Telling Distance Even Without Overlap

IoU is 0 regardless of how far apart two non-overlapping boxes are. Using it as a loss yields no gradients. GIoU(Generalized IoU) penalizes the "empty space inside C" by utilizing the smallest enclosing box C that bounds both boxes.

GIoU = IoU − |C 에서 두 상자의 합집합을 뺀 넓이| / |C|      (−1 ~ 1)

Manual calculation yields the following (measured):

Ground truth (0,0,10,10) vs. IoU GIoU
(0,0,10,10) identical 1.000 +1.000
(5,0,15,10) half overlap 0.333 +0.333
(12,0,22,10) 2 units apart 0.000 −0.091
(30,0,40,10) 20 units apart 0.000 −0.500

While IoU is 0 for both distant cases, GIoU becomes smaller as the distance increases, creating a gradient that pulls the box toward the ground truth.

4. Hands-On: The Hungarian Algorithm

Why Greedy Search Fails

Here are the costs for three slots in a scene where two players overlap. Slot 0 straddles both players and fits both moderately well, Slot 1 fits player A reasonably well, and Slot 2 fits player B quite well.

          슬롯 0   슬롯 1   슬롯 2
선수 A     0.9      1.0      6.0
선수 B     0.8      6.0      3.0

If we greedily pick "the cheapest remaining slot for each ground truth in turn," A takes Slot 0 (0.9) first, and B receives Slot 2 (3.0), resulting in a total cost of 3.9 . The Hungarian algorithm finds A–Slot 1 and B–Slot 0 for a total cost of 1.8 (measured). The strategy where whoever picks first wins can be detrimental overall. Using greedy matching for training would cause Slot 2 to mistakenly learn player B and Slot 1 to learn "no object."

Implementation and Verification

We implemented an O(n²m) version in numpy using potentials (dual variables) (ground truth n ≤ slots m). The core idea is to "increase matches row by row, but if a cheaper path (augmenting path) exists that alters existing matches, flip the matches along that path."

Check Result (Measured)
Total cost matches full permutation search across 200 random 4×7 problems 200/200
Ground truth 10 × Slots 100 0.2ms
Ground truth 50 × Slots 100 1.4ms
Ground truth 100 × Slots 100 8.1ms
Ground truth 300 × Slots 300 67.6ms

Evaluating all permutations for just 10 ground truths × 100 slots yields 6.3×10¹⁹ possible combinations. Hungarian-family algorithms solve this in polynomial time (roughly n³). A single DETR frame (dozens of ground truths × 100 slots) takes milliseconds, meaning it is not a training bottleneck. In practice, SciPy's linear_sum_assignment(modified Jonker–Volgenant algorithm) is frequently used.

Matching 3 ground truths (two players, ball) and 6 slots using the DETR cost formula (class probability + 5·L1 + 2·(1−GIoU)) assigns each ground truth to the most plausible slot, while the remaining 3 slots are assigned as "no object" (code/08_hungarian.out.txt).

5. Paper Metrics

Model (COCO Val) AP Small Object AP_S Large Object AP_L Parameters GFLOPs FPS
Faster R-CNN-FPN+(R50) 42.0 26.6 53.4 42M 180 26
DETR(R50) 42.0 20.5 61.1 41M 86 28

(Paper Table 1. Faster R-CNN version uses GIoU loss, random crop augmentation, and an enhanced version trained for ~109 epochs. Speed measured with a TorchScript model, GPU not specified.)

6. Follow-Up Research: Mitigating Weaknesses

Model Modifications Metrics (Paper, COCO)
Deformable DETR (2021) Attention looking at only a few sample points (K=4) around reference points instead of global attention. Uses multiple resolutions 43.8 AP in 50 epochs, AP_S 26.4 (DETR: 20.5 in 500 epochs). Training GPU hours: 325 vs. 2,000
DN-DETR (2022) Adding noise to ground truth boxes, feeding them to the decoder, and having it reconstruct the original boxes via denoising training — bypassing unstable matching +1.9 AP under identical settings with half the epochs for similar accuracy
DINO (2023) Enhanced denoising training + improved query initialization ResNet-50: 49.4 AP in 12 epochs, 51.3 AP in 24 epochs. Swin-L + Objects365 pretraining achieves 63.3 AP on test-dev
RT-DETR (2024) Real-time hybrid encoder R50: 53.1 AP, 108 fps (inference datacenter GPU, TensorRT FP16, 640×640). Apache-2.0

DETR's "set prediction + 1:1 matching" became the standard paradigm for subsequent detection. Both YOLOv10's NMS-free method from Part 6 (one-to-one head) and SAM 3's detector from Part 11 (DETR-family) build upon this idea.

7. Limitations and Our Project

Starting from the next post, we cover segmentation: Segment Anything (SAM), which paints anything with a single click.

Titi's Note. Picking the cheapest sequentially yields 3.9, while Hungarian yields 1.8. A strategy where whoever picks first takes everything is detrimental in team sports.

References

Sign in to like

Comments

No comments yet.

Sign in to leave a comment