Sub topic 16
DETR: object queries and set prediction
DETR (DEtection TRansformer, Carion et al., 2020) treats detection as predicting a set of objects directly. Earlier chapters covered anchors, label assignment by IoU, and non-maximum suppression (NMS). DETR removes all three and replaces them with a Transformer and one-to-one matching.
This chapter assumes you know how a CNN backbone produces feature maps, what self-attention and cross-attention do, and how the Hungarian algorithm assigns predictions to targets. It also assumes you are comfortable with classification and box-regression losses.
The idea: a fixed-size set of predictions
A conventional detector emits thousands of candidate boxes. Many of them overlap the same object, so a hand-written filter (NMS) is needed to remove duplicates. DETR emits exactly N predictions for every image. N is a fixed hyperparameter, 100 in the original paper. Each prediction is either an object (a class and a box) or the special "no object" class, written ∅.
Because N is larger than the number of objects in any image, most predictions should be ∅. The model must also learn to make its predictions different from one another. This is done by training with a one-to-one assignment between predictions and ground-truth objects, so duplicates are penalized by the loss instead of being filtered afterwards.
Architecture
The pipeline has four parts.
- Backbone. A CNN such as ResNet-50 turns the image into a feature map. It has stride 32 and 2048 channels, and a 1x1 convolution reduces the channels to the Transformer width (256).
- Encoder. The feature map is flattened into a sequence of H·W tokens. Fixed 2D sine positional encodings are added, and a stack of 6 self-attention layers lets every location exchange information with every other location.
- Decoder. The decoder takes N learned vectors called object queries. Each decoder layer applies self-attention among the queries, then cross-attention from the queries to the encoder output, then a feed-forward network. The self-attention among queries lets them coordinate, so two queries do not claim the same object.
- Prediction heads. A shared feed-forward network maps each decoder output to a class distribution over C+1 classes and a box
(cx, cy, w, h), normalized to [0, 1] relative to the image size.
What object queries are
An object query is a learned embedding, a parameter vector the model optimizes like any weight. It is the same for every image. A query has no built-in meaning, but after training each one tends to specialize. Some queries favor particular box sizes or image regions. Cross-attention then uses the query to pull the relevant evidence out of the encoder features.
Anchors are fixed reference boxes defined by hand. Queries are learned and their meaning depends on the image through attention.
Training: bipartite matching
To compute a loss, you must decide which prediction is responsible for which ground-truth object. DETR does this with the Hungarian algorithm, which finds the one-to-one assignment with the lowest total cost.
Pad the ground-truth set with ∅ entries until it has N elements. The matching cost between prediction i and ground-truth object j (a real object) combines three terms:
- the negative predicted probability of the true class,
-p_i(c_j); - the L1 distance between the predicted and true boxes;
- the negative generalized IoU (GIoU) between the boxes.
The paper weights these terms, for example 1 for class, 5 for L1, and 2 for GIoU.
Matching differs from the anchor assignment you saw earlier. IoU thresholds there can give many positives per object. Here each object gets exactly one prediction.
import numpy as np
from scipy.optimize import linear_sum_assignment
# 3 predictions, 2 real classes (0 and 1) plus a no-object class at index 2.
probs = np.array([
[0.7, 0.1, 0.2],
[0.1, 0.8, 0.1],
[0.1, 0.1, 0.8],
])
pred_boxes = np.array([
[0.3, 0.3, 0.2, 0.2],
[0.7, 0.7, 0.3, 0.3],
[0.5, 0.5, 0.9, 0.9],
])
gt_labels = np.array([0, 1])
gt_boxes = np.array([
[0.3, 0.3, 0.2, 0.2],
[0.7, 0.7, 0.3, 0.3],
])
cost_class = -probs[:, gt_labels] # (3, 2)
cost_l1 = np.abs(pred_boxes[:, None, :] - gt_boxes[None, :, :]).sum(-1) # (3, 2)
cost = 1.0 * cost_class + 5.0 * cost_l1 # GIoU term omitted for brevity
rows, cols = linear_sum_assignment(cost)
print(list(zip(rows.tolist(), cols.tolist()))) # [(0, 0), (1, 1)]
# Matched predictions get their object's class. All others get no-object.
target_classes = np.full(len(probs), 2)
target_classes[rows] = gt_labels[cols]
print(target_classes.tolist()) # [0, 1, 2]Prediction 2 is unmatched, so its class target is no-object. Its box is not penalized.
The loss
After matching, the loss is computed on the matched pairs:
- Classification: cross-entropy over all N predictions, with unmatched ones labeled ∅. Since ∅ dominates, its weight is reduced by a factor of 10 to balance the classes. This is a simpler answer to the imbalance problem that focal loss addressed in anchor-based detectors.
- Box: a weighted sum of L1 loss and GIoU loss on matched pairs only. L1 alone is scale-dependent, because large boxes produce larger errors. GIoU adds a scale-invariant term.
The decoder applies the same prediction heads after every layer, and the loss is applied to each layer's output (auxiliary decoding losses). This helps the model converge and learn the right number of objects per class.
Inference
Run the network, take each query's most likely class, and discard queries whose top class is ∅ or whose score is below a threshold. The remaining boxes are the detections. NMS is not required, because training with one-to-one matching pushes duplicate queries toward ∅.
Comparison with anchor-based detectors
| Aspect | Anchor-based (e.g. RetinaNet) | DETR |
|---|---|---|
| Prior boxes | Hand-designed anchors | Learned object queries |
| Training assignment | IoU thresholds, many positives per object | Hungarian matching, one positive per object |
| Duplicate handling | NMS at inference | Learned, no NMS |
| Class imbalance | Focal loss | Down-weighted no-object class |
| Context | Local convolutions, limited receptive field | Global attention |
| Hyperparameters | Anchor scales, ratios, IoU and NMS thresholds | Number of queries, matching weights |
Common errors and gotchas
- Slow convergence. The original DETR needs about 500 epochs on COCO, against roughly 12 to 36 for Faster R-CNN. Cross-attention starts out nearly uniform and takes a long time to learn to focus on single objects.
- Weak on small objects. The stride-32 feature map is coarse, and full attention over a higher-resolution map is too expensive. Quadratic attention cost is the main constraint.
- Unstable matching early in training. Initially, matching changes from step to step, so the targets for a query keep shifting. Later DETR variants address this directly.
- Too few queries. If N is smaller than the number of objects in an image, objects are missed. Choose N comfortably above the maximum count in your data.
- Box format mistakes. DETR predicts normalized
(cx, cy, w, h). Convert to(x1, y1, x2, y2)and scale to pixels before computing IoU or drawing. - Forgetting the ∅ weight. Leaving no-object weighted equally with real classes causes the model to predict ∅ nearly everywhere.
The next chapter covers the variants (Deformable DETR and others) that fix the slow training and small-object problems.
Exercise
An image contains 3 objects and DETR uses N = 100 queries. After Hungarian matching, how many predictions receive a box loss, and what class target do the others receive? Why is NMS not needed at inference?
Show answer
Exactly 3 predictions receive a box loss, one for each ground-truth object, because the matching is one-to-one. The other 97 receive the no-object class as their classification target and no box loss. NMS is not needed because training penalizes duplicates. If two queries predict the same object, only one can be matched. The other is trained to output no-object, so after thresholding only one box per object remains.
Exercise
A matching cost matrix has 4 predictions (rows) and 2 ground-truth objects (columns). How many predictions does linear_sum_assignment return pairs for, and what happens to the rest?
Show answer
It returns 2 pairs, one per ground-truth object, because it assigns each column to a distinct row when there are more rows than columns. The 2 unmatched predictions are given the no-object class target in the loss.