AI Logic

Convolution Types

Dynamic Convolution

Updated:

How dynamic convolution works. The left side shows the flow of one layer: attention weights π1 to π3 are computed from the input through global average pooling, two fully connected layers, and a temperature-scaled Softmax; the three kernels W1 to W3 are summed with these weights into one kernel, which is convolved with the input only once, followed by batch normalization and ReLU. The right side compares the weights computed from the same values z with Sigmoid (CondConv), Softmax (τ = 1), and Softmax (τ = 30), together with their sums

Background and Overview

Dynamic convolution is a method that gives one convolutional layer KK kernels, sums them using "attention weights" computed for each input, and then convolves only once. It was proposed by Chen et al. at Microsoft in 2020. It increases representational power without making the network deeper or wider, at a cost of only about 4% more computation.

Lightweight networks operate under a tight computational budget, so they can increase neither the number of layers (depth) nor the number of channels (width). According to the paper, cutting MobileNetV3's computation from 219M to 66M multiply-adds lowers its ImageNet top-1 accuracy from 75.2% to 67.4%. Dynamic convolution compensates for this drop by reshaping the kernels to fit each input while keeping depth and width unchanged.

The mechanism is very similar to CondConv, which was proposed around the same time. The difference lies in how the weights are produced: dynamic convolution constrains the weights to sum to 1 (Softmax) and uses a large temperature early in training so that the weights are nearly uniform. These two techniques make it easier to train deep networks in which many layers are made dynamic at once.

Replacing the convolutions in MobileNetV2, MobileNetV3, and ResNet with dynamic convolutions raised ImageNet top-1 accuracy by 2.3 to 5.6 points.

In language modeling there is a different method also named "Dynamic Convolution" (Wu et al., 2019, "Pay Less Attention with Lightweight and Dynamic Convolutions"). This article covers the method by Chen et al. (2020) used in image CNNs.

Mechanism and Computation

A dynamic convolution layer computes its output from an input xx in the following steps.

  1. Compute the values behind the attention weights: Apply global average pooling to the input to get one value per channel, then pass it through a fully connected layer (reducing the dimension to 1/4), a ReLU, and another fully connected layer to obtain KK values z1,…,zKz_1, \dots, z_K. This has the same shape as the SE block of SENet, but whereas the SE block outputs a scale for each output channel, this outputs a weight for each kernel.
  2. Turn them into weights with a temperature-scaled Softmax: Divide by the temperature τ\tau and apply Softmax to get attention weights πk(x)\pi_k(x) that sum to 1 (Equation 3 in the paper).
πk(x)=exp⁡(zk/τ)∑jexp⁡(zj/τ)\pi_k(x) = \frac{\exp(z_k / \tau)}{\sum_j \exp(z_j / \tau)}
  1. Mix the kernels and biases: Sum the KK learned kernels W~k\tilde{W}_k and biases b~k\tilde{b}_k, each weighted by the same πk(x)\pi_k(x). All KK kernels share the same size and the same numbers of input and output channels.
W~(x)=∑k=1Kπk(x) W~k,b~(x)=∑k=1Kπk(x) b~k,0≤πk(x)≤1,  ∑k=1Kπk(x)=1\tilde{W}(x) = \sum_{k=1}^{K} \pi_k(x)\, \tilde{W}_k, \qquad \tilde{b}(x) = \sum_{k=1}^{K} \pi_k(x)\, \tilde{b}_k, \qquad 0 \le \pi_k(x) \le 1,\ \ \sum_{k=1}^{K} \pi_k(x) = 1
  1. Convolve only once: Convolve the input with the mixed kernel and bias, followed by batch normalization and an activation function (such as ReLU), as in an ordinary CNN.

The paper defines the idea as a "dynamic perceptron" y=g(W~⊤(x) x+b~(x))y = g(\tilde{W}^{\top}(x)\, x + \tilde{b}(x)) that also applies to fully connected layers, and chooses convolution as the case that satisfies the computational condition: computing the attention and mixing the kernels must cost far less than the main computation. In a fully connected layer, mixing costs as much as the main computation, so the condition is not met.

For a layer that takes an H×W×CinH \times W \times C_{\text{in}} input and produces CoutC_{\text{out}} channels with a Dk×DkD_k \times D_k kernel, the number of multiplications is as follows.

