AI Logic

Convolution Types

Depthwise Separable Convolution

Updated:

Comparison of standard and depthwise separable convolution. The left shows the flow and channel connections of a standard convolution; the right shows the two-stage flow of depthwise and pointwise convolution and their channel connections. Below each, the number of parameters and multiplications

Background and overview

Depthwise separable convolution is a convolution that splits a standard convolution into two stages: "convolving each channel only spatially" (depthwise convolution) and "mixing channels with a 1×1 convolution" (pointwise convolution). The output shape stays the same as with a standard convolution, while the number of parameters and the amount of computation drop sharply.

A standard convolution uses a single filter to learn both "spatial patterns" and "which channels to combine" at once. Depthwise separable convolution divides these two jobs. In cooking terms, a standard convolution does separate prep work for every combination of ingredients, whereas a separable convolution preps each ingredient just once (spatial processing) and then only varies the blend (channel combination) at the end.

For a layer that maps 64 channels to 128 channels with a 3×3 filter, the number of weights is as follows.

ConvolutionNumber of weights
Standard convolution3 × 3 × 64 × 128 = 73,728
Depthwise separable convolution3 × 3 × 64 + 64 × 128 = 576 + 8,192 = 8,768

The number of weights drops to about 1/8.4.

The idea is said to have originated with Sifre, who developed it during an internship at Google Brain in 2013 and applied it to AlexNet (Chollet, 2017). Later, Chollet's Xception built an entire network by replacing the modules of GoogLeNet (Inception) with depthwise separable convolutions, and Howard et al.'s MobileNet used it as the basic building block of lightweight models that run on devices such as smartphones. Today it is used in many image recognition models, including MobileNetV2, EfficientNet and ConvNeXt.

In TensorFlow and Keras, this convolution is simply called "separable convolution" (SeparableConv2D). It is different from "spatially separable convolution", which splits a 3×3 filter into 3×1 and 1×3, so when reading explanations with similar names, check which one is meant.

Mechanism: a convolution split into two stages

Let the input be a feature map F\boldsymbol{F} of size DF×DFD_F \times D_F with MM channels, and the output have NN channels (with stride 1 and padding to preserve the spatial size; the notation follows the MobileNets paper).

A standard convolution uses NN filters of size DK×DK×MD_K \times D_K \times M and convolves all input channels at once.

Gk,l,n=∑i,j,mKi,j,m,n⋅Fk+i−1, l+j−1, mG_{k,l,n} = \sum_{i,j,m} K_{i,j,m,n} \cdot F_{k+i-1,\, l+j-1,\, m}

Depthwise separable convolution splits this into the following two stages.

  1. Depthwise convolution: prepare one DK×DKD_K \times D_K filter per input channel (MM in total) and convolve only that channel. Channels are not mixed, so the output still has MM channels.
G^k,l,m=∑i,jK^i,j,m⋅Fk+i−1, l+j−1, m\hat{G}_{k,l,m} = \sum_{i,j} \hat{K}_{i,j,m} \cdot F_{k+i-1,\, l+j-1,\, m}
  1. Pointwise convolution: use NN filters of size 1×1×M1 \times 1 \times M to take a weighted sum of the MM channel values at each pixel, producing NN channels. Spatial positions are not mixed; only channels are.
Gk,l,n=∑mPm,n⋅G^k,l,mG_{k,l,n} = \sum_{m} P_{m,n} \cdot \hat{G}_{k,l,m}

Here KK is the weight of the standard convolution, K^\hat{K} is the weight of the depthwise convolution (the mm-th filter of K^\hat{K} applies only to the mm-th input channel), and PP is the weight of the pointwise convolution (an M×NM \times N matrix).

Depthwise convolution alone cannot create new features that combine channels. Adding the pointwise convolution produces, with far fewer weights, the same kind of "output that mixes both space and channels" as a standard convolution.

MobileNet places batch normalization and ReLU after both the depthwise and the pointwise convolution.

Whether to insert an activation function between the two convolutions differs by model. MobileNet inserts batch normalization and ReLU in between, but in the Xception paper, omitting ReLU or ELU in between made training on ImageNet converge faster and also gave higher final accuracy. When reproducing an existing model, follow the ordering of the original paper.

How much computation and how many parameters are saved

