Deformable DETR: Deformable Transformers for End-to-End Object Detection
- 发表版本
- ICLR 2021会议
- arXiv 首次提交
- arXiv:2010.04159
引用此论文 · BibTeX
引用信息对应所链接的论文版本,作者为原论文作者。
@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 留给研究者们一个很好发挥的空间。
它只用了最基本的 Transformer 架构,做最朴素的目标检测。里面也没有用到什么提升分数的技巧,只是单纯的把图片丢进去,然后就可以得到目标的位置和类别。
多么美好的论文!
往后的研究者们只要基于这个思路改进模型,论文还不是刷刷刷一大把?
定义问题
和常见的目标检测器相比,DETR 的某些配置实在太慢了。
如果按论文表 1 比较 DETR-DC5 与 Faster R-CNN + FPN,推理速度约慢两倍:12 FPS 对 26 FPS!
那又怎样?感觉好像也不是什么大问题?
没错,更大的问题是训练收敛速度:同一组对照的训练耗时为 7000 对 380 GPU 小时,接近 20 倍!
按相同计算资源粗略换算,原本只需 1 天的训练,现在可能接近 20 天,这是多么可怕的事情?
韶光易逝,年华易老。等模型收敛,等到头发都白了。
这不行,肯定要改。
解决问题
作者认为问题出在 Transformer 的注意力机制上。
DETR 编码器在卷积特征图的所有空间位置之间计算注意力,特征图分辨率提高时,计算与内存成本会快速增加;初始注意力接近均匀,也需要较长训练才会聚焦。
所以这里不能再使用原本的 Transformer 注意力机制,而是借鉴了「可变形卷积」的思路,将原本的注意力机制改成一种「可变形的注意力机制」。
可变形注意力
在图像特征图中,给定每个查询元素(Query Element),作者以参考点为基准,从查询特征预测少量采样偏移与权重,再对采样点的特征做加权求和;偏移量没有固定的局部范围限制。
假设输入的特征图为:
其中 表示通道数, 和 分别是特征图的高度和宽度。
查询元素 包含一个内容特征 和一个 2D 参考点 ,可变形注意力特征的计算公式如下:
其中:
- 表示注意力头的数量。
- 表示每个注意力头对每个查询所采样的点数,远少于整张特征图的位置数。
- 是第 个注意力头中第 个采样点的注意力权重,范围在 之间;同一头的 个权重总和为 1。
- 是第 个注意力头中第 个采样点的偏移量,这些偏移量可以是任意的实数。
- 和 是可学习的权重矩阵,负责将输入特征进行线性变换。
- 表示在位置 处的特征值,因为该位置是分数值(即非整数点),因此使用双线性插值来计算。
查询特征 经过一个线性投影操作,该操作会输出一个 通道的张量:
- 前 个通道用来编码每个采样点的偏移量 。
- 剩余的 个通道会经过 softmax 操作,计算出对应的注意力权重 。
这种设计方式,可以保证「偏移量」与「注意力权重」都是从查询元素的特征中学习得到的,而不是基于固定的规则。
多尺度计算
现代目标检测框架通常会使用多尺度特征图来进行目标检测。
可变形注意力模块当然也得支持多尺度版本,允许同时在多个特征图层上进行采样和操作。
假设输入的多尺度特征图为 ,每个特征图 。
查询元素的参考点用归一化坐标 表示,则多尺度的计算公式为:
- 表示输入的特征图层数量。
- 是一个缩放函数,用来将归一化坐标转换到第 层特征图上的实际坐标。
- 其他符号的意义与单尺度的情况类似;此时每个注意力头的权重在所有 个采样点上一起归一化。
模型架构
如上图,编码器中处理多尺度特征图的自注意力、以及解码器读取特征图的交叉注意力改用可变形注意力;解码器内目标查询彼此互动的自注意力仍保留。编码器输入使用 ResNet 的 C3–C5 特征与从 C5 下采样得到的 C6,不经 FPN 的自上而下融合。
程式码拆解
我们单独把作者的实作拿出来看一下,到底 MSDeformAttn 和一般的 Attn 有什么差异:
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
从架构上来看,这个模块支持多层特征(不同分辨率)。论文使用 ResNet 的 C3–C6,经投影后展平为 input_flatten,再用 input_spatial_shapes 和 input_level_start_index 标记各层大小与起点;这些特征不是 FPN 融合后的输出。
-
每个 Query 自行学习偏移量
self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)这行的意思是,对于每一个 Query,模型会输出多个 offset (dx, dy),表示从 reference point 偏移的方向与距离,也就是「往哪看」。这些偏移点是学出来的,而非预先定义的固定格点。
-
Reference Points 决定「基准位置」
if reference_points.shape[-1] == 2: ... elif reference_points.shape[-1] == 4: ...注意力不再让 Query 对整张特征图逐点计算,而是以指定的
reference_points为基准,在学得的偏移点取样并加权;偏移不限定在固定视窗内。Encoder 以各特征位置自身为参考点,Decoder 的参考点则由目标查询预测。
关键差异是采样位置与权重都由 Query 决定;上方程式也在多尺度间共同归一化权重。Decoder 的查询间自注意力仍使用原本的形式。
训练策略
作者在 COCO 2017 数据集上进行实验。
首先 Backbone 使用 ResNet-50,并且在 ImageNet 上进行预训练。Neck 的部分直接从多尺度特征图中提取特征,并且没有使用 FPN。
可变形注意力设定:
- 注意力头的数量:M = 8
- 每个查询在每个注意力头、每个特征层的采样点数量:K = 4
可变形变换器编码器中的参数在不同的特征层之间共享。
超参数和训练策略主要遵循 DETR 的设置,除了以下几点:
- 边界框分类采用 Focal Loss,损失权重设为 2。
- 将目标查询数量从 100 增加至 300。
模型预设训练 50 个 epoch,第 40 个 epoch 时学习率会降低为原来的 0.1 倍。使用 Adam 优化器来进行训练,基本学习率为 ,且 ,,权重衰减为 。
预测目标查询参考点与采样偏移量的线性投影的学习率会额外乘以 0.1 的缩放因子。
讨论
与 DETR 的比较
根据上表,Faster R-CNN + FPN 在 109 epoch/380 GPU 小时时为 42.0 AP、26.6 AP_S;DETR 在 500 epoch/2000 GPU 小时时同为 42.0 AP,但 AP_S 为 20.5。Deformable DETR 用 50 epoch/325 GPU 小时达 43.8 AP、26.4 AP_S;「少 10 倍」指相对 DETR 的训练 epoch,不能直接当成 GPU 时数的倍率。
详细的收敛曲线见下图:
表中同样训练 50 epoch 的迭代框修正使 AP 从 43.8 升至 45.4;再加两阶段机制升至 46.2。上图的不同收敛曲线也包含改变学习率下降时点的实验,并非全是同一个 50-epoch 设定。
在论文的 Tesla V100 测试下,Deformable DETR 为 173G FLOPs/19 FPS,与 Faster R-CNN + FPN 的 180G/26 FPS、DETR-DC5 的 187G/12 FPS 计算量接近;其 FPS 约为 DETR-DC5 的 1.6 倍,比 Faster R-CNN + FPN 低约 27%。
DETR-DC5 速度较慢的原因主要在于 Transformer 注意力机制中大量的内存存取,而 Deformable Attention 可以缓解此问题,但代价是无序的内存存取,仍稍慢于传统卷积。
消融实验
上表展示了变形注意力模块中不同设计选项的消融研究。
在未使用跨尺度注意力且 的对照下,加入多尺度输入使 AP 从 39.7 升至 41.4、AP_S 从 21.2 升至 24.1(各高 1.7/2.9 个百分点);再将 增至 4,AP 由 41.4 升至 42.3(高 0.9 个百分点)。
在多尺度输入、 下加入跨尺度注意力,AP 从 42.3 升至 43.8(高 1.5 个百分点)。同样配置再加 FPN 仍为 43.8 AP;BiFPN 为 43.9 AP,增益很小。当未使用跨尺度注意力且 时,模块接近可变形卷积的单点取样形式,表列 AP 为 41.4,低于完整多尺度注意力的 43.8。
SOTA 比较
在上表中,Deformable DETR 均使用了迭代边界框优化与两阶段机制。
在已使用迭代框修正与两阶段机制、不使用 TTA 的设定下,ResNet-101 和 ResNeXt-101 分别达到 48.7/49.0 AP;带 DCN 的 ResNeXt-101 达 50.1 AP。不同骨干与 TTA 条件不能视为单独的注意力模块增益。
在加入测试时增强(test-time augmentations)后,该方法达到 52.3 AP。
结论
Deformable DETR 相较于传统的 DETR,大幅缩短了训练所需的时间。在小物体检测的表现上,比 DETR 展现更明显的优势。
虽然 Deformable DETR 引入了可变形注意力以提升运行速度,但由于无序内存存取的特性,仍略微慢于传统的卷积神经网络架构(如 Faster R-CNN)。因此,对于某些即时性要求高的应用,速度仍是需要考量的问题。
Deformable DETR 的设计为探索更高效、更实用的端对端物体检测器变体开辟了新的方向,并具有广泛的研究与应用潜力。