Back to paper library
Paper notesarXiv 2017ICCV 2017

Deformable ConvNets

Fancy Footwork

Original paper

Deformable Convolutional Networks

Paper authors

Jifeng Dai · Haozhi Qi · Yuwen Xiong …

Show all 7 authors

Jifeng Dai · Haozhi Qi · Yuwen Xiong · Yi Li · Guodong Zhang · Han Hu · Yichen Wei

Publication
ICCV 2017Conference
First submitted to arXiv
arXiv:1703.06211
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{classiccnnsdeformableconvnets2017,
  title = {{Deformable Convolutional Networks}},
  author = {Jifeng Dai and Haozhi Qi and Yuwen Xiong and Yi Li and Guodong Zhang and Han Hu and Yichen Wei},
  year = {2017},
  eprint = {1703.06211},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1703.06211}
}
On this page

In the same photo, a nearby dog looks big and a faraway dog looks small; the same cat can be sitting, lying down, or stretching. Besides the categories themselves, a recognition model has to cope with geometric variations like these.

Convolutional networks handle this mainly through data. During training, images are flipped, scaled, and cropped so the network sees enough variations, and a large enough model memorizes them. The network's own structure, though, is fixed. A 3×33\times3 convolution always samples on a square grid, pooling always downsizes by a fixed ratio, and RoI pooling always cuts a proposal into fixed bins.

In March 2017, Jifeng Dai and colleagues at Microsoft Research Asia released this paper. They wanted the sampling locations of convolution to move on their own.

Defining the Problem

The Fixed Grid

The authors note that there are traditionally two ways to handle geometric variation. One is data augmentation, making the training data cover enough variations; the other is designing features and algorithms that are insensitive to those variations, such as SIFT, or sliding-window detection.

Both rest on the same premise, that you know in advance which variations will occur. Data augmentation requires deciding beforehand how to rotate and how to scale; hand-crafted invariant features can't be built at all for variations that are too complex. As soon as a new task brings variations nobody anticipated, these approaches run out of options.

Convolutional networks have the same problem, and it stems from their fixed structure. The authors give two examples:

  1. Receptive fields in the same layer are all the same size. High-level features carry semantics, and different positions may correspond to objects of different sizes and shapes, yet the receptive fields are identical. Tasks that need fine localization, such as semantic segmentation, would want receptive fields that adapt to the object.
  2. Detection still extracts features from boxes. The object detection methods of the time all ended up extracting features from rectangular proposals. For objects without a fixed shape, such as people and animals, most of the box is background.

Someone Already Taught Networks to Warp

STN had already let networks learn geometric transformations on their own. It predicts a set of global transformation parameters, such as an affine matrix, and then warps the whole feature map accordingly.

STN applies one transformation to the entire feature map; the computation is expensive, the transformation parameters are hard to learn, and its successes at the time were mainly in small-scale image classification. Detection and segmentation scenes contain many objects, each with its own size and pose, and a single global transformation can't take care of them all.

Could each sampling point of a convolution, at every position, move on its own according to the content in front of it?

Solving the Problem

The Two Steps of Convolution

Let's first spell out ordinary convolution. The authors break 2D convolution into two steps, first sampling the input feature map on a regular grid R\mathcal{R}, then multiplying the sampled values by the weights and summing them.

For a 3×33\times3 convolution, the grid is

R={(−1,−1),(−1,0),…,(0,1),(1,1)},\mathcal{R}=\{(-1,-1),(-1,0),\ldots,(0,1),(1,1)\},

9 points in total. For each position p0\mathbf{p}_0 on the output feature map,

y(p0)=∑pn∈Rw(pn)⋅x(p0+pn).\mathbf{y}(\mathbf{p}_0)=\sum_{\mathbf{p}_n\in\mathcal{R}}\mathbf{w}(\mathbf{p}_n)\cdot\mathbf{x}(\mathbf{p}_0+\mathbf{p}_n).

pn\mathbf{p}_n runs through the 9 points of the grid in turn. This equation is the same for every channel, so from here on we look only at 2D spatial positions.

An Offset for Every Point

Deformable convolution changes just one thing, adding an offset Δpn\Delta\mathbf{p}_n to each point on the grid:

y(p0)=∑pn∈Rw(pn)⋅x(p0+pn+Δpn).\mathbf{y}(\mathbf{p}_0)=\sum_{\mathbf{p}_n\in\mathcal{R}}\mathbf{w}(\mathbf{p}_n)\cdot\mathbf{x}(\mathbf{p}_0+\mathbf{p}_n+\Delta\mathbf{p}_n).

The weights w\mathbf{w} stay the same; what changes is where the values are taken from.