The number of multiplications (computational cost) of a standard convolution is as follows (Eq. 2 of MobileNets).

DK⋅DK⋅M⋅N⋅DF⋅DFD_K \cdot D_K \cdot M \cdot N \cdot D_F \cdot D_F

For depthwise separable convolution, it is the sum of the depthwise and pointwise convolutions (Eq. 5).

DK⋅DK⋅M⋅DF⋅DF  +  M⋅N⋅DF⋅DFD_K \cdot D_K \cdot M \cdot D_F \cdot D_F \;+\; M \cdot N \cdot D_F \cdot D_F

Their ratio is as follows.

DK⋅DK⋅M⋅DF⋅DF+M⋅N⋅DF⋅DFDK⋅DK⋅M⋅N⋅DF⋅DF=1N+1DK2\frac{D_K \cdot D_K \cdot M \cdot D_F \cdot D_F + M \cdot N \cdot D_F \cdot D_F}{D_K \cdot D_K \cdot M \cdot N \cdot D_F \cdot D_F} = \frac{1}{N} + \frac{1}{D_K^2}

The number of output channels NN is in the tens to hundreds, so 1/N1/N is small and the ratio is determined almost entirely by 1/DK21/D_K^2. With a 3×3 filter, the cost is roughly 1/8–1/9 that of a standard convolution (MobileNets). The number of parameters drops by the same ratio.

Counting for the example in the figure at the top (DK=3D_K = 3, M=64M = 64, N=128N = 128, DF=56D_F = 56) gives the following.

Number of parametersNumber of multiplications
Standard convolution73,728About 231 million
Depthwise convolution576About 1.8 million
Pointwise convolution8,192About 26 million
Depthwise separable convolution (total)8,768About 27 million (about 1/8.4)

After the reduction, most of the computation is in the pointwise convolution. Across MobileNet as a whole, too, about 95% (94.86%) of the multiplications and about 75% (74.59%) of the parameters are concentrated in 1×1 convolutions. A 1×1 convolution is just a matrix multiplication, so it can be computed quickly with highly optimized matrix libraries.

Regarding the effect on accuracy, the MobileNets paper compares against a model with the same structure using standard convolutions. ImageNet accuracy dropped by about 1 point, from 71.7% to 70.6%, while the multiplications decreased from 4,866 million to 569 million and the parameters from 29.3 million to 4.2 million.

Even if the number of multiplications drops to 1/8, the actual runtime does not necessarily drop to 1/8. Depthwise convolution involves a lot of memory reads and writes relative to its computation, so on GPUs and similar hardware it may not speed up as much as the computation count suggests. Speed is not determined by computation alone but also depends on memory access and the hardware, so measuring on the actual target device is recommended (Ma et al., 2018).

Comparison with related convolutions and how to choose

The following table lines up depthwise separable convolution and closely related convolutions from the same perspective. MM is the number of input channels, NN the number of output channels, and gg the number of groups.

ConvolutionHow channels are mixedNumber of weights (for DK×DKD_K \times D_K)Main uses
Standard convolutionAll channels mixed at onceDK2MND_K^2 M NMany CNNs such as VGG and ResNet
Grouped convolutionChannels split into gg groups, mixed only within each groupDK2MN/gD_K^2 M N / gResNeXt, ShuffleNet
Depthwise convolution aloneNot mixed (each channel independent)DK2MD_K^2 MNot used alone; combined with a 1×1 convolution
Depthwise separable convolutionSpace mixed depthwise, channels mixed by 1×1DK2M+MND_K^2 M + M NXception, MobileNet

Depthwise convolution corresponds to grouped convolution with the number of groups equal to the number of input channels (g=Mg = M). In PyTorch, passing the number of input channels as groups to nn.Conv2d yields a depthwise convolution.

A rough guide to choosing:

  • Keeping computation and model size down: use depthwise separable convolution. It is the standard choice for models running on smartphones and embedded devices.
  • Accuracy comes first and compute is plentiful: use standard convolution. With the same structure, standard convolution gives slightly higher accuracy.
  • Something in between: use grouped convolution and tune the number of groups.

Since MobileNet, this building block has continued to be used and refined. MobileNetV2 uses blocks that widen the channels with a pointwise convolution, apply a depthwise convolution, and then narrow them again with another pointwise convolution. ConvNeXt uses depthwise convolutions with large 7×7 filters.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

