6.4 Multiple Input and Multiple Output Channels

So far our convolutions have mapped a single 2D grid to a single 2D grid. Real images and hidden representations have multiple channels on both sides: an RGB photograph is a 3×h×w3 \times h \times w tensor (requiring cross-channel comparisons to detect a red-on-green boundary of equal luminance), and a hidden layer extracts dozens or hundreds of distinct feature maps in parallel.

As derived in Section 6.1, a layer with cic_\textrm{i} input channels and coc_\textrm{o} output channels maintains one ci×kh×kwc_\textrm{i} \times k_\textrm{h} \times k_\textrm{w} kernel per output channel, cross-correlating across all input channels and summing the results. In this section, we implement multi-channel convolutions, account for their parameter, FLOP, and activation-memory costs (governed by the product cicoc_\textrm{i} c_\textrm{o}), and introduce 1×11 \times 1 bottleneck convolutions.

6.4.1 Multiple Input Channels#

Let us begin with the input side. When the input contains cic_\textrm{i} channels, the kernel must supply one kh×kwk_\textrm{h}\times k_\textrm{w} filter for each input channel, giving a third-order kernel tensor of shape ci×kh×kwc_\textrm{i}\times k_\textrm{h}\times k_\textrm{w}. We cross-correlate every input channel Xc\mathbf{X}_c with its corresponding kernel slice Kc\mathbf{K}_c using two-dimensional cross-correlation (Section 6.2, computed by corr2d) and sum the cic_\textrm{i} intermediate grids:

Y=∑c=1ciXc⋆Kc.(6.4.1)\mathbf{Y} = \sum_{c=1}^{c_\textrm{i}} \mathbf{X}_c \star \mathbf{K}_c. \tag{6.4.1}

Each entry of the resulting two-dimensional output is therefore a weighted sum over the same spatial window across all input channels, combining cikhkwc_\textrm{i} k_\textrm{h} k_\textrm{w} scalar products. Figure 6.4.1 illustrates this calculation for two input channels, where the shaded upper-left output entry equals (1×1+2×2+4×3+5×4)+(0×0+1×1+3×2+4×3)=56(1\times1+2\times2+4\times3+5\times4)+(0\times0+1\times1+3\times2+4\times3)=56.

Figure 6.4.1:

Cross-correlation with two input channels: one cross-correlation per channel, then a sum.

Summing across channels is precisely what allows a kernel to compare information carried by different channels, such as color. Consider a 1×11\times 1 kernel with weight +1+1 on the red channel and −1-1 on the green channel: at every pixel it computes red minus green, producing positive values in red regions, negative values in green regions, and zero in neutral gray regions regardless of brightness. Wherever its sign flips between adjacent pixels, a red region meets a green one, even if both regions have identical luminance, in which case a grayscale brightness filter would see no edge at all.

Implementing multi-input cross-correlation translates the formula directly into Python: we call corr2d once per channel and sum the results.

def corr2d_multi_in(X, K):
    """Cross-correlate each channel of X with its channel of K and add."""
    return sum(d2l.corr2d(x, k) for x, k in zip(X, K))

Let us verify the implementation on the input and kernel tensors from Figure 6.4.1; the upper-left output entry should be 56.

X = d2l.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],
               [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])
K = d2l.tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]])

corr2d_multi_in(X, K)
tensor([[ 56.,  72.],
        [104., 120.]])

6.4.2 Multiple Output Channels#

No matter how many input channels it reads, a single multi-input kernel produces just one two-dimensional feature map (Section 6.1.4). To extract coc_\textrm{o} distinct feature maps simultaneously, a convolutional layer maintains coc_\textrm{o} such kernels, each of shape ci×kh×kwc_\textrm{i}\times k_\textrm{h}\times k_\textrm{w}. Stacking them along a new axis yields a fourth-order kernel tensor of shape co×ci×kh×kwc_\textrm{o}\times c_\textrm{i}\times k_\textrm{h}\times k_\textrm{w}, where output channel oo is given by