ComputationMultiplications
Convolution (main)HWCinCoutDk2H W C_{\text{in}} C_{\text{out}} D_k^2
AttentionHWCin+Cin2/4+CinK/4H W C_{\text{in}} + C_{\text{in}}^2/4 + C_{\text{in}} K/4
Mixing kernels and biasesKCinCoutDk2+KCoutK C_{\text{in}} C_{\text{out}} D_k^2 + K C_{\text{out}}

As long as KK is much smaller than the number of positions HWH W, the extra computation is small compared with the main convolution. For MobileNetV2 (×1.0) with K=4K = 4, multiply-adds increased only from 300.0M to 312.9M (Table 1 in the paper).

Why It Works: Two Techniques for Easier Training

Dynamic convolution works because it selects and applies a different linear function for each input. Each input is convolved with just one kernel, but because the attention weights depend on the input, the layer as a whole is a nonlinear function of the input and is more expressive than a static convolution.

A deep dynamic convolution network must learn the kernels and attention of every layer jointly, which makes training difficult as is. The paper presented two techniques that make training easier.

Technique 1: Constrain the attention weights to sum to 1

With a sum of 1, the mixed kernel ∑kπkW~k\sum_k \pi_k \tilde{W}_k stays inside the region whose vertices are the KK kernels (their convex hull). If each weight is merely kept between 0 and 1, as in CondConv, the mixed kernel can move over a much larger range (Figure 4 in the paper: for 3 kernels, the 0-to-1 constraint alone gives two pyramids, while adding the sum-to-1 constraint gives a triangle). Removing the degree of freedom along the direction from the origin (how much the whole kernel is scaled) makes the attention model easier to learn.

Technique 2: Keep attention nearly uniform early in training

An ordinary Softmax with temperature τ=1\tau = 1 tends to concentrate its output on a single kernel, so early in training only some of the kernels get trained. A larger temperature brings the weights closer to uniform, so all kernels are trained together.

TemperatureExample: weights for z=(4,1,−1)z = (4, 1, -1)Behavior
τ=1\tau = 10.95, 0.05, 0.01Uses almost only one kernel
τ=30\tau = 300.36, 0.33, 0.31Uses all kernels almost equally

On MobileNetV2 (×0.5, K=4K = 4), τ=1\tau = 1 gave a top-1 accuracy of 64.8%, below the 65.4% of static convolution. τ=30\tau = 30 gave 69.4%, and linearly lowering τ\tau from 30 to 1 over the first 10 epochs gave 69.9%.

Analysis of the trained models showed that the attention weights are nearly uniform in shallow layers and sparse in deep layers. It was also confirmed that using attention correctly for each input is essential (Table 3 below).

Experimental Results

ImageNet classification (K=4K = 4 in each layer, trained with temperature annealing)

Results with every convolution except the first layer replaced by dynamic convolution (Table 8 in the paper).

ModelParametersMultiply-addsTop-1 (%)Top-5 (%)
MobileNetV2 ×1.03.5M300.0M72.091.0
Dynamic version11.1M312.9M75.2 (+3.2)92.1
MobileNetV2 ×0.52.0M97.0M65.486.4
Dynamic version4.0M101.4M69.9 (+4.5)89.0
MobileNetV2 ×0.351.7M59.2M60.382.9
Dynamic version2.8M62.0M65.9 (+5.6)86.4
MobileNetV3-Small2.9M66.0M67.486.4
Dynamic version4.8M68.5M70.3 (+2.9)88.7
ResNet-1811.1M1.81G70.489.7
Dynamic version42.7M1.85G72.7 (+2.3)90.7

The thinner (lower-computation) the model, the larger the improvement.

Effect of temperature (MobileNetV2 ×0.5; static convolution scores 65.4%)

Temperature τ\tau1510203040Annealed 30 → 1
Top-1 (%)64.865.767.569.469.469.269.9

Does it really adapt to each input? (MobileNetV2 ×0.5, Table 3 in the paper)

Accuracy of the trained model when only the way the kernels are mixed is changed.

MixingTop-1 (%)
Sum with attention weights (the actual method)69.4
Average of the KK kernels36.0
Only the kernel with the largest attention0.1
Shuffle weights across kernels within the same image14.8
Use attention weights from other images27.3

Accuracy drops sharply in every case, showing that the kernels play different roles and that the attention is meaningful for each input.

Comparison with CondConv (MobileNetV2, ImageNet, Table 2 in the paper)

