Deformable DETR: Deformable Transformers for End-to-End Object Detection
- Publication
- ICLR 2021Conference
- First submitted to arXiv
- arXiv:2010.04159
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{objectdetectiondeformabledetr2020,
title = {{Deformable DETR: Deformable Transformers for End-to-End Object Detection}},
author = {Xizhou Zhu and Weijie Su and Lewei Lu and Bin Li and Xiaogang Wang and Jifeng Dai},
year = {2020},
eprint = {2010.04159},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2010.04159}
}
DETR leaves a lot of room for researchers to innovate.
It uses only the most basic Transformer architecture to perform the simplest object detection. There are no score-boosting tricks inside; it simply takes the image as input and outputs the object locations and classes.
What a beautiful paper!
Subsequent researchers can improve the model based on this idea, and papers will keep coming out rapidly.
Problem Definition
Compared with other detectors, DETR feels painfully slow to train. What about inference? That depends on the variant: the paper's ordinary DETR runs at 28 FPS against Faster R-CNN + FPN's 26 FPS, while the high-resolution DETR-DC5 runs at 12 FPS.
So is inference really the problem? Not here. The troubling part is convergence: DETR takes 500 epochs in the paper's COCO comparison, versus 109 for Faster R-CNN + FPN and 50 for Deformable DETR. The often-quoted “10–20 times” refers to training schedules in epochs, not a guaranteed multiplication of elapsed days; Table 1 reports 2,000 versus 380 GPU hours for DETR and Faster R-CNN + FPN.
Time flies; youth fades. We cannot wait until our hair turns white for a model to converge. This has to change.
Problem Solution
The authors believe the problem lies in the Transformer’s attention mechanism.
In DETR’s encoder, global attention links every feature-map position to all other positions. Its attention cost grows quadratically with their count, making high-resolution features expensive; training must also learn to focus from initially diffuse weights.
So the original Transformer attention over dense image features is too costly here. Inspired by “deformable convolution,” the authors modify it into a “deformable attention mechanism.”
Deformable Attention
In the image feature map, given each query element, the authors use a reference point as a base, predict a few sampling offsets and weights from the query feature, then aggregate the sampled features. The offsets need not stay within a fixed local window.
Assuming the input feature map is:
where is the number of channels, and , are the height and width of the feature map, respectively.
The query element contains a content feature and a 2D reference point . The deformable attention feature is computed as follows:
where:
- is the number of attention heads.
- is the number of samples per query and per attention head. Learned offsets from the reference point determine their positions; they are not confined to a fixed small window.
- is the attention weight for the -th sampling point of the -th attention head, ranging in . For fixed , these weights sum to 1.
- is the offset of the -th sampling point of the -th head; these offsets can be arbitrary real numbers.
- and are learnable weight matrices responsible for linear transformations of the input features.
- denotes the feature value at location . Since this position is fractional (non-integer), bilinear interpolation is used to compute it.
The query feature undergoes a linear projection outputting a tensor with channels:
- The first channels encode the offsets of each sampling point.
- The remaining channels pass through a softmax to produce the attention weights .
This design ensures that both the offsets and attention weights are learned from the query element’s features rather than being fixed by a predetermined rule.
Multi-Scale Computation
Modern object detection frameworks usually use multi-scale feature maps for detection.
The deformable attention module naturally supports a multi-scale version, allowing sampling and operations on multiple feature map layers simultaneously.
Assuming the multi-scale feature maps as , where each feature map .
The query element’s reference point is represented by normalized coordinates . The multi-scale computation formula is:
- is the number of input feature map levels.
- is a scaling function that converts normalized coordinates to actual coordinates on the -th feature map layer.
- Each query samples points per head per level. Within a head, softmax normalizes jointly over all samples, so their weights sum to 1.
Model Architecture
The replacement affects encoder self-attention over image features and decoder cross-attention reading those features. Decoder self-attention among object queries remains standard; not every Transformer module is replaced. The encoder receives ResNet C3–C5 features plus a downsampled C6 from C5, without FPN's top-down fusion.
Code Breakdown
Let's take a closer look at the authors' MSDeformAttn implementation. What differs from ordinary attention? This excerpt is for reading: imports, helpers and the custom CUDA operator are omitted, so it is not a standalone script. See the official repository above for the complete environment.
class MSDeformAttn(nn.Module):
def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4):
"""
Multi-Scale Deformable Attention Module
:param d_model hidden dimension
:param n_levels number of feature levels
:param n_heads number of attention heads
:param n_points number of sampling points per attention head per feature level
"""
super().__init__()
if d_model % n_heads != 0:
raise ValueError('d_model must be divisible by n_heads, but got {} and {}'.format(d_model, n_heads))
_d_per_head = d_model // n_heads
# you'd better set _d_per_head to a power of 2 which is more efficient in our CUDA implementation
if not _is_power_of_2(_d_per_head):
warnings.warn("You'd better set d_model in MSDeformAttn to make the dimension of each attention head a power of 2 "
"which is more efficient in our CUDA implementation.")
self.im2col_step = 64
self.d_model = d_model
self.n_levels = n_levels
self.n_heads = n_heads
self.n_points = n_points
self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)
self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points)
self.value_proj = nn.Linear(d_model, d_model)
self.output_proj = nn.Linear(d_model, d_model)
self._reset_parameters()
def _reset_parameters(self):
constant_(self.sampling_offsets.weight.data, 0.)
thetas = torch.arange(self.n_heads, dtype=torch.float32) * (2.0 * math.pi / self.n_heads)
grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
grid_init = (grid_init / grid_init.abs().max(-1, keepdim=True)[0]).view(self.n_heads, 1, 1, 2).repeat(1, self.n_levels, self.n_points, 1)
for i in range(self.n_points):
grid_init[:, :, i, :] *= i + 1
with torch.no_grad():
self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))
constant_(self.attention_weights.weight.data, 0.)
constant_(self.attention_weights.bias.data, 0.)
xavier_uniform_(self.value_proj.weight.data)
constant_(self.value_proj.bias.data, 0.)
xavier_uniform_(self.output_proj.weight.data)
constant_(self.output_proj.bias.data, 0.)
def forward(self, query, reference_points, input_flatten, input_spatial_shapes, input_level_start_index, input_padding_mask=None):
"""
:param query (N, Length_{query}, C)
:param reference_points (N, Length_{query}, n_levels, 2), range in [0, 1], top-left (0,0), bottom-right (1, 1), including padding area
or (N, Length_{query}, n_levels, 4), add additional (w, h) to form reference boxes
:param input_flatten (N, \sum_{l=0}^{L-1} H_l \cdot W_l, C)
:param input_spatial_shapes (n_levels, 2), [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
:param input_level_start_index (n_levels, ), [0, H_0*W_0, H_0*W_0+H_1*W_1, H_0*W_0+H_1*W_1+H_2*W_2, ..., H_0*W_0+H_1*W_1+...+H_{L-1}*W_{L-1}]
:param input_padding_mask (N, \sum_{l=0}^{L-1} H_l \cdot W_l), True for padding elements, False for non-padding elements
:return output (N, Length_{query}, C)
"""
N, Len_q, _ = query.shape
N, Len_in, _ = input_flatten.shape
assert (input_spatial_shapes[:, 0] * input_spatial_shapes[:, 1]).sum() == Len_in
value = self.value_proj(input_flatten)
if input_padding_mask is not None:
value = value.masked_fill(input_padding_mask[..., None], float(0))
value = value.view(N, Len_in, self.n_heads, self.d_model // self.n_heads)
sampling_offsets = self.sampling_offsets(query).view(N, Len_q, self.n_heads, self.n_levels, self.n_points, 2)
attention_weights = self.attention_weights(query).view(N, Len_q, self.n_heads, self.n_levels * self.n_points)
attention_weights = F.softmax(attention_weights, -1).view(N, Len_q, self.n_heads, self.n_levels, self.n_points)
# N, Len_q, n_heads, n_levels, n_points, 2
if reference_points.shape[-1] == 2:
offset_normalizer = torch.stack([input_spatial_shapes[..., 1], input_spatial_shapes[..., 0]], -1)
sampling_locations = reference_points[:, :, None, :, None, :] \
+ sampling_offsets / offset_normalizer[None, None, None, :, None, :]
elif reference_points.shape[-1] == 4:
sampling_locations = reference_points[:, :, None, :, None, :2] \
+ sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
else:
raise ValueError(
'Last dim of reference_points must be 2 or 4, but get {} instead.'.format(reference_points.shape[-1]))
output = MSDeformAttnFunction.apply(
value, input_spatial_shapes, input_level_start_index, sampling_locations, attention_weights, self.im2col_step)
output = self.output_proj(output)
return output
This interface flattens and concatenates projected ResNet C3–C6 features into input_flatten, using input_spatial_shapes and input_level_start_index to identify levels. These are not FPN-fused outputs. Standard attention can also receive multi-scale tokens, but its cost differs from sparse sampling.
-
Each Query Learns Its Own Offsets
self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)This means for each query, the model outputs multiple offsets (dx, dy), representing directions and distances offset from the reference point — essentially "where to look." These sampling offsets are learned rather than fixed predefined grids.
-
Reference Points Determine the “Base Location”
if reference_points.shape[-1] == 2: ... elif reference_points.shape[-1] == 4: ...Attention no longer compares each query with every feature-map position. It samples at learned offsets from the
reference_points, without a fixed window. Encoder reference points correspond to feature-map positions; decoder reference points are predicted from object queries.
That's roughly it. One more essential difference: the sampling positions and weights both come from the query, without computing every query-key dot product. The softmax spans all levels and sampling points within each head; decoder query self-attention still uses the standard form.
Training Strategy
The authors conducted experiments on the COCO 2017 dataset.
The backbone is ResNet-50, pretrained on ImageNet. Its C3–C5 features and a downsampled C6 feed the encoder without FPN's top-down fusion.
Deformable Attention settings:
- Number of attention heads: M = 8
- Samples per query, per head and per feature level: K = 4
Parameters in the deformable transformer encoder are shared across different feature levels.
Hyperparameters and training strategy mostly follow DETR’s setup, with these exceptions:
- Bounding box classification uses Focal Loss with a loss weight of 2.
- Number of object queries increased from 100 to 300.
The model is trained for 50 epochs by default; at epoch 40, the learning rate is reduced to 0.1 times the original. The official implementation defaults to AdamW with a base learning rate of , , , and weight decay of .
The linear projections predicting object query reference points and sampling offsets have their learning rates scaled by an additional factor of 0.1.
Discussion
Comparison with DETR
Table 1 makes the comparison concrete. Faster R-CNN + FPN reaches 42.0 AP and 26.6 AP_S after 109 epochs / 380 GPU hours. DETR reaches the same 42.0 AP only after 500 epochs / 2,000 GPU hours, with 20.5 AP_S. Deformable DETR reaches 43.8 AP and 26.4 AP_S after 50 epochs / 325 GPU hours. The “10 times fewer” comparison is about epochs versus DETR, not GPU hours.
Detailed convergence curves are shown below:
At the same 50-epoch schedule in Table 1, iterative bounding box refinement raises AP from 43.8 to 45.4; adding the two-stage mechanism raises it to 46.2. The different curves above also vary the learning-rate drop epoch, so they are not all the same 50-epoch run.
On the paper's Tesla V100, Deformable DETR uses 173G FLOPs and runs at 19 FPS, compared with Faster R-CNN + FPN's 180G / 26 FPS and DETR-DC5's 187G / 12 FPS. Its throughput is about 1.6 times DETR-DC5's and about 27% below Faster R-CNN + FPN's under those conditions.
The slower speed of DETR-DC5 mainly stems from extensive memory access in the Transformer attention mechanism. Deformable Attention mitigates this issue at the cost of irregular memory access, still slightly slower than traditional convolutions.
Ablation Studies
The table shows ablation studies of different design choices within the deformable attention module.
Without cross-scale attention and at , adding multi-scale input raises AP 39.7→41.4 and 21.2→24.1, gains of 1.7 and 2.9 percentage points. Raising from 1 to 4 then raises AP 41.4→42.3, another 0.9 point.
With multi-scale input and , adding cross-scale attention raises AP 42.3→43.8, a 1.5-point gain. Adding FPN to that configuration leaves AP at 43.8; BiFPN reaches 43.9, a small gain. With no cross-scale attention and , the module approaches deformable convolution's single-sample form and reports 41.4 AP, below the complete multi-scale attention's 43.8.
SOTA Comparison
In the table above, Deformable DETR uses iterative bounding box refinement and a two-stage mechanism.
With iterative refinement and two-stage detection already included, the ResNet-101 and ResNeXt-101 rows reach 48.7 and 49.0 AP without TTA. ResNeXt-101 with DCN reaches 50.1 AP. These backbone differences are not an isolated attention-module effect.
With test-time augmentations (TTA), the ResNeXt-101 + DCN configuration reaches 52.3 AP.
Conclusion
Compared to the original DETR, Deformable DETR significantly shortens required training time. It shows more evident advantages in small object detection.
Although deformable attention speeds up computation, its irregular memory access still leaves throughput slightly below Faster R-CNN + FPN in the paper’s comparison. Thus, speed remains a consideration for real-time applications.
Deformable DETR’s design opens new directions for exploring more efficient and practical end-to-end object detector variants, with broad research and application potential.