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 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 input channels and output channels maintains one 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 ), and introduce bottleneck convolutions.
6.4.1 Multiple Input Channels#
Let us begin with the input side. When the input contains
channels, the kernel must supply one filter
for each input channel, giving a third-order kernel tensor of shape
. We cross-correlate
every input channel with its corresponding kernel slice
using two-dimensional cross-correlation (Section 6.2,
computed by corr2d) and sum the intermediate grids:
Each entry of the resulting two-dimensional output is therefore a weighted sum over the same spatial window across all input channels, combining scalar products. Figure 6.4.1 illustrates this calculation for two input channels, where the shaded upper-left output entry equals .
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 kernel with weight on the red channel and 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 distinct feature maps simultaneously, a convolutional layer maintains such kernels, each of shape . Stacking them along a new axis yields a fourth-order kernel tensor of shape , where output channel is given by
Notice that every output channel connects to every input channel through its own slice ; this dense all-to-all channel wiring is the primary driver of the layer's computational cost. Adding a scalar bias 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 .
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.shapetorch.Size([3, 2, 2, 2])
Applying corr2d_multi_in_out to our two-channel input X and the stacked
kernel K produces a three-channel output
tensor of shape .
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 .
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
learnable parameters. Near the input of a network, this number is modest: the 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 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 ( in all). Across an output feature map of spatial size and output channels, the layer performs
multiply-adds. Applied to a feature map, our 256-to-256 layer executes multiply-adds for a single image. Both parameter count and arithmetic cost scale with the product , 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 .
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 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 output must cache activations per example, nearly two thousand times more numbers than its 1,792 parameters.
6.4.3 The Convolution#
At first glance, a convolution () 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 , a convolution multiplies the -dimensional channel vector by a shared weight matrix to produce a -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 convolution mapping 3 input channels to 2 output channels while leaving height and width intact.
A 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 convolution with a single matrix multiplication: we reshape the input into a matrix, left-multiply by the kernel matrix, and reshape the output back to .
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 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 layer. Instead of applying kernels directly to all 256 channels, we can use a convolution to project 256 channels down to 64, apply the convolution across those 64 channels, and use a second convolution to expand back to 256. Together, the three layers use only weights instead of , a reduction of roughly 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 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 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 output feature maps, the layer stacks such multi-input kernels into a tensor of shape , incurring parameters and multiply-adds (both proportional to ), while training must also store activations per example. A 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#
-
Composition of convolutions. Two convolutional layers with stride 1, no padding, and no nonlinearity in between have kernels of shape and .
- Prove that their composition is a single convolution, and give the shape of its kernel.
- Compare the number of weights of the pair with that of the single convolution. For which intermediate width is the pair cheaper?
- As Section 6.2 showed, three stacked single-channel kernels have a receptive field. Decide whether every single-channel kernel is the composition of three kernels, and justify the answer.
-
Three costs, three layers. A network for RGB images begins with four 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.
- 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.
- 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.
- The images are replaced by ones. Which of the three costs change, and by what factor?
-
[code] Multi-channel im2col. Extend the patch matrix of Section 6.2.3 to several input and output channels. Rebuild the two-channel
Xof Figure 6.4.1 and the three-output-channelKof Section 6.4.2, since later cells of this section overwrite both. Build the patch matrix, whose rows are input patches of shape flattened in that order, and arrangeKinto a kernel matrix whose rows follow the same order. Confirm that their product, rearranged into the shape of the output, reproducescorr2d_multi_in_out(X, K).Adapted from Simon Prince, Understanding Deep Learning, Problems 10.6 and 10.7.