ModelMethodKernelsParametersMultiply-addsTop-1 (%)
×1.0CondConv827.5M329M74.6
×1.0Dynamic convolution411.1M312.9M75.2
×0.5CondConv815.5M113M68.4
×0.5Dynamic convolution44M101.4M69.9

COCO keypoint detection

On the task of locating human body keypoints (AP), switching the backbone to dynamic convolution also improved results by 1.6 points for ResNet-18, 2.9 for MobileNetV2, and 2.2 for MobileNetV3-Small (Table 10 in the paper).

Practical Considerations

Without a large temperature, it can perform worse than static convolution. Making many layers dynamic with an ordinary Softmax (τ=1\tau = 1) slows training, and on MobileNetV2 ×0.5 it ended 0.6 points below static convolution. As in the paper, a good starting point is to begin at τ=30\tau = 30 and lower it to 1 over the first 10 epochs.

  • The number of parameters grows nearly KK-fold: It rose from 3.5M to 11.1M for MobileNetV2 ×1.0 and from 11.1M to 42.7M for ResNet-18. What stays nearly flat is the number of multiply-adds; the amount of weights held in memory does grow.
  • More kernels are not always better: On MobileNetV2, accuracy stopped improving once KK exceeded 4, because jointly learning the kernels and attention becomes harder and overfitting becomes more likely. The paper uses K=4K = 4 as the default.
  • Actual speed does not hold up as well as the multiply-add count: Inference time on a CPU (single core, batch size 1) rose by about 10%, against a 4% increase in multiply-adds. The paper attributes this to global average pooling and small matrix operations being less optimized than convolution.
  • Layers closer to the output benefit more: Using attention only in the low-resolution (deep) layers reached 67.0%, close to the 69.4% of using it in all layers, while using it only in the shallow layers reached just 42.5% (with the remaining layers using the average of the kernels). If only one convolution in a MobileNetV2 block is chosen, the final 1×1 convolution was the most effective.
  • It can be combined with SE blocks: On MobileNetV3-Small, removing SE and using dynamic convolution still scored 2.2 points above the original model with SE, and using both added another 0.7 points.

Comparison with CondConv and Others, and How to Choose

The table below compares the two methods that mix kernels according to the input, along with related methods, from the same viewpoints.

MethodWhat changes per inputHow weights are producedWeight rangeDefault number of kernels
Dynamic convolutionKernel and biasTwo FC layers (reduced to 1/4) + temperature-scaled Softmax0 to 1, summing to 14
CondConvKernelOne FC layer + SigmoidEach 0 to 1, sum unconstrained8
SE block (SENet)Per-channel scale of the outputTwo FC layers―― (one kernel)
Deformable convolutionPositions the kernel readsA convolution predicts offsets―― (one kernel)

The differences between dynamic convolution and CondConv are summarized below.

AspectDynamic convolutionCondConv
Weight functionSoftmax (divided by temperature τ\tau)Sigmoid
Sum of weightsFixed at 1Unconstrained (0 to nn)
Weights early in trainingNearly uniform via a large temperatureNearly uniform at first due to Sigmoid
Range of the mixed kernelInside the convex hull of the kernelsWider (the overall scale can also change)
Routing sharingPer layerShared within a block
Main targetModels with very low computation (mobile)Uses where inference speed matters more than parameter count (servers, autonomous driving, etc.)

In the CondConv paper, Sigmoid scored 1.5 points higher than Softmax (MobileNetV1 (0.25x)). The dynamic convolution paper, on the other hand, reports that a Softmax with a large temperature achieved higher accuracy than CondConv with fewer kernels. Both conclusions come from each paper's own setup, so the reliable approach is to verify on the model at hand.

Rough guidelines for choosing:

  • Improving the accuracy of very low-computation models: Use dynamic convolution. The thinner the model, the larger the gain, and the parameter increase is smaller than with CondConv.
  • Increasing capacity without worrying about parameter count: Also consider CondConv with more experts.
  • Adding almost no parameters: Keep a single kernel and use an SE block, which scales the output channels.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# Dynamic convolution: not built into PyTorch, so it is written following Equations 1 and 3 and Figure 3 of the paper
#   z = FC(ReLU(FC(GlobalAveragePool(x))))      the first FC reduces the dimension to 1/4
#   pi = softmax(z / tau)                       sums to 1
#   y = (sum_k pi_k W_k) * x + sum_k pi_k b_k   followed by batch normalization and ReLU


