Sub topic 17
Deformable DETR and Other Fixes for DETR's Weaknesses
This chapter assumes you know how DETR works: a CNN backbone, a transformer encoder and decoder, a fixed set of object queries, and Hungarian matching during training. You should also know self-attention and cross-attention. Here you will see why the original DETR trains slowly and misses small objects, and how Deformable DETR and its successors fix both problems.
The two weaknesses
The original DETR matched Faster R-CNN on COCO, but it needed about 500 training epochs. Faster R-CNN baselines needed far fewer. DETR was also clearly worse on small objects. Both problems have identifiable causes.
Slow convergence.
- At initialization, attention is almost uniform. Every query looks at every pixel with roughly equal weight, so it takes a long time to learn to focus on a small region.
- Hungarian matching can change between epochs. A query may be matched to one object in one epoch and a different object in the next, so the learning signal is noisy.
- Object queries are learned embeddings with no explicit spatial meaning, so the decoder must discover where each query should look.
Poor small-object accuracy.
- DETR uses only the last backbone feature map, at stride 32. A 16×16 pixel object covers a quarter of one cell.
- Detectors with feature pyramids avoid this by using stride-8 or stride-4 maps. DETR does not use them.
- Self-attention cost grows with the square of the number of tokens, so using a high-resolution map directly is too expensive.
A feature map that is too coarse hurts small objects, but a finer map costs too much. The fixes below attack this tension and the slow focus problem.
Deformable attention
Deformable DETR replaces dense attention with deformable attention. Each query attends to only a few sampled points around a reference point instead of every pixel.
For one query, one attention head, and one feature level:
- The query has a reference point, a 2D location in the image.
- A linear layer on the query predicts K sampling offsets. Each offset is an (x, y) shift from the reference point.
- Another linear layer predicts K attention logits. A softmax over them gives the weights.
- The feature map is sampled at each shifted location with bilinear interpolation, and the sampled values are summed using the weights.
Key properties:
- The weights come from the query alone, with no query-key dot product. The keys are never compared against.
- Cost grows linearly with the number of query positions, because each query touches only K points. In the paper, K is small (4 per level).
- The model learns where to look. The offsets are learned, so attention can reach well beyond a fixed local window.
The following NumPy code implements one head on one level. The feature map holds x + 10*y, which is linear, so bilinear sampling returns exact values and you can check the result by hand.
import numpy as np
def bilinear(feat, x, y):
"""Sample feat (H, W, C) at pixel coordinates (x, y). Zero outside."""
H, W, C = feat.shape
x0, y0 = int(np.floor(x)), int(np.floor(y))
out = np.zeros(C)
for dy in (0, 1):
for dx in (0, 1):
xi, yi = x0 + dx, y0 + dy
if 0 <= xi < W and 0 <= yi < H:
w = (1 - abs(x - xi)) * (1 - abs(y - yi))
out += w * feat[yi, xi]
return out
def deformable_attention(feat, ref, offsets, logits):
"""One head, one level. ref=(x, y); offsets: K (dx, dy); logits: K scores."""
logits = np.asarray(logits, dtype=float)
weights = np.exp(logits - logits.max())
weights /= weights.sum()
out = np.zeros(feat.shape[2])
for (dx, dy), w in zip(offsets, weights):
out += w * bilinear(feat, ref[0] + dx, ref[1] + dy)
return out
ys, xs = np.mgrid[0:4, 0:4]
feat = (xs + 10 * ys).astype(float)[..., None] # shape (4, 4, 1)
result = deformable_attention(feat, (1.0, 1.0), [(0.5, 0.5), (-1.0, 0.0)], [0.0, 0.0])
print(float(result[0])) # 13.25 = 0.5 * 16.5 + 0.5 * 10.0In a real model the offsets and logits are outputs of linear layers, and the operation runs for every head, every level, and every query, usually in a fused CUDA kernel.
Multi-scale without the quadratic cost
Because deformable attention is sparse, Deformable DETR can afford feature maps from several backbone stages (strides 8, 16, 32, plus an extra downsampled level). Each query samples K points on every level, so the attention is multi-scale with no separate pyramid network.
The saving is large. A single stride-8 map for an 800×1066 image has about 100×134 = 13,400 tokens. Dense self-attention on that map would need 13,400² ≈ 180 million query-key pairs per head. Deformable attention needs 13,400 queries times 4 levels times K sampled points, which is tens of times fewer operations for K = 4.
The paper reports comparable or better accuracy than DETR with about 10 times fewer training epochs, and clearly better small-object AP.
Other changes in Deformable DETR
- Reference points. In the decoder, each object query predicts a reference point. The decoder then samples around that point, so queries gain a spatial meaning.
- Iterative box refinement. Each decoder layer predicts a box offset relative to the previous layer's box, and the next layer uses the refined box.
- Two-stage variant. The encoder proposes boxes from its output features. The top proposals then initialize the decoder's queries and reference points, instead of learned fixed queries.
Later fixes for convergence and queries
| Method | Main idea | What it fixes |
|---|---|---|
| Conditional DETR | Separates the spatial part of a query from its content part | Cross-attention focuses on object extremities faster |
| Anchor DETR | Queries are tied to anchor points | Queries have clear location |
| DAB-DETR | Each query is a 4D box (x, y, w, h) updated layer by layer | Box-shaped positional prior, width and height modulate attention |
| DN-DETR | Trains with noised ground-truth boxes that the decoder must denoise | Stabilizes matching, speeds up training |
| DINO | Contrastive denoising, mixed query selection, look-forward-twice box updates | Faster training and state-of-the-art accuracy |
| RT-DETR | Hybrid encoder that handles multi-scale features efficiently | Real-time speed without NMS |
Denoising training deserves a closer look. During training, extra queries are built from ground-truth boxes with random noise added. These queries bypass Hungarian matching: each is already assigned to its source object, and the decoder learns to reconstruct the clean box and label. This gives a stable, fixed learning signal alongside the changing matched queries. These denoising queries are used only in training and are removed at inference.
Common errors and gotchas
- Assuming DETR-style detectors never need NMS. One-to-one matching removes the need in the base designs. Some later variants add one-to-many training branches, and then NMS may be needed at inference for those branches. Check which head you actually deploy.
- Confusing the reference point with the box. A reference point is a location for sampling. A box also has width and height. Some variants (DAB-DETR, DINO) treat queries as full boxes.
- Expecting deformable attention to run well anywhere. It depends on a custom sampling operator. Export to inference runtimes can be harder than for standard attention, and naive pure-PyTorch implementations are slower than the fused kernel.
- Reading the speedup as only a cheaper attention. Faster convergence comes from several changes together: sparse attention, reference points, and in later models denoising and better query initialization.
- Forgetting that denoising queries need an attention mask. Matched queries must not see the noised ground-truth queries, or the model could copy the answer.
Summary of the design shift
Original DETR made the pipeline simple (no anchors, no NMS) but paid for it with dense attention and unguided queries. The fixes restore some of what anchor-based detectors had: multi-scale features, spatial priors for queries, and a stable training signal. They do this without bringing back hand-designed anchor sets or NMS in the core design.
Exercise
A decoder query in a deformable attention layer uses 8 heads, 4 feature levels, and 4 sampling points per level per head. How many sampling offsets does the query predict, and how many attention weights does a single head's softmax cover?
Show answer
Each head predicts 4 levels × 4 points = 16 offsets, so the query predicts 8 × 16 = 128 offsets (each an (x, y) pair, so 256 numbers). Each head's softmax covers its 16 sampled points, because the weights are normalized across all levels and points of that head.
Exercise
Explain why denoising queries speed up DETR training, and why they must be hidden from the matched queries with an attention mask.
Show answer
Hungarian matching can assign a different query to an object from one epoch to the next, which makes the learning signal unstable. Denoising queries are built from noised ground-truth boxes with a fixed assignment, so the decoder gets a consistent target to learn from. They must be masked from the matched queries, because otherwise the matched queries could read the noised copies of the answers and learn to cheat instead of detecting objects from the image.