AI Logic

Convolution Types

Grouped Convolution

Updated๏ผš

How the number of groups changes the connections between input and output channels. From the left: ordinary convolution (g = 1), grouped convolution (g = 2 and g = 4), and depthwise convolution (g = 8). The bottom row is the 8 input channels and the top row the 8 output channels, connected by lines, with the number of weights shown below

Background and Overview

Grouped convolution is a convolution that splits the input and output channels into gg groups each and convolves only within groups of the same index. Because channels are not mixed across groups, the number of parameters and the amount of computation are 1/g1/g of an ordinary convolution.

It is like splitting a class into several teams that discuss only within their own team and then lining up the conclusions of each team (concatenation), instead of the whole class discussing together at once (ordinary convolution). Fewer conversation partners means less effort, but information does not pass directly between teams.

For a layer that maps 256 channels to 256 channels with a 3ร—3 kernel, the number of weights is as follows (excluding biases).

Number of groups ggNumber of weights
1 (ordinary convolution)3 ร— 3 ร— 256 ร— 256 = 589,824
2589,824 รท 2 = 294,912
32589,824 รท 32 = 18,432
256 (depthwise convolution)3 ร— 3 ร— 256 = 2,304

Grouped convolution originated in AlexNet (Krizhevsky et al., 2012), where it was used to split a network that did not fit on a single GPU with 3GB of memory across two GPUs. Later, ResNeXt (Xie et al., 2017) used grouped convolution as a way to raise accuracy without changing the computational cost, showing that the number of groups (called "cardinality" in ResNeXt) is a design dimension alongside depth and width. Setting the number of groups equal to the number of input channels gives the "depthwise convolution" that forms the first half of depthwise separable convolution.

Mechanism and Computation

Let the input have CinC_{\text{in}} channels, the output CoutC_{\text{out}} channels, the kernel be kร—kk \times k, and the number of groups be gg. Both CinC_{\text{in}} and CoutC_{\text{out}} must be divisible by gg.

  1. Split the input channels: Split the CinC_{\text{in}} channels, in order from the first, into gg groups of Cin/gC_{\text{in}}/g channels each.
  2. Split the output channels: Likewise split the CoutC_{\text{out}} output channels into gg groups of Cout/gC_{\text{out}}/g each.
  3. Convolve each group: The output channels of group jj are computed by an ordinary convolution that uses only the input channels of group jj. The kernel shape is kร—kร—(Cin/g)k \times k \times (C_{\text{in}}/g).
  4. Concatenate: Stack the outputs of the gg groups along the channel dimension to form the CoutC_{\text{out}}-channel output.

In equation form, with j=โŒŠoโ€‰/โ€‰(Cout/g)โŒ‹j = \lfloor o \,/\, (C_{\text{out}}/g) \rfloor denoting the group of output channel oo (โ‹†\star is spatial convolution):

yo=โˆ‘m=0Cin/gโˆ’1Ko,โ€‰mโ‹†xโ€‰jCin/g+my_o = \sum_{m=0}^{C_{\text{in}}/g - 1} K_{o,\,m} \star x_{\,j C_{\text{in}}/g + m}

In an ordinary convolution (g=1g = 1), mm runs over all input channels, but in a grouped convolution it runs only over the Cin/gC_{\text{in}}/g channels of its own group. As a result, the number of weights and the number of multiplications for an Hร—WH \times W feature map both become 1/g1/g, as follows.

Weights=k2โ‹…Cingโ‹…Cout,Multiplications=k2โ‹…Cingโ‹…Coutโ‹…Hโ‹…W\text{Weights} = k^2 \cdot \frac{C_{\text{in}}}{g} \cdot C_{\text{out}}, \qquad \text{Multiplications} = k^2 \cdot \frac{C_{\text{in}}}{g} \cdot C_{\text{out}} \cdot H \cdot W