Yo=∑c=1ciXc⋆Ko,c,o=1,…,co.(6.4.2)\mathbf{Y}_o = \sum_{c=1}^{c_\textrm{i}} \mathbf{X}_c \star \mathbf{K}_{o,c}, \quad o = 1, \ldots, c_\textrm{o}. \tag{6.4.2}

Notice that every output channel connects to every input channel through its own kh×kwk_\textrm{h}\times k_\textrm{w} slice Ko,c\mathbf{K}_{o,c}; this dense all-to-all channel wiring is the primary driver of the layer's computational cost. Adding a scalar bias uou_o per output channel recovers the multi-channel convolutional layer derived in Section 6.1. In typical CNN architectures, the number of channels grows as spatial resolution shrinks via strides or pooling, trading fine-grained spatial layout for richer, jointly learned feature descriptions at each location.

PyTorch stores kernels channels-first as (co,ci,kh,kw)(c_\textrm{o}, c_\textrm{i}, k_\textrm{h}, k_\textrm{w}).

To implement multi-channel output cross-correlation, we iterate over the output kernels, apply corr2d_multi_in to each, and stack the resulting feature maps along axis 0.

def corr2d_multi_in_out(X, K):
    """Apply corr2d_multi_in once per output channel of K and stack."""
    return d2l.stack([corr2d_multi_in(X, k) for k in K], 0)

Let us test this function by stacking K, K + 1, and K + 2 into a kernel tensor with three output channels.

K = d2l.stack((K, K + 1, K + 2), 0)
K.shape
torch.Size([3, 2, 2, 2])

Applying corr2d_multi_in_out to our two-channel input X and the stacked 3×2×2×23 \times 2 \times 2 \times 2 kernel K produces a three-channel output tensor of shape (3,2,2)(3, 2, 2).

corr2d_multi_in_out(X, K)
tensor([[[ 56.,  72.],
         [104., 120.]],

        [[ 76., 100.],
         [148., 172.]],

        [[ 96., 128.],
         [192., 224.]]])

The first output channel matches our earlier result because its kernel is the original K. We can verify the second channel by mental arithmetic: adding 1 to every kernel weight increases each output entry by the sum of all elements in its receptive window across both input channels. For the upper-left window that sum is 20, so the second channel begins at 56+20=7656 + 20 = 76.

6.4.2.1 Parameters and Cost#

Adding channels gives a network expressive power, but it also scales up memory and computation rapidly. Including one scalar bias per output channel, a convolutional layer contains

cocikhkw+co(6.4.3)c_\textrm{o} c_\textrm{i} k_\textrm{h} k_\textrm{w} + c_\textrm{o} \tag{6.4.3}

learnable parameters. Near the input of a network, this number is modest: the 3×33\times 3 layer mapping 3 RGB channels to 64 channels in Section 6.1 has only 1,792 parameters. Deeper inside the network, however, channel counts grow large: a 3×33\times 3 layer mapping 256 channels to 256 channels requires 589,824 weights plus 256 biases.

Turning to computational cost, each output element requires one multiply-add for every weight in its output channel (cikhkwc_\textrm{i} k_\textrm{h} k_\textrm{w} in all). Across an output feature map of spatial size ho×woh_\textrm{o}\times w_\textrm{o} and coc_\textrm{o} output channels, the layer performs

howo⋅cocikhkw(6.4.4)h_\textrm{o} w_\textrm{o} \cdot c_\textrm{o} c_\textrm{i} k_\textrm{h} k_\textrm{w} \tag{6.4.4}

multiply-adds. Applied to a 56×5656\times 56 feature map, our 256-to-256 layer executes 562⋅589,824≈1.8×10956^2\cdot 589{,}824 \approx 1.8\times 10^9 multiply-adds for a single image. Both parameter count and arithmetic cost scale with the product cicoc_\textrm{i} c_\textrm{o}, meaning that doubling the width of every layer quadruples both. Because the same weights are reused at every spatial location, arithmetic cost also scales directly with the output area howoh_\textrm{o} w_\textrm{o}.

