AI Logic

Convolution Types

Deformable Convolution

Updated:

Difference between standard and deformable convolution in which input cells the kernel uses. The left shows a standard convolution using the central 3×3 cells of a 9×9 input. The center shows a deformable convolution in which the 9 sampling positions are shifted by offset arrows, using the cells surrounding the shifted positions. The right shows the flow of the convolution that produces the offsets and the bilinear interpolation that computes the value at a fractional position from the 4 surrounding cells

Background and overview

Deformable convolution is a convolution that moves the positions at which the kernel reads its input by learned per-cell shifts (offsets). A standard convolution always reads the input in a fixed grid shape, whereas deformable convolution can spread or bend its sampling positions to fit the size and shape of objects.

A standard convolution is like reading a pattern through a stencil of fixed shape. With deformable convolution, the positions of the stencil's 9 holes can be nudged to fit what is being looked at: spread out over a large object, or lined up vertically over a tall, thin one.

Dai et al. (2017) attributed CNNs' difficulty with geometric variations such as object scale, pose, viewpoint and part deformation to the fixed geometry of their building blocks. Convolutions read the input at fixed positions, pooling downsamples by a fixed ratio, and RoI pooling divides a region into a fixed layout. As a result, every cell in the same layer has a receptive field of the same size, which cannot adapt to object size.

The paper therefore proposed two modules that add offsets to the sampling positions.

ModuleReplacesWhat is shifted
Deformable convolutionStandard convolutionEach kernel position (9 positions for 3×3)
Deformable RoI poolingRoI poolingThe position of each bin into which the region is divided

Both only add a small layer that computes the offsets from the input, and no ground-truth data on how to shift is needed. This article focuses mainly on deformable convolution.

Mechanism and computation steps

For an output position p0\boldsymbol{p}_0, a standard convolution computes the following using the set of kernel positions R\mathcal{R} ({(−1,−1),(−1,0),…,(1,1)}\{(-1,-1), (-1,0), \ldots, (1,1)\} for 3×3) (Eq. 1 of the paper).

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

Deformable convolution reads the input at each kernel position pn\boldsymbol{p}_n plus an offset Δpn\Delta\boldsymbol{p}_n (Eq. 2). N=∣R∣N = |\mathcal{R}| is the number of kernel positions, 9 for 3×3.

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

The computation proceeds as follows.

  1. Compute the offsets: apply another convolution (with the same kernel size and dilation as the main one) to the same input feature map to produce a 2N2N-channel "offset field". For each cell, this gives the vertical and horizontal shifts Δpn\Delta\boldsymbol{p}_n for all NN positions.
  2. Determine the sampling positions: for each output cell p0\boldsymbol{p}_0, read at p0+pn+Δpn\boldsymbol{p}_0 + \boldsymbol{p}_n + \Delta\boldsymbol{p}_n. Offsets are usually fractional, so the positions fall off cell centers.
  3. Interpolate values at fractional positions: obtain the value at each such position from the values at the surrounding integer positions by bilinear interpolation (Eqs. 3 and 4).
x(p)=∑qG(q,p)⋅x(q),G(q,p)=g(qx,px)⋅g(qy,py),g(a,b)=max⁡(0, 1−∣a−b∣)\boldsymbol{x}(\boldsymbol{p}) = \sum_{\boldsymbol{q}} G(\boldsymbol{q}, \boldsymbol{p}) \cdot \boldsymbol{x}(\boldsymbol{q}), \qquad G(\boldsymbol{q}, \boldsymbol{p}) = g(q_x, p_x) \cdot g(q_y, p_y), \quad g(a, b) = \max(0,\, 1 - |a - b|)

GG is nonzero only for the 4 cells surrounding p\boldsymbol{p}, so the computation is quick. 4. Multiply by the weights and sum: multiply the NN interpolated values by the kernel weights w(pn)\boldsymbol{w}(\boldsymbol{p}_n) and sum them into one output cell.

The offset layer and the main weights are learned jointly. Gradients for the offsets are obtained by backpropagation through the bilinear interpolation of Eqs. 3 and 4. The weights of the offset layer are initialized to 0, so training starts from exactly the same computation as a standard convolution.

The offsets are not a single value for the whole layer but values computed from the input for each cell of the image. Even within the same layer, the sampling positions spread out over large objects and contract over small ones. Active Convolution, proposed around the same time, also learns sampling positions, but its offsets are fixed learned values shared across all positions. The paper argues that this difference matters for per-position prediction tasks such as object detection.

