AI Logic

Convolution Types

CondConv

Updated:

How CondConv works. The left shows the flow of a single layer: routing weights α1–α3 are computed from the input via global average pooling, a fully connected layer and a Sigmoid; the three expert kernels W1–W3 are summed with these weights into one kernel, which is convolved with the input only once. The right shows an example in which inputs A and B have different α, changing the pattern of the mixed kernel

Background and overview

CondConv (conditionally parameterized convolution) is a method that gives a single convolutional layer several kernels (experts), sums them with weights computed for each input, and then convolves only once. It was proposed in 2019 by Yang et al. at Google Brain. Even as the number of kernels grows to increase model capacity (how much the model can learn), the inference cost barely increases.

A standard convolution uses the same kernel for every input. The only ways to increase capacity are to add layers or to enlarge the kernels or add channels, and in either case the cost grows in proportion to the input size. CondConv sidesteps this constraint by dropping the assumption that the kernel is shared across all inputs and instead rebuilding the kernel to fit each input.

In cooking terms, rather than fixing a single recipe (kernel), several base recipes are prepared; after looking at the ingredients (input), they are blended into one recipe, and the cooking (convolution) is done only once.

In the paper, replacing the convolutions of MobileNet, MobileNetV2, MnasNet, ResNet and EfficientNet with CondConv raised ImageNet top-1 accuracy by 0.9–3.0 points in every case, while keeping the increase in inference cost below 10%.

Mechanism and computation steps

A CondConv layer computes its output from the input xx in the following steps. Let nn be the number of experts.

  1. Compute the routing weights: apply global average pooling to the input xx to get one value per channel, map it to nn values with a fully connected layer (weights RR), and squash them to 0–1 with a Sigmoid.
r(x)=Sigmoid⁡(GlobalAveragePool⁡(x) R),αi=ri(x)r(x) = \operatorname{Sigmoid}\bigl(\operatorname{GlobalAveragePool}(x)\, R\bigr), \qquad \alpha_i = r_i(x)
  1. Mix the kernels: weight the nn learned expert kernels W1,…,WnW_1, \dots, W_n by αi\alpha_i and sum them into one kernel for this input. Each WiW_i has the same shape as the kernel of the convolution being replaced.
  2. Convolve once: convolve the input with the mixed kernel and apply the activation function σ\sigma.
Output⁡(x)=σ((α1W1+⋯+αnWn)∗x)\operatorname{Output}(x) = \sigma\bigl((\alpha_1 W_1 + \dots + \alpha_n W_n) * x\bigr)

Because convolution is linear, this gives the same result as applying each of the nn convolutions separately and then taking the weighted sum (Figure 1 of the paper).

σ((α1W1+⋯+αnWn)∗x)=σ(α1(W1∗x)+⋯+αn(Wn∗x))\sigma\bigl((\alpha_1 W_1 + \dots + \alpha_n W_n) * x\bigr) = \sigma\bigl(\alpha_1 (W_1 * x) + \dots + \alpha_n (W_n * x)\bigr)

The right-hand side is a linear mixture of experts in which each expert is a single convolution. CondConv achieves the same capacity at the cost of a single convolution.

The routing weights are computed from the input each time, separately from the kernel weights. If α\alpha took the same value for every input, the mixed kernel would always be the same, and CondConv would have no more capacity than an ordinary convolution. The fact that α\alpha changes per input is the key to the method.

In the paper's experiments, layers within the same block (residual block, inverted bottleneck block, separable convolution) share routing weights. The paper also notes that the same idea applies to depthwise convolutions and fully connected layers.

Why it works: mixing once, reusing the convolution everywhere

CondConv achieves "large capacity, little extra compute" because mixing the kernels happens only once per input, while the mixed kernel is reused at every position of the input.

Consider a layer with a k×kk \times k kernel that maps CinC_{\text{in}} channels to CoutC_{\text{out}} channels with an output of size H×WH \times W, and compare the number of multiplications.

How capacity is increasedAdditional weightsAdditional multiplications
Enlarging the kernel, e.g. adding channelsΔ\DeltaΔ×H×W\Delta \times H \times W
Adding one CondConv expertk2CinCoutk^2 C_{\text{in}} C_{\text{out}}k2CinCoutk^2 C_{\text{in}} C_{\text{out}} (for mixing only)

With the usual approaches, each added weight adds as many multiplications as there are output positions (H×WH \times W). With CondConv, each added expert weight adds just one multiplication. For a 56×5656 \times 56 feature map there are 3,136 positions, so the difference is large. The routing computation (global average pooling and a small fully connected layer) is also small compared with the convolution.

Another reason is that the routing uses information from the entire image through global average pooling. A standard convolution only sees the small area covered by its kernel. CondConv can switch the local processing (kernel) according to the overall content of the image.