'''
Image classification on MNIST (a small CNN built with depthwise separable convolutions)
'''

# Hyperparameters
batch_size = 64       # batch size
epochs = 3            # number of epochs
learning_rate = 1e-3  # learning rate

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


# Depthwise separable convolution (as in MobileNet, batch normalization and ReLU follow each convolution)
class DepthwiseSeparableConv(nn.Module):
  def __init__(self, in_ch, out_ch, kernel_size=3, stride=1):
    super().__init__()
    # Depthwise convolution: groups=in_ch applies a separate filter to each channel
    self.depthwise = nn.Conv2d(in_ch, in_ch, kernel_size, stride=stride,
                               padding=kernel_size // 2, groups=in_ch, bias=False)
    self.bn1 = nn.BatchNorm2d(in_ch)
    # Pointwise convolution: mix channels with a 1×1 convolution
    self.pointwise = nn.Conv2d(in_ch, out_ch, kernel_size=1, bias=False)
    self.bn2 = nn.BatchNorm2d(out_ch)
    self.relu = nn.ReLU()

  def forward(self, x):
    x = self.relu(self.bn1(self.depthwise(x)))
    return self.relu(self.bn2(self.pointwise(x)))


# Compare the number of weights (same setting as the table in the text: 3×3, 64 → 128 channels)
standard = nn.Conv2d(64, 128, kernel_size=3, padding=1, bias=False)
separable = DepthwiseSeparableConv(64, 128)
count = lambda m: sum(p.numel() for p in m.parameters())
print(count(standard))             # 3*3*64*128 = 73728
print(count(separable.depthwise))  # 3*3*64 = 576
print(count(separable.pointwise))  # 64*128 = 8192


# Small CNN: a standard convolution first, then depthwise separable convolutions
class SmallMobileNet(nn.Module):
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False),  # [B, 1, 28, 28] -> [B, 32, 28, 28]
      nn.BatchNorm2d(32),
      nn.ReLU(),
      DepthwiseSeparableConv(32, 64, stride=2),                 # -> [B, 64, 14, 14]
      DepthwiseSeparableConv(64, 128, stride=2),                # -> [B, 128, 7, 7]
      DepthwiseSeparableConv(128, 128),                         # -> [B, 128, 7, 7]
      nn.AdaptiveAvgPool2d(1),                                  # -> [B, 128, 1, 1]
      nn.Flatten(),
    )
    self.classifier = nn.Linear(128, num_classes)

  def forward(self, x):
    return self.classifier(self.features(x))


# Dataset and loaders
transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)

# Training
model = SmallMobileNet().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

for epoch in range(epochs):
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    loss = criterion(model(images), labels)
    loss.backward()
    optimizer.step()

# Evaluation
model.eval()
correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = model(images).argmax(dim=1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

print(f"Test Accuracy: {100 * correct / total:.2f}%")

FAQ

Q. Isn't depthwise convolution alone enough?
A.

Depthwise convolution only processes each channel separately and never combines channels. As a result, it cannot create new features that combine colors or patterns. This is also why the MobileNets paper pairs it with a 1×1 pointwise convolution.

Q. Does accuracy drop compared with a standard convolution?
A.

It often drops slightly. In the MobileNets paper, compared with a model of the same structure using standard convolutions, ImageNet accuracy fell from 71.7% to 70.6%, while the multiplications dropped to about 1/8.5 and the parameters to about 1/7.

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

Depthwise convolution is grouped convolution with the number of groups equal to the number of input channels. Depthwise separable convolution adds a 1×1 convolution to it to provide the channel-mixing role.

References

  1. L. Sifre, "Rigid-Motion Scattering for Image Classification," Ph.D. thesis, Ecole Polytechnique, 2014.
  2. F. Chollet, "Xception: Deep Learning with Depthwise Separable Convolutions," CVPR, 2017.
  3. A. G. Howard, M. Zhu, B. Chen, D. Kalenichenko, W. Wang, T. Weyand, M. Andreetto, and H. Adam, "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications," arXiv:1704.04861, 2017.
  4. N. Ma, X. Zhang, H.-T. Zheng, and J. Sun, "ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design," ECCV, 2018.
  5. PyTorch Documentation, "torch.nn.Conv2d."