class DynamicConv2d(nn.Module):
  def __init__(self, in_ch, out_ch, kernel_size, stride=1, padding=0, K=4, reduction=4, tau=30.0):
    super().__init__()
    self.out_ch, self.stride, self.padding, self.tau = out_ch, stride, padding, tau
    self.weight = nn.Parameter(torch.empty(K, out_ch, in_ch, kernel_size, kernel_size))
    for w in self.weight:
      nn.init.kaiming_normal_(w, nonlinearity="relu")
    self.bias = nn.Parameter(torch.zeros(K, out_ch))
    hidden = max(in_ch // reduction, 4)
    self.attention = nn.Sequential(nn.Linear(in_ch, hidden), nn.ReLU(), nn.Linear(hidden, K))

  def attention_weights(self, x):
    z = self.attention(x.mean(dim=(2, 3)))   # (B, K)
    return F.softmax(z / self.tau, dim=1)     # sums to 1; the larger tau, the closer to uniform

  def forward(self, x):
    b, c, h, w = x.shape
    pi = self.attention_weights(x)
    kernels = torch.einsum("bk,koihw->boihw", pi, self.weight)  # (B, out_ch, in_ch, k, k)
    biases = pi @ self.bias                                     # (B, out_ch); the biases are mixed with the same weights
    # Merge the B inputs into one and use groups=B to apply "a different kernel per input" in a single convolution
    y = F.conv2d(x.reshape(1, b * c, h, w), kernels.reshape(b * self.out_ch, c, *kernels.shape[-2:]),
                 biases.reshape(-1), stride=self.stride, padding=self.padding, groups=b)
    return y.reshape(b, self.out_ch, *y.shape[-2:])


# Lower the temperature linearly from 30 to 1 over the first 10 epochs (the paper's temperature annealing)
def set_temperature(model, epoch, start=30.0, end=1.0, anneal_epochs=10):
  t = end if epoch >= anneal_epochs else start + (end - start) * epoch / anneal_epochs
  for m in model.modules():
    if isinstance(m, DynamicConv2d):
      m.tau = t


block = nn.Sequential(DynamicConv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU())
x = torch.randn(2, 32, 28, 28)
for epoch in range(3):
  set_temperature(block, epoch)
  block.train()
  y = block(x)  # the training step (loss, backpropagation) is omitted
print(y.shape)  # torch.Size([2, 64, 28, 28])

block.eval()  # because of BatchNorm, switch to eval() for inference to use the training statistics
with torch.no_grad():
  print(block[0].attention_weights(x).sum(dim=1))  # tensor([1., 1.])

FAQ

Q. How does dynamic convolution differ from CondConv?
A.

Both sum several kernels with per-input weights and convolve only once. The difference is how the weights are produced: CondConv keeps each weight between 0 and 1 with Sigmoid, while dynamic convolution uses a temperature-scaled Softmax so that the weights sum to 1, and starts training with a large temperature so that the weights are nearly uniform. In the dynamic convolution paper, these techniques achieved high accuracy with half as many kernels as CondConv (4).

Q. How should the temperature τ be set?
A.

The paper reports that starting at τ = 30 and lowering it linearly to 1 over the first 10 epochs worked best (69.9% on MobileNetV2 ×0.5). Fixing τ at 20 to 30 gave 69.4%, while keeping τ = 1 fell below static convolution.

Q. Does inference really stay fast?
A.

Multiply-adds increase by only about 4%, but in the paper's CPU measurements inference time rose by about 10%. This is because the global average pooling and small fully connected layers used for attention are less optimized than convolution. The number of parameters also grows nearly K-fold, so enough memory is needed.

References

  1. Y. Chen, X. Dai, M. Liu, D. Chen, L. Yuan, and Z. Liu, "Dynamic Convolution: Attention over Convolution Kernels," CVPR, 2020.
  2. B. Yang, G. Bender, Q. V. Le, and J. Ngiam, "CondConv: Conditionally Parameterized Convolutions for Efficient Inference," NeurIPS, 2019.
  3. F. Wu, A. Fan, A. Baevski, Y. N. Dauphin, and M. Auli, "Pay Less Attention with Lightweight and Dynamic Convolutions," ICLR, 2019. (A different method with the same name)