The paper's analysis found the following tendencies in the learned routing weights (CondConv-MobileNetV1 (0.5x), 32 experts per layer).

  • Shallow layers vary little across classes, while deeper layers become class-specific: this explains why applying CondConv to layers near the input does not improve accuracy much.
  • Weights in the final layer cluster near 0 or 1: even without regularization, experts are used sparsely and specialize.
  • Each expert has its specialty: in the final layer, experts were found that respond strongly to wheeled vehicles, rectangular structures, cylindrical household objects, and brown or black dog breeds, respectively.

Experimental results

ImageNet classification (top-1 accuracy %, 8 experts per layer)

Results of replacing each model's convolutions with CondConv (Table 1 of the paper). The baselines were retrained with the same settings as CondConv for a fair comparison.

ModelBaseline: multiplications (millions)Baseline: top-1CondConv: multiplications (millions)CondConv: top-1
MobileNetV1 (1.0x)56771.960073.7
MobileNetV2 (1.0x)30171.632974.6
MnasNet-A131274.932576.2
ResNet-50409377.7421378.6
EfficientNet-B039177.241378.3

In addition, a CondConv-EfficientNet-B0 made 1.1 times deeper reached 79.5% with 614 million multiplications. EfficientNet-B1 trained with the same settings (700 million) reached 79.2%, showing that when spending more compute, increasing capacity with CondConv is more efficient than uniformly scaling up the model. For MobileNetV1, accuracy increased monotonically as the number of experts grew through 1, 2, 4, 8, 16 and 32 (with sufficient regularization).

COCO object detection (mAP, SSD300, 8 experts per layer)

Results of using CondConv-MobileNetV1 as the feature extractor of SSD (Table 2 of the paper).

Feature extractorBaseline: multiplications (millions)Baseline: mAPCondConv: multiplications (millions)CondConv: mAP
MobileNetV1 (0.5x)35214.436318.0
MobileNetV1 (0.75x)73018.275521.0
MobileNetV1 (1.0x)123020.3128022.4

Comparison of routing functions (CondConv-MobileNetV1 (0.25x), 32 experts per layer, ImageNet top-1 %)

Results of varying how the routing is built (Table 3 of the paper). The standard MobileNetV1 (0.25x) reaches 50.4%.

Routing functiontop-1
Baseline (one fully connected layer + Sigmoid per layer)62.0
Computed once at the 7th block and used for all later layers56.5
Shared between two adjacent layers62.5
Add a ReLU hidden layer (1/8 of the input dimension)57.7
Add a ReLU hidden layer (same as the input dimension)62.2
Add a ReLU hidden layer (8 times the input dimension)54.1
Also connect the previous layer's routing weights60.3
Use Softmax instead of Sigmoid60.5

Computing the routing per layer (or among nearby layers) works better, and Sigmoid scored 1.5 points higher than Softmax. The paper attributes this to the fact that multiple experts are often useful for a single input at the same time.

Practical considerations

The number of weights grows with the number of experts, making overfitting more likely. With nn experts, the weights of the replaced layers grow roughly nn-fold. For large models the paper uses Dropout, AutoAugment and Mixup, and for ResNet-50 it additionally adds a "randomly drop experts during training" augmentation based on Shake-Shake to suppress overfitting. What barely grows is the number of multiplications at inference; the amount of weights held in memory does grow.

  • The training computation strategy must be chosen: because each input has a different kernel, a batch cannot be convolved in one go as is. The paper reports that with 4 or fewer experts it is more efficient to train in mixture-of-experts form (nn batched convolutions that are then summed) and run inference in CondConv form, while with 5 or more experts computing directly with a batch size of 1 is more efficient.
  • It is more effective in layers near the output than near the input: in Table 4 of the paper, accuracy was nearly the same whether CondConv was introduced from the 7th layer or from the 1st layer (62.0% and 62.5%). Making even the final classification layer CondConv improves accuracy, but that layer accounts for much of the additional compute.
  • Do not over-engineer the routing: adding a large hidden layer or connecting the previous layer's weights actually caused overfitting.
  • Multiplication count and actual speed are different things: the paper compares cost by the number of multiplications. Actual speed on hardware depends on how the per-input kernel construction is implemented, so measure on the target hardware.

Comparison with related methods and how to choose

The following table lines up methods that adapt computation to the input from the same perspective.

MethodWhat changes per inputHow the weights are producedNumber of convolutions
Standard convolutionNothing―1
CondConvThe kernel (weighted sum of nn experts)One fully connected layer + Sigmoid (each 0–1, sum unconstrained)1
Dynamic convolution (Chen et al., 2020)The kernel (weighted sum of KK kernels)Two fully connected layers + Softmax with temperature (sums to 1)1
Linear mixture of expertsWeights on each expert's outputWeights computed from the inputOne per expert
Sparsely-Gated MoEWhich experts are used (top kk only)Noisy top-kk gatingOne per selected expert
SE block of SENetPer-channel scaling of the outputGlobal average pooling + fully connected layers1 (output multiplied by scales)
Deformable convolutionThe positions the kernel readsOffsets produced by a convolution1 (with shifted read positions)