Four diagrams of 3x3 convolution sampling locations on a dashed grid. (a) 9 green points in a regular 3x3 grid; (b) each light-green original location is pushed by a light-blue arrow to a new dark-blue location, in different directions and by different distances; (c) the 9 points are pushed outward from the center proportionally, forming an enlarged grid; (d) the 9 points are rotated together by an angle
Figure 1 from the paper, excerpted from page 2 of the v3 PDF. (a) The regular sampling grid of standard convolution; (b) deformable convolution, with an offset added to each point; (c)(d) are special cases of (b), corresponding to scaling and rotation.

(a) is ordinary convolution. In (b), each of the 9 points is pushed to a new location, in different directions and by different distances. (c) and (d) are special cases of (b). In (c), all the points are pushed outward from the center, which amounts to enlarging the kernel; in (d), all the points rotate together around the center, which amounts to a rotation. In other words, transformations such as scaling, aspect ratio, and rotation are all contained in “each point gets its own offset.”

Sampling at Fractional Positions

The offsets are learned, so they usually aren't exactly whole numbers, and the sampling points land between grid points. The authors use bilinear interpolation to get the values:

x(p)=∑qG(q,p)⋅x(q),G(q,p)=g(qx,px)⋅g(qy,py),g(a,b)=max⁡(0,1−∣a−b∣).\mathbf{x}(\mathbf{p})=\sum_{\mathbf{q}}G(\mathbf{q},\mathbf{p})\cdot\mathbf{x}(\mathbf{q}),\qquad G(\mathbf{q},\mathbf{p})=g(q_x,p_x)\cdot g(q_y,p_y),\qquad g(a,b)=\max(0,1-|a-b|).

q\mathbf{q} runs over all integer positions on the feature map, but gg is nonzero only when the distance is less than 1, so in practice only the four nearest points get any weight. For example, a grid point originally at (1,3)(1,3) lands at (1.25,3.5)(1.25,3.5) after an offset of (0.25,0.5)(0.25,0.5); its four neighbors (1,3)(1,3), (1,4)(1,4), (2,3)(2,3) and (2,4)(2,4) get weights of 0.375, 0.375, 0.125 and 0.125 according to distance, which add up to 1.

Interpolation is continuous, so the output is differentiable with respect to Δpn\Delta\mathbf{p}_n, and gradients can flow all the way back to the offsets.

Where the Offsets Come From

Diagram of deformable convolution. On the left is the input feature map, marked with a set of 3x3 sampling boxes. A green arrow sends the input into conv, producing an offset field with 2N channels, from which the offsets for this position are taken, drawn as 3x3 small arrows pointing in different directions. The offsets are passed down to the deformable convolution, and the deformed sampling locations on the input feature map are connected by blue dashed lines to a single point on the output feature map on the right
Figure 2 from the paper, excerpted from page 2 of the v3 PDF. A 3×33\times3 deformable convolution.

The offsets are computed by another convolutional layer from the same input feature map, which is the green path at the top of the figure. This convolution has the same kernel size and dilation as the main convolution, and its output offset field has the same spatial size as the input, with 2N2N channels. A 3×33\times3 convolution has N=9N=9 sampling points, each needing two numbers, (Δy,Δx)(\Delta y,\Delta x), which makes 18 channels.

In other words, every position on the feature map has its own set of 9 offsets, and those offsets are computed by looking at the content around that position. This is what the authors mean by local, dense, and adaptive.

Let's build a complete layer with torchvision's deform_conv2d:

Python
import torch
import torch.nn as nn
from torchvision.ops import deform_conv2d