Why it works: receptive fields that vary by position

Stacking deformable convolutions compounds the shifts, so the shape of the receptive field changes substantially to fit objects. The paper defined the "effective dilation" as the mean distance between adjacent sampling positions and aggregated it by object size (R-FCN, VOC 2007 test images, Table 2 of the paper; mean ± standard deviation).

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

In every layer, the sampling range widens over larger objects. Although nothing was taught explicitly, the offsets are evidently learned from image content. Over the background, the range lies between that for medium and large objects, which the paper explains by the need for a relatively wide area to recognize background.

This mechanism can also be seen as a generalization of dilated convolution. Setting the offsets to Δpn=(l−1)pn\Delta\boldsymbol{p}_n = (l - 1)\boldsymbol{p}_n yields a dilated convolution with dilation ll, and other transformations such as scaling, aspect ratio changes and rotation can also be represented (Figure 1 of the paper). Dilated convolution spreads the kernel the same way at every position, whereas deformable convolution can vary the spread by position.

A method based on a similar idea is Spatial Transformer Networks (STN), which deform the entire feature map with an affine or similar transformation. The paper notes that learning the offsets of deformable convolution can be viewed as an "extremely light-weight STN", but differs in that it changes sampling positions densely and locally rather than deforming the whole map with a single transformation.

Experimental results

Dai et al. replaced the 3×3 convolutions near the end of ResNet-101 with deformable convolutions and evaluated them on semantic segmentation (DeepLab) and object detection (Faster R-CNN, R-FCN and others).

Number of layers replaced (Table 1 of the paper)

Layers replacedDeepLab mIoU (VOC, %)Faster R-CNN mAP@0.7 (VOC 2007, %)R-FCN mAP@0.7 (VOC 2007, %)
0 (baseline)69.762.161.8
173.963.863.0
274.863.363.8
3 (default)75.263.364.7
674.864.065.4

Accuracy rose as more layers were replaced, saturating at 3 layers for DeepLab and at 6 for the others. The paper uses 3 layers in subsequent experiments.

Comparison with dilated convolution (Table 3 of the paper)

The baseline network uses dilated convolutions with dilation 2 in its last 3 layers. Increasing the dilation improves accuracy, but the best value differed by task (6 for DeepLab, 4 for Faster R-CNN). Deformable convolution achieved the highest accuracy on every task.

ModuleDeepLab mIoU (VOC / Cityscapes)Faster R-CNN mAP@0.5 / @0.7R-FCN mAP@0.5 / @0.7
Dilated convolution (dilation 2, default)69.7 / 70.478.1 / 62.180.0 / 61.8
Dilated convolution (dilation 4)73.1 / 71.978.6 / 63.180.5 / 63.0
Dilated convolution (dilation 6)73.6 / 72.778.5 / 62.380.2 / 63.5
Deformable convolution75.3 / 75.278.6 / 63.381.4 / 64.7
Deformable convolution + deformable RoI pooling―79.3 / 66.982.6 / 68.5

On COCO test-dev (mAP@[0.5:0.95]) as well, Faster R-CNN with ResNet-101 improved from 29.4 to 33.1, and R-FCN from 30.8 to 34.5 (Table 5 of the paper).

Parameters and runtime (Table 4 of the paper, Nvidia K40 GPU)

ModelParametersTotal inference time
DeepLab (VOC)46.0M → 46.1M0.094 s → 0.098 s
Faster R-CNN58.3M → 59.9M0.190 s → 0.234 s
R-FCN47.1M → 49.5M0.170 s → 0.193 s

The added parameters and time are small, showing that the accuracy gains do not come simply from a larger model.

Practical considerations

It requires dedicated operators and is not as fast as a standard convolution. Because the sampling positions differ from cell to cell, it is hard to fold into fast matrix operations as with standard convolutions, and bilinear interpolation adds further computation. It is not available as PyTorch's core nn.Conv2d; use a dedicated implementation such as torchvision's torchvision.ops.DeformConv2d. In Table 4 of the paper, too, the total inference time of Faster R-CNN increases from 0.190 s to 0.234 s.

  • There is no need to replace every layer: the paper replaced only the 3×3 convolutions near the end of the network and showed that 3 layers are enough. Replacing shallow layers as well adds computation with little gain.
  • Initialize the offset layer to 0: this makes training start out identical to a standard convolution. The paper uses the same learning rate for the offset layers as for the existing layers (except the fully connected layer of deformable RoI pooling in Faster R-CNN, which uses 0.01 times that rate).
  • Match the shape of the offsets: in torchvision's DeformConv2d, offsets are passed with shape (batch, 2 × offset_groups × kH × kW, output height, output width). For 3×3 with offset_groups=1, that is 18 channels. Make the output size of the offset convolution the same as the main output.
  • An improved version with masks exists: torchvision's deform_conv2d computes the improved version (Deformable ConvNets v2), which multiplies the sampled values by weights, when mask is passed; otherwise it computes the method of this paper.