A third resource cost is just as important during training yet easily overlooked: activation memory. To compute gradients in the backward pass, the framework must retain each layer's output activations, storing howocoh_\textrm{o} w_\textrm{o} c_\textrm{o} numbers per training example (Section 5.7.3.2). Unlike parameter memory, activation memory is largest in the earliest layers, where spatial resolution is highest even though parameter counts are tiny. For example, a 3-to-64 layer producing a 224×224224\times 224 output must cache 2242⋅64≈3.2×106224^2\cdot 64 \approx 3.2\times 10^6 activations per example, nearly two thousand times more numbers than its 1,792 parameters.

6.4.3 The 1×11\times 1 Convolution#

At first glance, a 1×11\times 1 convolution (kh=kw=1k_\textrm{h} = k_\textrm{w} = 1) might look pointless: because its spatial window covers only a single pixel, it cannot detect edges, corners, or any other pattern spanning neighboring locations. When multiple channels are present, however, it performs a very useful operation, just as our red-minus-green color filter did earlier. At every spatial coordinate (i,j)(i, j), a 1×11\times 1 convolution multiplies the cic_\textrm{i}-dimensional channel vector by a shared co×cic_\textrm{o}\times c_\textrm{i} weight matrix to produce a coc_\textrm{o}-dimensional output vector. In other words, it acts as a fully connected layer applied independently at every pixel with weights tied across all spatial positions. Figure 6.4.2 depicts a 1×11\times 1 convolution mapping 3 input channels to 2 output channels while leaving height and width intact.

Figure 6.4.2:

A 1×11\times 1 convolution with three input channels and two output channels. Each output element is a linear combination of the input elements at the same position.

Because the exact same linear map is applied at every pixel, we can compute the entire 1×11\times 1 convolution with a single matrix multiplication: we reshape the input into a ci×hwc_\textrm{i}\times hw matrix, left-multiply by the co×cic_\textrm{o}\times c_\textrm{i} kernel matrix, and reshape the output back to (co,h,w)(c_\textrm{o}, h, w).

def corr2d_multi_in_out_1x1(X, K):
    """A 1x1 convolution as one matrix product."""
    c_i, h, w = X.shape
    c_o = K.shape[0]
    Y = d2l.matmul(d2l.reshape(K, (c_o, c_i)), d2l.reshape(X, (c_i, h * w)))
    return d2l.reshape(Y, (c_o, h, w))

Let us verify on random inputs that this matrix-multiplication formulation agrees with corr2d_multi_in_out.

X = d2l.normal(0, 1, (3, 3, 3))
K = d2l.normal(0, 1, (2, 3, 1, 1))
Y1 = corr2d_multi_in_out_1x1(X, K)
Y2 = corr2d_multi_in_out(X, K)
float(d2l.reduce_sum(d2l.abs(Y1 - Y2)))
0.0

As expected, the two results match up to floating-point rounding error.

Why are 1×11\times 1 convolutions so ubiquitous in modern architectures? Their main strength is adjusting channel dimensionality cheaply so that expensive spatial convolutions can operate on narrower representations. Return to our 256-to-256 3×33\times 3 layer. Instead of applying 3×33\times 3 kernels directly to all 256 channels, we can use a 1×11\times 1 convolution to project 256 channels down to 64, apply the 3×33\times 3 convolution across those 64 channels, and use a second 1×11\times 1 convolution to expand back to 256. Together, the three layers use only 16,384+36,864+16,384=69,63216{,}384 + 36{,}864 + 16{,}384 = 69{,}632 weights instead of 589,824589{,}824, a reduction of roughly 8.5×8.5\times in both parameters and multiply-adds. Such a bottleneck restricts intermediate spatial mixing to a 64-channel subspace, a tradeoff that architectures such as ResNet (Section 7.4) happily make in exchange for much greater depth. Placing an activation function after a 1×11\times 1 convolution turns it into a tiny nonlinear MLP evaluated at every pixel (Lin et al., 2013); without a nonlinearity, consecutive linear convolutions would simply collapse into a single linear map.