class DeformableConv(nn.Module):
    def __init__(self, cin, cout, k=3):
        super().__init__()
        self.weight = nn.Parameter(torch.randn(cout, cin, k, k) * 0.01)
        # convolution that predicts the offsets: 3×3 like the main convolution, 2N = 18 output channels, initialized to 0
        self.offset = nn.Conv2d(cin, 2 * k * k, k, padding=k // 2)
        nn.init.zeros_(self.offset.weight)
        nn.init.zeros_(self.offset.bias)

    def forward(self, x):
        offset = self.offset(x)                        # [B, 18, H, W]: 9 (Δy, Δx) pairs for each output position
        print("Offset shape:", tuple(offset.shape))
        return deform_conv2d(x, offset, self.weight, padding=1)

m = DeformableConv(256, 256)
y = m(torch.randn(2, 256, 38, 38))
print("Output shape:", tuple(y.shape))
print(f"Main convolution parameters {m.weight.numel():,}, offset convolution parameters {sum(p.numel() for p in m.offset.parameters()):,}")
Text
Offset shape: (2, 18, 38, 38)
Output shape: (2, 256, 38, 38)
Main convolution parameters 589,824, offset convolution parameters 41,490

The offset convolution adds only about 7% of the main convolution's parameters. Its weights are initialized to 0, so at the start of training all the offsets are 0 and the layer is just an ordinary convolution; the offset convolution's learning rate is β\beta times that of the other layers, with β=1\beta=1 by default. The main convolution's weights and the offsets are learned together during training, with no extra annotation required.

Two Special Cases

The uniform enlargement of Figure 1(c) is in fact atrous convolution. With all offsets at 0, deformable convolution is an ordinary convolution; a grid point (i,j)(i,j) plus the offset (i,j)(i,j) moves to (2i,2j)(2i,2j), which is exactly atrous convolution with a dilation of 2. Atrous convolution's enlargement factor has to be hard-coded in advance, whereas deformable convolution lets the network decide for itself at every position.

Deformable RoI Pooling

The same idea is applied to RoI pooling in detection. RoI pooling cuts a proposal into k×kk\times k bins, averages each bin, and outputs features of a fixed size. Deformable RoI pooling adds an offset to each bin so the bins can move onto the object.

The offsets are computed a little differently here. The authors first run an ordinary RoI pooling, followed by a fully connected layer that outputs “normalized” offsets Δp^ij\Delta\hat{\mathbf{p}}_{ij}, which are then multiplied by the proposal's width and height to get the actual offsets:

Δpij=γ⋅Δp^ij∘(w,h),γ=0.1.\Delta\mathbf{p}_{ij}=\gamma\cdot\Delta\hat{\mathbf{p}}_{ij}\circ(w,h),\qquad \gamma=0.1.

Multiplying by the width and height makes offset learning independent of the proposal's size. The position-sensitive RoI pooling used in R-FCN also has a deformable version, in which the offsets are instead computed over the whole image by a convolutional layer.

Into the Network

The authors put deformable convolution into two backbones pretrained on ImageNet, namely ResNet-101 and Aligned-Inception-ResNet, which fixes a feature-alignment problem. As was common practice at the time, the stride of the last stage (conv5) is changed from 2 to 1 and its convolutions to dilation 2, raising the resolution of the output feature map from 1/32 to 1/16.

Deformable convolution replaces only the last few 3×33\times3 convolutions in conv5, the last 3 by default. The backbones feed four task networks, namely DeepLab for semantic segmentation, the single-stage class-aware RPN, and the two-stage detectors Faster R-CNN and R-FCN. The latter two can also swap their RoI pooling for the deformable version.

Discussion

Semantic segmentation uses PASCAL VOC and Cityscapes, measured by mIoU; detection uses PASCAL VOC and COCO, measured by mAP.

Receptive Fields Really Do Follow the Object

Diagram of the receptive fields of two convolutional layers, over a grayscale photo of a small sheep and a large sheep, stacked in three levels. (a) standard convolution: on the top level there is one point on the small sheep and one on the large sheep, and the sampling points they map to in the two levels below are fixed-size square grids. (b) deformable convolution: for the same two points, the sampling points on the small sheep's side cluster on the small sheep, while those on the large sheep's side spread out widely, covering the whole large sheep
Figure 5 from the paper, excerpted from page 4 of the v3 PDF. Receptive fields of two layers of standard convolution (a) and two layers of deformable convolution (b).

Trace a point on the top level downward through two 3×33\times3 convolutions, and it maps to a cluster of sampling points on the bottom level. (a) is ordinary convolution, where the sampling region is the same-sized square whether the point sits on the small sheep or the large one. In (b), with deformable convolution, the point on the small sheep looks only at the small sheep, while the point on the large sheep spreads out over the whole animal.

This is an illustration, and the authors also quantified it. They define a metric called effective dilation, the mean distance between adjacent sampling points within a filter, which can be read as a rough measure of receptive field size. They then run R-FCN with 3 deformable convolution layers on the VOC 2007 test set and group the statistics by the kind of object on which the filter's center falls:

Table: Excerpted from Table 2 of the paper, mean and standard deviation of effective dilation. Objects are divided into small, medium, and large by box area, with boundaries at 96296^2 and 2242224^2 pixels.
LayerSmall objectsMedium objectsLarge objectsBackground
res5c5.3 ± 3.35.8 ± 3.58.4 ± 4.56.2 ± 3.0
res5b2.5 ± 1.33.1 ± 1.55.1 ± 2.53.2 ± 1.2
res5a2.2 ± 1.22.9 ± 1.34.2 ± 1.63.1 ± 1.1

All three layers show the same trend, with the sampling points spreading wider as objects get larger. The background values fall between those of medium and large objects, which the authors take to mean that recognizing background also needs a fairly large receptive field.

How Many Layers to Replace

Table: Excerpted from Table 1 of the paper, ResNet-101. DeepLab is mIoU on Cityscapes; the three detectors are [email protected] on the VOC 2007 test set.
Deformable convolution layersDeepLab (Cityscapes)class-aware RPNFaster R-CNNR-FCN
0 (baseline)70.444.962.161.8
173.554.463.863.0
274.456.363.363.8
3 (default)75.257.263.364.7
675.157.764.065.4

Replacing just the last layer improves DeepLab by 3 percentage points and class-aware RPN by nearly 10. These two methods have no RoI pooling and compute their results directly from convolutional features, which may be why they benefit the most. DeepLab saturates at 3 layers, while the detectors are still improving at 6, and the authors settle on 3 layers as a trade-off across tasks.

Compared with Atrous Convolution

If atrous convolution is a special case, would simply turning up the dilation have the same effect?

Table: Excerpted from Table 3 of the paper, ResNet-101. DeepLab is mIoU; the detectors are [email protected] / [email protected] on the VOC 2007 test set. The numbers in parentheses are the dilations of the last three 3×33\times3 convolutions.
SettingDeepLab (VOC / Cityscapes)class-aware RPNFaster R-CNNR-FCN
Atrous convolution (2,2,2), default69.7 / 70.468.0 / 44.978.1 / 62.180.0 / 61.8
Atrous convolution (4,4,4)73.1 / 71.972.8 / 53.178.6 / 63.180.5 / 63.0
Atrous convolution (6,6,6)73.6 / 72.773.6 / 55.278.5 / 62.380.2 / 63.5
Atrous convolution (8,8,8)73.2 / 72.473.2 / 55.177.8 / 61.880.3 / 63.2
Deformable convolution75.3 / 75.274.5 / 57.278.6 / 63.381.4 / 64.7
Deformable RoI pooling––78.3 / 66.681.2 / 65.0
Both––79.3 / 66.982.6 / 68.5

Increasing the dilation improves every task, which shows the default receptive field was too small to begin with. But the best dilation varies by task, 6 for DeepLab and 4 for Faster R-CNN, and no single value suits them all. Deformable convolution is no worse than the best dilation on any task, and it needs no per-task tuning.

Deformable RoI pooling on its own already lifts both detectors' [email protected] considerably, and this stricter metric demands more precise boxes. With both modules, R-FCN goes from 80.0 / 61.8 to 82.6 / 68.5.

The Cost

Table: Three groups excerpted from Table 4 of the paper, ResNet-101, on an Intel E5-2650 v2 CPU and an NVIDIA K40 GPU. Total runtime includes image resizing and post-processing such as NMS.
MethodParametersNetwork forward (s)Total runtime (s)
DeepLab (Cityscapes)46.0M0.6100.650
+ deformable modules46.1M0.6560.696
Faster R-CNN58.3M0.1470.190
+ deformable modules59.9M0.1920.234
R-FCN47.1M0.1430.170
+ deformable modules49.5M0.1690.193

Parameters go up by at most 2.4M, from which the authors conclude that the gains come from the ability to model geometric transformations, not from a bigger model. In time, DeepLab adds only about 7%, while Faster R-CNN's forward time goes from 0.147 seconds to 0.192 seconds, about 30% more.

The other cost is in deployment. Deformable convolution isn't a standard convolution; early on, exporting torchvision's deform_conv2d to ONNX required a third-party package to break it down into ordinary operations, which also affected speed.

COCO

Finally, a full comparison on COCO test-dev, measured by mAP@[0.5:0.95]:

Table: Excerpted from Table 5 of the paper.
MethodBackboneStandardDeformable
class-aware RPNResNet-10123.225.8
Faster R-CNNResNet-10129.433.1
R-FCNResNet-10130.834.5
Faster R-CNNAligned-Inception-ResNet30.834.1
R-FCNAligned-Inception-ResNet32.936.1
R-FCN, multi-scale testing and box averagingAligned-Inception-ResNet35.537.5

On ResNet-101, the three methods improve by 11%, 13%, and 12% in relative terms. The gains hold up with a stronger backbone or with tricks such as multi-scale testing. Broken down by object size, the largest absolute gains are on medium and large objects; Faster R-CNN's mAP on large objects, for example, goes from 47.1 to 51.2, and on small objects from 9.0 to 11.6.

Conclusion

Deformable convolution adds a learned offset to every sampling point of a convolution. The change is small, adding only a few percent more parameters, yet the receptive field can adapt to the size and shape of objects, giving consistent gains in both segmentation and detection, especially on [email protected], which demands more precise boxes.

To try it in your own network, torchvision's deform_conv2d plus a zero-initialized offset convolution is all it takes. Deployment isn't as easy, since it isn't a standard convolution and inference frameworks may not support it. The sampling points have mastered some fancy footwork, and the engineers deploying them may have to learn a few steps too.

This idea went a long way afterward. v2 added modulation weights to the sampling points, InternImage built a large-model backbone on v3, and Deformable DETR carried it over to attention. We'll run into it again in the next few notes.