Comparison with related methods and how to choose

The following table lines up convolutions that change the shape of the receptive field from the same perspective.

MethodSampling positionsVaries by positionAdditional parametersComputational cost
Standard convolutionFixed k×kk \times k gridNoNoneLightest
Dilated convolutionSpaced-out grid (set by the dilation)NoNoneLight (keeps the feature map size)
Deformable convolutionGrid + offsets computed from the inputYesOffset layerHeavy (dedicated operators and interpolation)
STNThe whole feature map deformed by an affine or similar transformationOne transformation per imageLayer producing the transformation parametersHeavier due to the deformation

A rough guide to choosing:

  • Objects vary in size and shape, and per-position predictions are needed: for object detection and segmentation, replace the last few layers with deformable convolutions.
  • Only a larger receptive field is needed: dilated convolution is sufficient. However, the best dilation differs by task and needs to be explored.
  • Speed and ease of implementation come first: use standard or dilated convolutions. Deformable convolution requires dedicated operators and may not be available on some target hardware.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torchvision.ops import DeformConv2d

# Deformable convolution: not in core PyTorch, so use torchvision.ops.DeformConv2d
# Offset shape: (batch, 2 * offset_groups * kH * kW, output height, output width)


class DeformableConvBlock(nn.Module):
  def __init__(self, in_ch, out_ch, kernel_size=3, padding=1, dilation=1):
    super().__init__()
    k = kernel_size
    # Offset convolution: same kernel size and dilation as the main one, outputs 2N channels (18 for 3×3)
    self.offset = nn.Conv2d(in_ch, 2 * k * k, k, padding=padding, dilation=dilation)
    nn.init.zeros_(self.offset.weight)  # initialize to 0: training starts out identical to a standard convolution
    nn.init.zeros_(self.offset.bias)
    self.conv = DeformConv2d(in_ch, out_ch, k, padding=padding, dilation=dilation)

  def forward(self, x):
    offset = self.offset(x)        # vertical and horizontal shifts for 9 positions per cell
    return self.conv(x, offset)   # read shifted positions by bilinear interpolation, multiply by weights and sum


x = torch.randn(2, 64, 32, 32)
block = DeformableConvBlock(64, 128)
print(block(x).shape)  # torch.Size([2, 128, 32, 32])

# Initially (offsets are 0), the output matches a standard convolution with the same weights
plain = nn.Conv2d(64, 128, 3, padding=1)
with torch.no_grad():
  plain.weight.copy_(block.conv.weight)
  plain.bias.copy_(block.conv.bias)
  print(torch.allclose(block(x), plain(x), atol=1e-4))  # True

# The only additional parameters are in the offset layer
count = lambda m: sum(p.numel() for p in m.parameters())
print(count(block.conv), count(block.offset))  # 73856 (main) 10386 (64*18*3*3 + 18)

FAQ

Q. How are the offsets learned?
A.

The offsets are the output of a separate convolution applied to the same input. Because the values at the sampling positions are obtained by bilinear interpolation, the output is differentiable with respect to position, and gradients from the loss backpropagate all the way to the offset layer. No ground-truth data on how to shift is needed.

Q. How does it differ from dilated convolution?
A.

Dilated convolution spreads out at the same spacing at every position. Deformable convolution changes the sampling positions using offsets computed from the input for each cell, so it can read widely over large objects and narrowly over small ones. Dilated convolution can be viewed as a deformable convolution with the offsets fixed to particular values.

Q. Which layers should it be used in?
A.

In the paper, replacing the 3×3 convolutions near the end of ResNet-101 was enough, with 3 layers giving a sufficient effect. Since it increases computation, a safe start is to replace only the last few layers.

References

  1. J. Dai, H. Qi, Y. Xiong, Y. Li, G. Zhang, H. Hu, and Y. Wei, "Deformable Convolutional Networks," ICCV, 2017.
  2. torchvision Documentation, "torchvision.ops.deform_conv2d."
  3. torchvision Documentation, "torchvision.ops.DeformConv2d."