In PyTorch, gg is set with the groups argument of nn.Conv2d. The weight shape is (out_channels, in_channels / groups, kH, kW). The documentation explains that groups=2 is equivalent to "two conv layers side by side, each seeing half the input channels and producing half the output channels, and both subsequently concatenated." The spatial size of the output follows the same formula as an ordinary convolution and does not depend on groups.

Why It Works: Correspondence with Parallel Branches

ResNeXt explains why grouped convolution is useful beyond merely "saving computation" through its correspondence with a split-transform-merge structure.

A ResNeXt block places CC small transformations Ti\mathcal{T}_i of the same shape side by side, sums them, and adds a residual connection (Equation 3 in ResNeXt).

y=x+โˆ‘i=1CTi(x)\boldsymbol{y} = \boldsymbol{x} + \sum_{i=1}^{C} \mathcal{T}_i(\boldsymbol{x})

Each Ti\mathcal{T}_i is a "bottleneck" that reduces 256 channels to dd channels with a 1ร—1 convolution, applies a 3ร—3 convolution, and restores 256 channels with a 1ร—1 convolution. The paper showed that these CC branches are exactly equivalent to the following single path (Figure 3 in the paper).

  1. A 1ร—1 convolution reduces 256 channels to Cโ‹…dC \cdot d channels at once (the first layers of the CC branches merged into one)
  2. A 3ร—3 grouped convolution with CC groups is applied (each group corresponds to the 3ร—3 of one branch)
  3. A 1ร—1 convolution restores 256 channels (summing the outputs of the CC branches is the same as concatenating them and applying a 1ร—1)

In other words, grouped convolution is an efficient way to express "many branches of the same shape side by side" in a single layer. With C=32C = 32 and d=4d = 4, the block has Cโ‹…(256โ‹…d+3โ‹…3โ‹…dโ‹…d+dโ‹…256)โ‰ˆ70,000C \cdot (256 \cdot d + 3 \cdot 3 \cdot d \cdot d + d \cdot 256) \approx 70{,}000 weights, almost the same as the ResNet bottleneck (256โ‹…64+3โ‹…3โ‹…64โ‹…64+64โ‹…256โ‰ˆ70,000256 \cdot 64 + 3 \cdot 3 \cdot 64 \cdot 64 + 64 \cdot 256 \approx 70{,}000). Yet the width of the 3ร—3 layer grows from 64 to 128 channels (Table 2 in the paper).

Number of groups CC124832
Width per group dd644024144
Width of the grouped layer Cโ‹…dC \cdot d648096112128

The advantage of grouped convolution is that splitting into groups allows a wider layer with the same number of weights.

In the AlexNet paper, the convolutional layers split across the two GPUs consistently learned different roles. The first-layer kernels on GPU 1 learned largely color-agnostic patterns, while those on GPU 2 learned color-specific patterns, and this was reported to happen regardless of the weight initialization. Splitting into groups can lead each group to specialize in a different kind of feature.

Experimental Results

AlexNet (ImageNet, network split across two GPUs)

AlexNet connected the convolutions in layers 2, 4, and 5 only to the channels of the previous layer on the same GPU (layer 3 and the fully connected layers connect to all channels). Compared with training a network with half as many kernels in each convolutional layer on a single GPU, the top-1 and top-5 error rates dropped by 1.7 and 1.2 points, respectively. However, according to a note in the paper, the single-GPU network being compared did not halve the last convolutional layer and the fully connected layers, so it is larger than "exactly half," and the comparison is biased in favor of the single-GPU side.

ResNeXt (ImageNet-1K, top-1 error % with a single 224ร—224 crop)

Results of varying the number of groups CC and the width per group dd while keeping the computation fixed (Table 3 in the paper). The more groups, the lower the error.

Setting (Cร—dC \times d)50 layers101 layers
1 ร— 64d (ResNet)23.922.0
2 ร— 40d23.021.7
4 ร— 24d22.621.4
8 ร— 14d22.321.3
32 ร— 4d22.221.2