CondConv and dynamic convolution are very similar methods proposed at about the same time. The difference lies in how the weights are produced: dynamic convolution makes the weights sum to 1 and uses a high temperature early in training to keep them nearly uniform. The dynamic convolution paper reports that, thanks to this, it achieved higher accuracy than CondConv with fewer kernels (4 versus 8) (75.2% versus 74.6% on MobileNetV2 (1.0x)).

A rough guide to choosing:

  • Improving accuracy with almost no increase in inference cost: use CondConv or dynamic convolution. They suit settings where more weights are acceptable (such as server-side processing).
  • Keeping the number of weights down as well: consider dynamic convolution, which needs fewer kernels, or the SE block, which only multiplies by scales.
  • Adapting the read positions to object shapes: use deformable convolution. CondConv changes the kernel's values, while deformable convolution changes the kernel's shape (the positions it reads).

PyTorch example

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

# CondConv: not built into PyTorch, so write it following the paper's equations
#   alpha = Sigmoid(GlobalAveragePool(x) R)
#   Output(x) = (alpha_1 W_1 + ... + alpha_n W_n) * x   (the activation is applied outside the layer)


class CondConv2d(nn.Module):
  def __init__(self, in_ch, out_ch, kernel_size, stride=1, padding=0, num_experts=8):
    super().__init__()
    self.out_ch, self.stride, self.padding = out_ch, stride, padding
    # Expert kernels: shape (n, out_ch, in_ch, k, k). Each has the same shape as the original convolution kernel
    self.weight = nn.Parameter(torch.empty(num_experts, out_ch, in_ch, kernel_size, kernel_size))
    for w in self.weight:
      nn.init.kaiming_normal_(w, nonlinearity="relu")
    self.routing = nn.Linear(in_ch, num_experts)  # routing fully connected layer R

  def routing_weights(self, x):
    return torch.sigmoid(self.routing(x.mean(dim=(2, 3))))  # (B, n). Each in 0–1

  def forward(self, x):
    b, c, h, w = x.shape
    alpha = self.routing_weights(x)
    # Mix the kernels per input: (B, out_ch, in_ch, k, k)
    kernels = torch.einsum("bn,noikl->boikl", alpha, self.weight)
    # Merge the B inputs into one and use groups=B to compute "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:]),
                 stride=self.stride, padding=self.padding, groups=b)
    return y.reshape(b, self.out_ch, *y.shape[-2:])


layer = CondConv2d(32, 64, kernel_size=3, padding=1, num_experts=4)
x = torch.randn(2, 32, 28, 28)
y = layer(x)
print(y.shape)  # torch.Size([2, 64, 28, 28])

# Check that the result matches the mixture-of-experts form (convolve per expert, then take the weighted sum)
with torch.no_grad():
  alpha = layer.routing_weights(x)  # (2, 4)
  y_moe = sum(alpha[:, i, None, None, None] * F.conv2d(x, layer.weight[i], padding=1) for i in range(4))
  print(torch.allclose(y, y_moe, atol=1e-4))  # True

# When used as a layer: as with a standard convolution, follow it with batch normalization and an activation
block = nn.Sequential(CondConv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU())
block.eval()  # BatchNorm is present, so switch to eval() for inference to use the training statistics
print(block(x).shape)  # torch.Size([2, 64, 28, 28])

FAQ

Q. How does CondConv differ from a mixture of experts (MoE)?
A.

The result is the same as a linear mixture of experts in which each expert is a single convolution. The difference is the order of computation: a mixture of experts convolves once per expert and then sums the outputs, whereas CondConv sums the kernels first and convolves only once. As a result, adding experts barely increases the inference cost.

Q. How many experts should be used?
A.

The paper's main experiments use 8 per layer. For MobileNetV1, accuracy kept improving up to 32, but the number of weights grows in proportion to the number of experts, so decide together with regularization against overfitting and the amount of weights that fit in memory.

Q. Why use Sigmoid rather than Softmax for routing?
A.

In the paper's experiment (MobileNetV1 (0.25x), 32 experts), Sigmoid reached 62.0% and Softmax 60.5%, so Sigmoid performed better. The paper suggests this is because Sigmoid outputs a weight between 0 and 1 independently for each expert, allowing several experts to be used strongly at the same time for a single input.

References

  1. B. Yang, G. Bender, Q. V. Le, and J. Ngiam, "CondConv: Conditionally Parameterized Convolutions for Efficient Inference," NeurIPS, 2019.
  2. Y. Chen, X. Dai, M. Liu, D. Chen, L. Yuan, and Z. Liu, "Dynamic Convolution: Attention over Convolution Kernels," CVPR, 2020.
  3. TensorFlow TPU models, "CondConv" (implementation by the paper's authors)