Two other architectural mechanisms reduce the cicoc_\textrm{i} c_\textrm{o} factor by restricting which input channels feed into each output channel: grouped convolutions, popularized by ResNeXt (Section 7.4.5.1), and depthwise-separable convolutions, which underpin lightweight mobile models (Section 7.5.1.1). We will introduce each in the next chapter as we build the architectures that rely on them.

Notice that channels alone leave one basic property unchanged: convolutional outputs still shift pixel-for-pixel whenever the input shifts. In Section 6.5, we introduce pooling layers to summarize local neighborhoods and build tolerance to small spatial shifts.

6.4.4 Summary#

To handle multi-channel inputs, a convolutional layer cross-correlates each input channel with its own spatial kernel and sums the results, allowing a single filter to integrate cues across channels such as color. To produce coc_\textrm{o} output feature maps, the layer stacks coc_\textrm{o} such multi-input kernels into a tensor of shape co×ci×kh×kwc_\textrm{o}\times c_\textrm{i}\times k_\textrm{h}\times k_\textrm{w}, incurring cocikhkw+coc_\textrm{o} c_\textrm{i} k_\textrm{h} k_\textrm{w} + c_\textrm{o} parameters and howococikhkwh_\textrm{o} w_\textrm{o} c_\textrm{o} c_\textrm{i} k_\textrm{h} k_\textrm{w} multiply-adds (both proportional to cicoc_\textrm{i} c_\textrm{o}), while training must also store howocoh_\textrm{o} w_\textrm{o} c_\textrm{o} activations per example. A 1×11\times 1 convolution acts as a shared fully connected layer at every pixel, letting architectures mix channels and construct parameter- and compute-efficient bottlenecks.

6.4.5 Exercises#

  1. Composition of convolutions. Two convolutional layers with stride 1, no padding, and no nonlinearity in between have kernels of shape cm×ci×k1×k1c_\textrm{m} \times c_\textrm{i} \times k_1 \times k_1 and co×cm×k2×k2c_\textrm{o} \times c_\textrm{m} \times k_2 \times k_2.

    1. Prove that their composition is a single convolution, and give the shape of its kernel.
    2. Compare the number of weights of the pair with that of the single convolution. For which intermediate width cmc_\textrm{m} is the pair cheaper?
    3. As Section 6.2 showed, three stacked single-channel 3×33 \times 3 kernels have a 7×77 \times 7 receptive field. Decide whether every single-channel 7×77 \times 7 kernel is the composition of three 3×33 \times 3 kernels, and justify the answer.
  2. Three costs, three layers. A network for 224×224224\times 224 RGB images begins with four 3×33\times 3 convolutions with padding 1: from 3 to 64 channels at stride 1, from 64 to 128 at stride 2, from 128 to 128 at stride 1, and from 128 to 256 at stride 2.

    1. For each layer give the output shape, the number of weights, the number of multiply-adds per image, and the number of output values that training must keep for the backward pass.
    2. Which layer has the most weights, which performs the most multiply-adds, and which keeps the most output values? Explain why these are three different layers.
    3. The images are replaced by 448×448448\times 448 ones. Which of the three costs change, and by what factor?
  3. [code] Multi-channel im2col. Extend the patch matrix of Section 6.2.3 to several input and output channels. Rebuild the two-channel X of Figure 6.4.1 and the three-output-channel K of Section 6.4.2, since later cells of this section overwrite both. Build the patch matrix, whose rows are input patches of shape ci×kh×kwc_\textrm{i} \times k_\textrm{h} \times k_\textrm{w} flattened in that order, and arrange K into a cikhkw×coc_\textrm{i} k_\textrm{h} k_\textrm{w} \times c_\textrm{o} kernel matrix whose rows follow the same order. Confirm that their product, rearranged into the shape of the output, reproduces corr2d_multi_in_out(X, K).

    Adapted from Simon Prince, Understanding Deep Learning, Problems 10.6 and 10.7.

Discussions