The paper also compared which dimension to grow when doubling the computation of ResNet-101 (Table 4 in the paper).

How to growSettingTop-1 errorTop-5 error
(Baseline) ResNet-1011 ร— 64d22.06.0
Deeper (ResNet-200)1 ร— 64d21.75.8
Wider (ResNet-101)1 ร— 100d21.35.7
More groups (ResNeXt-101)2 ร— 64d20.75.5
More groups (ResNeXt-101)64 ร— 4d20.45.3

For the same added computation, increasing the number of groups lowered the error more than going deeper or wider.

Practical Considerations

Stacking only grouped convolutions blocks information flow between groups. With two consecutive grouped convolutions, the output of a group is computed only from the input channels that were in the same group from the start, and cannot use any information from other groups (ShuffleNet, Zhang et al., 2018). ResNeXt places ordinary 1ร—1 convolutions before and after the grouped convolution, and ShuffleNet inserts a "channel shuffle" that reorders the channels after the grouped convolution, to connect the groups.

  • Fewer multiplications do not necessarily mean faster execution: In the ResNeXt paper, training ResNet-101 took 0.70 seconds per mini-batch, while ResNeXt-101 (32ร—4d), with nearly the same computation, took 0.95 seconds (8 GPUs, a Torch implementation without special optimization). ShuffleNet V2 (Ma et al., 2018) also lists as one of its guidelines that increasing groups at fixed computation increases memory access and slows execution.
  • Channel counts must be divisible by gg: Both in_channels and out_channels must be multiples of groups.
  • Use it inside blocks of three or more layers: The ResNeXt paper notes that for a block of only two layers (two stacked 3ร—3 convolutions), rewriting it as parallel branches just yields a wide ordinary convolution, which is not a meaningful structure.
  • Too many groups leads to diminishing returns in accuracy: In ResNeXt's Table 3, the improvement from 8 ร— 14d to 32 ร— 4d is only 0.1 points. The paper keeps the width per group at 4 or more.

Comparison with Related Convolutions and How to Choose

The table below compares convolutions that mix channels differently, from the same viewpoints. CinC_{\text{in}} and CoutC_{\text{out}} are the numbers of input and output channels.

ConvolutionHow channels are mixedWeights (for kร—kk \times k)Typical use
Ordinary convolution (g=1g = 1)Mixes all channelsk2CinCoutk^2 C_{\text{in}} C_{\text{out}}VGG, ResNet, etc.
Grouped convolutionMixes only within groupsk2CinCout/gk^2 C_{\text{in}} C_{\text{out}} / gAlexNet, ResNeXt, ShuffleNet
Depthwise convolution (g=Cing = C_{\text{in}})No mixing (per channel)k2Coutk^2 C_{\text{out}}MobileNet, etc.; combined with 1ร—1
Depthwise separable convolutionDepthwise mixes space, 1ร—1 mixes channelsk2Cin+CinCoutk^2 C_{\text{in}} + C_{\text{in}} C_{\text{out}}Xception, MobileNet

Rough guidelines for choosing:

  • Raising accuracy at the same computation: As in ResNeXt, turn the 3ร—3 in the bottleneck into a grouped convolution and widen the layer. Connect the groups with the 1ร—1 convolutions before and after it.
  • Cutting computation substantially: Use depthwise separable convolution, the extreme form of grouped convolution.
  • Making the 1ร—1 convolutions lighter too: Consider the ShuffleNet design, which also makes the 1ร—1 convolutions grouped and connects the groups with channel shuffle.
  • Prioritizing speed on GPUs: Avoid using too many groups, and measure speed on the actual hardware.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Grouped convolution: in PyTorch, set the number of groups with the groups argument of nn.Conv2d
# Both in_channels and out_channels must be divisible by groups

count = lambda m: sum(p.numel() for p in m.parameters())
for g in (1, 2, 32, 256):
  conv = nn.Conv2d(256, 256, kernel_size=3, padding=1, groups=g, bias=False)
  print(g, tuple(conv.weight.shape), count(conv))
# 1   (256, 256, 3, 3) 589824
# 2   (256, 128, 3, 3) 294912
# 32  (256, 8, 3, 3)   18432
# 256 (256, 1, 3, 3)   2304   โ† depthwise convolution


# Check that groups=2 computes the same as "convolving each half of the channels and concatenating"
x = torch.randn(1, 8, 16, 16)
grouped = nn.Conv2d(8, 8, kernel_size=3, padding=1, groups=2, bias=False)
conv_a = nn.Conv2d(4, 4, kernel_size=3, padding=1, bias=False)
conv_b = nn.Conv2d(4, 4, kernel_size=3, padding=1, bias=False)
with torch.no_grad():
  conv_a.weight.copy_(grouped.weight[:4])  # outputs 0-3 see only inputs 0-3
  conv_b.weight.copy_(grouped.weight[4:])  # outputs 4-7 see only inputs 4-7
  y_split = torch.cat([conv_a(x[:, :4]), conv_b(x[:, 4:])], dim=1)
  print(torch.allclose(grouped(x), y_split, atol=1e-6))  # True


# ResNeXt bottleneck (Figure 3(c) in the paper, 32ร—4d, 256 input/output channels)
class ResNeXtBlock(nn.Module):
  def __init__(self, channels=256, cardinality=32, width=4):
    super().__init__()
    inner = cardinality * width  # 32 ร— 4 = 128
    self.body = nn.Sequential(
      nn.Conv2d(channels, inner, 1, bias=False),         # 1ร—1: 256 โ†’ 128 (the first layers of 32 branches merged)
      nn.BatchNorm2d(inner), nn.ReLU(),
      nn.Conv2d(inner, inner, 3, padding=1, groups=cardinality, bias=False),  # 3ร—3: 32 groups, 4 โ†’ 4 each
      nn.BatchNorm2d(inner), nn.ReLU(),
      nn.Conv2d(inner, channels, 1, bias=False),         # 1ร—1: 128 โ†’ 256 (corresponds to summing the branch outputs)
      nn.BatchNorm2d(channels),
    )
    self.relu = nn.ReLU()

  def forward(self, x):
    return self.relu(x + self.body(x))  # residual connection


block = ResNeXtBlock()
conv_params = sum(m.weight.numel() for m in block.modules() if isinstance(m, nn.Conv2d))
print(conv_params)  # 32 * (256*4 + 3*3*4*4 + 4*256) = 70144 (the ResNet bottleneck has 69632)
block.eval()  # BatchNorm is used, so switch to eval() for inference to use the training statistics
print(block(torch.randn(2, 256, 56, 56)).shape)  # torch.Size([2, 256, 56, 56])

FAQ

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

Depthwise convolution is the special case of grouped convolution in which the number of groups equals the number of input channels. Each group then contains a single channel, and channels are not mixed at all.

Q. How should the number of groups be chosen?
A.

In the ResNeXt experiments, increasing the groups from 1 to 32 at fixed computation lowered the error, but the gain from 8 to 32 was small. The paper keeps each group at least 4 channels wide. Since GPU speed also tends to drop, decide by actually measuring accuracy and speed.

Q. Is it a problem that information does not mix between groups?
A.

It becomes a problem when only grouped convolutions are stacked. ResNeXt places ordinary 1ร—1 convolutions before and after the grouped convolution, and ShuffleNet inserts a channel shuffle, to connect the groups.

References

  1. A. Krizhevsky, I. Sutskever, and G. E. Hinton, "ImageNet Classification with Deep Convolutional Neural Networks," NeurIPS, 2012.
  2. S. Xie, R. Girshick, P. Dollรกr, Z. Tu, and K. He, "Aggregated Residual Transformations for Deep Neural Networks," CVPR, 2017.
  3. X. Zhang, X. Zhou, M. Lin, and J. Sun, "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices," CVPR, 2018.
  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."