Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Multi-channel convolutions and 1×1 convs

P5.535 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

Real images have several channels and every layer of a CNN passes on a stack of feature maps, so the kernels of a CNN are blocks that read all the channels at once. The shapes and counts in this lesson are what you read off every convolutional layer you meet.

  • A CNN stacks layers of this kind: the first layer reads the three colour channels and each later layer reads the maps of the layer before. (P5.7: Build a CNN)
  • ResNet bottleneck blocks use 1×1 convolutions to shrink and then grow the number of channels cheaply, and Inception modules use them to shrink channels before larger kernels. (P5.9: The CNN architecture tour)
  • A projection shortcut, which makes a residual connection fit when the number of channels changes, is a 1×1 convolution. (P4.20: Residual connections)

Before this: Images as tensors, The convolution operation, The forward pass in matrix form

After this lesson you can

  • Explain why a kernel for a colour image is a block with one slice per input channel, and compute one output value as the sum over all channels of the window-times-kernel products, plus one bias
  • State the shapes in PyTorch, weight (Cout,Cin,k,k)(C_{\text{out}},C_{\text{in}},k,k) and bias (Cout,)(C_{\text{out}},), and count the parameters Cout(Cink2+1)C_{\text{out}}(C_{\text{in}}k^2+1) and the multiply-adds of a layer
  • Show that a 1×1 convolution is the same small matrix applied to the channel values of every pixel, and name what it is used for
  • Describe grouped and depthwise-separable convolutions and how much they save

P5.2 ended with a layer of 32 kernels on a greyscale 28×2828\times28 image: 32⋅10=32032\cdot10=320 learned numbers and 32 feature maps of size 26×2626\times26. Those maps are not one picture any more. They are a stack of 32 pictures, a tensor of shape (32,26,26)(32,26,26) in the (C,H,W)(C,H,W) order. The next layer has to read all 32 of them. A 3×33\times3 kernel from P5.2 has only 9 weights and looks at one grid, so it cannot.

A colour photo has the same problem from the start: three grids (red, green, blue) for every image. This lesson shows how a kernel grows into a block that reads every channel, how many numbers that costs, and how a block of size 1×11\times1 turns out to be useful too.

Scope: valid mode and stride 1, as in P5.2 (padding, stride and dilation are in P5.4). Pooling and what a unit can “see” are P5.6, building a network is P5.7 and the named architectures are P5.9.

A kernel is a block

A colour image is a tensor with three channels, one grid of numbers each (P5.1). In this lesson a tensor of one image has shape (C,H,W)(C,H,W), the PyTorch order, and a batch has shape (N,C,H,W)(N,C,H,W). The channel count of the input is written CinC_{\text{in}}.

Why must one kernel read all the channels? Because the patterns that matter often live across them. A yellow pixel is bright in red and green and dark in blue. Looking at red alone cannot tell it from white. So a kernel for a colour image has one slice for each input channel: a 3×33\times3 kernel for an RGB image holds 3×3×3=273\times3\times3=27 weights, shaped Cin×k×kC_{\text{in}}\times k\times k.

At one position, the window is a block of pixels too: a k×kk\times k patch from every channel. The rule is P5.2’s rule, repeated for each channel and then added up:

  1. Multiply each channel’s window with the matching slice of the kernel, element by element.
  2. Add all the products, from all channels, into one number.
  3. Add the bias.

That gives one output value. For Cin=3C_{\text{in}}=3 and k=3k=3, it is 2727 products added together. The kernel slides over height and width exactly as before. It does not slide along the channels, because it already covers all of them. A greyscale image has Cin=1C_{\text{in}}=1, and then the block is the single slice of P5.2.

A small example by hand

Take an input with two channels of size 3×33\times3 (a tensor of shape (2,3,3)(2,3,3)) and 2×22\times2 kernels.

X0=(120013211)X1=(201110032)\begin{aligned} \mathbf{X}_0&=\begin{pmatrix}1&2&0\\0&1&3\\2&1&1\end{pmatrix}\\[4pt] \mathbf{X}_1&=\begin{pmatrix}2&0&1\\1&1&0\\0&3&2\end{pmatrix} \end{aligned}

The first kernel block, which makes output channel 0, has one 2×22\times2 slice per input channel and a bias of 11:

K0,0=(100−1),K0,1=(0110),b0=1.\begin{aligned} \mathbf{K}_{0,0}&=\begin{pmatrix}1&0\\0&-1\end{pmatrix},\\[4pt] \mathbf{K}_{0,1}&=\begin{pmatrix}0&1\\1&0\end{pmatrix},\quad b_0=1. \end{aligned}

(The first index of Ko,c\mathbf{K}_{o,c} is the output channel oo, the second is the input channel cc.)

Top-left position. The window covers rows 0 to 1 and columns 0 to 1 in both channels. Multiply each channel with its own slice:

channel 0:(1201)⊙(100−1)=(100−1), sum 0channel 1:(2011)⊙(0110)=(0010), sum 1\begin{aligned} \text{channel 0:}&\quad\begin{pmatrix}1&2\\0&1\end{pmatrix}\odot\begin{pmatrix}1&0\\0&-1\end{pmatrix}\\ &\quad=\begin{pmatrix}1&0\\0&-1\end{pmatrix},\ \text{sum }0\\[8pt] \text{channel 1:}&\quad\begin{pmatrix}2&0\\1&1\end{pmatrix}\odot\begin{pmatrix}0&1\\1&0\end{pmatrix}\\ &\quad=\begin{pmatrix}0&0\\1&0\end{pmatrix},\ \text{sum }1 \end{aligned}

(⊙\odot means multiply element by element.) The output value is the two sums plus the bias: 0+1+1=20+1+1=2. Sliding to the other three positions gives the whole map of output channel 0. A second kernel block, with its own slices K1,0=(1111)\mathbf{K}_{1,0}=\begin{pmatrix}1&1\\1&1\end{pmatrix}, K1,1=(−100−1)\mathbf{K}_{1,1}=\begin{pmatrix}-1&0\\0&-1\end{pmatrix} and bias b1=0b_1=0, gives output channel 1. At the top-left position its sums are 44 and −3-3, so the value is 11. The two maps are

Y0=(2214),Y1=(1603).\mathbf{Y}_0=\begin{pmatrix}2&2\\1&4\end{pmatrix},\qquad \mathbf{Y}_1=\begin{pmatrix}1&6\\0&3\end{pmatrix}.

The input volume (2,3,3)(2,3,3) became an output volume (2,2,2)(2,2,2). Each map has the size 3−2+1=23-2+1=2 from P5.2. The number of output channels is a free choice: it is the number of kernel blocks, and it has nothing to do with the number of input channels.

Output channels (kernel blocks):
ch 1ch 0120013211input volume→out 1out 02214output volume

Front slice = channel 0; the output slice with numbers is output 0. The window block spans every input channel. Each output slice is the feature map of one kernel block.

Show kernel block:
Channel 0: window × kernel slice
1×112×000×001×−1−1
sum: 0
Channel 1: window × kernel slice
2×000×101×111×00
sum: 1

Output 0, position 1 of 4 (row 0, column 0): 0 + 1 + bias 1 = 2.

Feature map of output 0, 2×2. Tap a cell, or use the arrow keys, to move the window.

Weights: 2 × 2 × 2 × 2 = 16, plus 2 biases = 18 learned numbers. Output volume: 2 × 2 × 2.

A kernel block sweeping through an input volume. Left in the drawing: the input volume, two 3 by 3 slices stacked (the front slice is channel 0, with its numbers). The blue frame and the dashed edges are the window block: a 2 by 2 patch of every channel at once. Right: the output volume, one 2 by 2 slice per kernel block. Under the drawing, choose which kernel block to look at, and see the products of each input channel, the sum of each channel, and the output value with the bias. Tap a cell of the feature map, use its arrow keys, or press the previous and next buttons to move the window. The buttons at the top add output channels: each one adds a kernel block and a slice of the output, and the parameter count under the widget grows with it.

Things to try. Step through the four positions with output 0 selected and check 2,2,1,42,2,1,4. Switch to 3 output channels: the first two maps do not change, and a third map appears. Press Output 2 under “Show kernel block” to read its numbers (the drawing shows numbers for output 0 only). Count the weights as you add blocks: each block adds 2⋅2⋅2+1=92\cdot2\cdot2+1=9 learned numbers.

The formula, and what a layer has

Write Xc,i,jX_{c,i,j} for the pixel at row ii and column jj of input channel cc (indices from 0). In P5.2 the kernel entries were Ka,cK_{a,c} with cc as the column. Now cc is the channel, so the row and column inside the kernel are called uu and vv, and the kernel gets two more indices, the output channel oo and the input channel cc: Ko,c,u,vK_{o,c,u,v}. The output is

Yo,i,j=bo+∑c=0Cin−1 ∑u=0k−1 ∑v=0k−1Ko,c,u,v Xc, i+u, j+v.\begin{aligned} Y_{o,i,j}=b_o&+\sum_{c=0}^{C_{\text{in}}-1}\ \sum_{u=0}^{k-1}\ \sum_{v=0}^{k-1}\\ &\qquad K_{o,c,u,v}\,X_{c,\,i+u,\,j+v}. \end{aligned}

Read it from the inside out: for one channel, P5.2’s sliding sum; then add over channels; then add the bias bob_o of that output channel. With Cin=1C_{\text{in}}=1 it is exactly P5.2’s formula. The map has size (H−k+1)×(W−k+1)(H-k+1)\times(W-k+1) for every oo.

Shapes. For a layer with CinC_{\text{in}} input and CoutC_{\text{out}} output channels:

  • input (N,Cin,H,W)(N,C_{\text{in}},H,W), output (N,Cout,H′,W′)(N,C_{\text{out}},H',W') with H′=H−k+1H'=H-k+1 and W′=W−k+1W'=W-k+1 in valid mode;
  • weight (Cout,Cin,k,k)(C_{\text{out}},C_{\text{in}},k,k), one Cin×k×kC_{\text{in}}\times k\times k block for each output channel;
  • bias (Cout,)(C_{\text{out}},), one number per output channel, added at every position of that channel’s map.

The NN images in a batch all use the same weights, and the layer is applied to each image on its own. The input’s channel count must match the kernel: a layer built for 3 channels cannot be applied to a tensor with 32. The output volume of one layer is the input volume of the next, so the next layer’s CinC_{\text{in}} is this layer’s CoutC_{\text{out}}.

Parameters. Each block has Cink2C_{\text{in}}k^2 weights and one bias, and there are CoutC_{\text{out}} blocks:

parameters=Cout (Cink2+1).\text{parameters}=C_{\text{out}}\,(C_{\text{in}}k^2+1).

The widget’s layer has 2⋅(2⋅4+1)=182\cdot(2\cdot4+1)=18. P5.2’s layer, 32 kernels on a grey image, has 32⋅(1⋅9+1)=32032\cdot(1\cdot9+1)=320. A layer from a colour image to 32 maps with 3×33\times3 kernels has 32⋅(3⋅9+1)=89632\cdot(3\cdot9+1)=896. A layer that reads those 32 maps and makes 64 has 64⋅(32⋅9+1)=18,49664\cdot(32\cdot9+1)=18{,}496. As in P5.2, none of these depends on the height and width of the image.

Multiply-adds. Each output value needs Cink2C_{\text{in}}k^2 multiplications (the bias addition is not counted). There are CoutH′W′C_{\text{out}}H'W' output values, so

multiply-adds=H′ W′ Cout Cin k2.\text{multiply-adds}=H'\,W'\,C_{\text{out}}\,C_{\text{in}}\,k^2.

For P5.2’s layer, 26⋅26⋅32⋅1⋅9=194,68826\cdot26\cdot32\cdot1\cdot9=194{,}688, which is the 6,0846{,}084 of one kernel times 32. For the colour layer on a 32×3232\times32 image (H′=W′=30H'=W'=30): 30⋅30⋅32⋅27=777,60030\cdot30\cdot32\cdot27=777{,}600. The parameter count does not grow with the image, but the amount of work does.

Go deeper Counting multiply-adds and FLOPs

Sources count the work of a layer in different ways. A multiply-add (one multiplication and one addition, often called a MAC) is counted as one unit above. Many sources count the multiplication and the addition separately, so the same layer is twice as many FLOPs (floating-point operations). Read which convention a table uses before you compare two numbers. The totals also leave out the bias additions and the activation, which are small next to Cink2C_{\text{in}}k^2 per output.

The output volume also has to be stored, because backpropagation (P4.8) needs it. Its size is CoutH′W′C_{\text{out}}H'W' numbers per image, which is a different cost from the number of parameters.

What a channel means

In the first layer, the input channels are red, green and blue, and a kernel’s three slices decide what pattern of colour and brightness it responds to. If the three slices of a kernel are identical, the output depends only on the sum of the three colours at each pixel (a brightness pattern), and colour differences are ignored.

In a deeper layer, input channel cc is the feature map made by kernel cc of the layer before. It is not a colour. It says “how much of the pattern that kernel looks for is here”. A kernel of the second layer reads all of these maps at the same time, so it can combine several simple patterns into a more complicated one. Early layers of trained CNNs tend to respond to edges and colours and later layers to larger and more specific patterns. P5.8 shows real examples, and P5.7 trains a network so you can look at one. In many CNNs the number of channels grows from layer to layer (for example 33, then 3232, then 6464), while the height and width shrink (P5.4, P5.6).

The layer is not named “2D” because of its channels. It is 2D because the kernel slides along two axes, height and width. (There is a 3D convolution that also slides along a third axis, such as time in a video. It is outside this course.)

The 1×1 convolution

Take k=1k=1. A 1×11\times1 kernel has one weight per input channel, so each of the CoutC_{\text{out}} kernels is just CinC_{\text{in}} numbers. At each pixel it multiplies the pixel’s channel values by those weights and adds them. There is no neighbourhood, so it cannot see edges or shapes. What it does is mix channels at each pixel.

Collect the pixel’s channel values in a vector xi,j=(X0,i,j,…,XCin−1,i,j)\mathbf{x}_{i,j}=(X_{0,i,j},\dots,X_{C_{\text{in}}-1,i,j}). Put the weights in a matrix W\mathbf{W} of shape Cout×CinC_{\text{out}}\times C_{\text{in}} with Wo,c=Ko,c,0,0W_{o,c}=K_{o,c,0,0}, and the biases in b\mathbf{b}. Then the formula above reads

yi,j=W xi,j+b.\mathbf{y}_{i,j}=\mathbf{W}\,\mathbf{x}_{i,j}+\mathbf{b}.

That is the dense layer of P4.5, applied to the channel vector of every pixel with the same W\mathbf{W} and b\mathbf{b}. A 1×11\times1 convolution is a linear layer that shares its weights across all positions.

Example: three channels, a 2×22\times2 image and two output channels, with W=(10−1211)\mathbf{W}=\begin{pmatrix}1&0&-1\\2&1&1\end{pmatrix} and b=(0,−1)\mathbf{b}=(0,-1). The top-left pixel has channel values (3,5,2)(3,5,2):

(10−1211)(352)+(0−1)=(3−26+5+2)+(0−1)=(112).\begin{aligned} &\begin{pmatrix}1&0&-1\\2&1&1\end{pmatrix}\begin{pmatrix}3\\5\\2\end{pmatrix}+\begin{pmatrix}0\\-1\end{pmatrix}\\ &\quad=\begin{pmatrix}3-2\\6+5+2\end{pmatrix}+\begin{pmatrix}0\\-1\end{pmatrix}\\ &\quad=\begin{pmatrix}1\\12\end{pmatrix}. \end{aligned}

The same matrix is applied to the other three pixels, and the output has the same height and width as the input, 2×22\times2, because H−1+1=HH-1+1=H.

Input: 3 channels of 2×2. Choose a pixel:
10−1211
×
352
+
0−1
=
112

Pixel (row 0, column 0) has channel values (3, 5, 2). Output 0 = 1·3 + 0·5 + −1·2 + 0 = 1. Output 1 = 2·3 + 1·5 + 1·2 + −1 = 12.

Output maps, same 2×2 size as the input. The selected pixel is outlined.
Output 0
1−202
Output 1
12227

Every pixel uses the same 2×3 matrix. No pixel looks at its neighbours.

A 1 by 1 convolution on an image with 3 channels and 2 by 2 pixels. Choose a pixel with the buttons. The same 2 by 3 matrix, shown at the left of the equation, is multiplied with the three channel values of that pixel (blue), the bias vector is added, and the result (blue) is the pair of values that the two output maps have at that pixel. The output maps are shown below with the chosen pixel outlined.

Running the Code tab confirms this on random numbers: a Conv2d with k=1k=1 gives the same result as an nn.Linear applied to the tensor after moving the channel axis last. A simple use you may already know is turning RGB into greyscale: one output channel with weights (0.299, 0.587, 0.114)(0.299,\,0.587,\,0.114) is a 1×11\times1 convolution with Cout=1C_{\text{out}}=1 (the greyscale weights of P5.1).

What it is used for.

  • Changing the number of channels cheaply. A 1×11\times1 layer from CinC_{\text{in}} to CoutC_{\text{out}} has Cout(Cin+1)C_{\text{out}}(C_{\text{in}}+1) parameters: 2,1122{,}112 from 32 to 64 channels, against 18,49618{,}496 for a 3×33\times3 layer.
  • Bottlenecks. Before an expensive 3×33\times3 layer, a 1×11\times1 layer squeezes the channels down. After it, another 1×11\times1 layer expands them again. A block with 256256 channels, squeezed to 6464, a 3×33\times3 layer on 6464 channels and expanded back to 256256 has 16,448+36,928+16,640=70,01616{,}448+36{,}928+16{,}640=70{,}016 parameters, against 590,080590{,}080 for one 3×33\times3 layer from 256 to 256 channels. That is about 88 times fewer (counted with biases; real ResNet convolutions have none because a normalization layer follows, P4.19). ResNet’s bottleneck blocks have exactly this shape, and Inception modules use 1×11\times1 convolutions to shrink the channels before their larger kernels (P5.9 tours both).
  • Matching shapes. A residual connection adds two tensors, which must have the same shape (P4.20). When a block changes the channel count, a 1×11\times1 convolution on the shortcut makes the shapes agree.
  • Mixing channels after channels were treated separately, as in the box below.
Go deeper Grouped and depthwise-separable convolutions

A normal kernel reads all CinC_{\text{in}} channels. In a grouped convolution with gg groups, the input channels and the output channels are each split into gg equal groups, and every output channel reads only the input channels of its own group. Both CinC_{\text{in}} and CoutC_{\text{out}} must be divisible by gg. Each kernel then has Cin/gC_{\text{in}}/g slices, so

parameters=Cout(Cingk2+1),\text{parameters}=C_{\text{out}}\left(\frac{C_{\text{in}}}{g}k^2+1\right),

and the weight shape in PyTorch is (Cout, Cin/g, k, k)(C_{\text{out}},\,C_{\text{in}}/g,\,k,\,k). For 32 to 64 channels with 3×33\times3 kernels, g=4g=4 gives 64⋅(8⋅9+1)=4,67264\cdot(8\cdot9+1)=4{,}672 against 18,49618{,}496 for g=1g=1. The multiply-adds shrink by the same factor gg. The groups cannot see each other, so something else has to mix the channels.

The extreme case g=Cing=C_{\text{in}} (with CoutC_{\text{out}} a multiple of it, usually equal) is a depthwise convolution: one k×kk\times k filter per channel, and no mixing between channels at all. Follow it with a 1×11\times1 convolution (also called a pointwise convolution), which does the mixing, and you have a depthwise-separable convolution. For 32 to 64 channels:

32⋅(9+1)⏟depthwise 3×3+64⋅(32+1)⏟pointwise 1×1=320+2,112=2,432\begin{aligned} &\underbrace{32\cdot(9+1)}_{\text{depthwise }3\times3}+\underbrace{64\cdot(32+1)}_{\text{pointwise }1\times1}\\ &\quad=320+2{,}112=2{,}432 \end{aligned}

parameters, against 18,49618{,}496 for the plain 3×33\times3 layer, about 7.67.6 times fewer. Without biases the counts are 2,3362{,}336 against 18,43218{,}432, a ratio of exactly 1Cout+1k2=164+19≈0.127\frac{1}{C_{\text{out}}}+\frac{1}{k^2}=\frac{1}{64}+\frac{1}{9}\approx0.127. The price is that the two steps cannot represent every function that one full layer can. Networks for phones, such as MobileNet (P5.9), are built from such pairs.

Depth: three ways to see it

Intuition

Think of a stack of transparent sheets, one per channel, each printed with a grid of numbers. The kernel is a stack of small stencils, one per sheet. You hold the stack of stencils over the stack of sheets at one spot, multiply what you see on each sheet by the stencil’s number, and add everything into one score. One stack of stencils gives one new sheet of scores. With ten stacks of stencils you get ten new sheets.

The picture breaks in two places. Each sheet has its own stencil: the slices of a kernel are different numbers, so the layer can treat red and green differently. And the new sheets are not pictures of the input: in a deeper layer they say where patterns were found.

A 1×11\times1 convolution is a stencil of one hole. It looks through one spot of every sheet and mixes what it sees.

Math

The layer is a sum over input channels of single-channel convolutions,

Yo=bo+∑cKo,c⋆Xc,\mathbf{Y}_o=b_o+\sum_{c}\mathbf{K}_{o,c}\star\mathbf{X}_c,

where ⋆\star is the single-channel valid cross-correlation of P5.2, and Ko,c\mathbf{K}_{o,c} is the k×kk\times k slice of kernel block oo for channel cc.

Gradient. As in P5.2, a weight’s gradient adds up over every position where it was used, and now it touches only its own input channel: ∂L/∂Ko,c,u,v=∑i,jGo,i,jXc,i+u,j+v\partial L/\partial K_{o,c,u,v}=\sum_{i,j}G_{o,i,j}X_{c,i+u,j+v}, where Go,i,j=∂L/∂Yo,i,jG_{o,i,j}=\partial L/\partial Y_{o,i,j}. The bias gradient is ∂L/∂bo=∑i,jGo,i,j\partial L/\partial b_o=\sum_{i,j}G_{o,i,j}.

Code

The worked example in PyTorch. Tensors are (N,C,H,W)(N,C,H,W), and the weight is (Cout,Cin,k,k)(C_{\text{out}},C_{\text{in}},k,k).

import torch
import torch.nn as nn

x = torch.tensor([[[1, 2, 0], [0, 1, 3], [2, 1, 1]],
                  [[2, 0, 1], [1, 1, 0], [0, 3, 2]]],
                 dtype=torch.float32)
x = x.reshape(1, 2, 3, 3)       # (N, C_in, H, W)

conv = nn.Conv2d(in_channels=2, out_channels=2, kernel_size=2)
with torch.no_grad():
    conv.weight[0, 0] = torch.tensor([[1., 0.], [0., -1.]])
    conv.weight[0, 1] = torch.tensor([[0., 1.], [1., 0.]])
    conv.weight[1, 0] = torch.tensor([[1., 1.], [1., 1.]])
    conv.weight[1, 1] = torch.tensor([[-1., 0.], [0., -1.]])
    conv.bias[:] = torch.tensor([1., 0.])

y = conv(x)
print("weight (out,in,k,k):", tuple(conv.weight.shape))
print("bias (out,):", tuple(conv.bias.shape))
print("output (N,C,H,W):", tuple(y.shape))
print(y[0, 0].detach().int())
print(y[0, 1].detach().int())
print("parameters:", sum(p.numel() for p in conv.parameters()))

# 1x1 convolution = the same matrix at every pixel
c1 = nn.Conv2d(3, 2, kernel_size=1)
img = torch.randn(1, 3, 4, 5)
lin = nn.Linear(3, 2)
with torch.no_grad():
    lin.weight.copy_(c1.weight[:, :, 0, 0])
    lin.bias.copy_(c1.bias)
y1 = c1(img)
y2 = lin(img.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
print("1x1 conv:", tuple(img.shape), "->", tuple(y1.shape))
print("same as Linear per pixel:", torch.allclose(y1, y2, atol=1e-6))

# parameter counts (groups=g splits the channels)
for cin, cout, k, g in [(1, 32, 3, 1), (32, 64, 3, 1),
                        (32, 64, 3, 4), (32, 32, 3, 32), (32, 64, 1, 1)]:
    c = nn.Conv2d(cin, cout, k, groups=g)
    n = sum(p.numel() for p in c.parameters())
    print(cin, cout, k, "groups", g, "->", n)

Output from a local run with PyTorch 2.9.1:

weight (out,in,k,k): (2, 2, 2, 2)
bias (out,): (2,)
output (N,C,H,W): (1, 2, 2, 2)
tensor([[2, 2],
        [1, 4]], dtype=torch.int32)
tensor([[1, 6],
        [0, 3]], dtype=torch.int32)
parameters: 18
1x1 conv: (1, 3, 4, 5) -> (1, 2, 4, 5)
same as Linear per pixel: True
1 32 3 groups 1 -> 320
32 64 3 groups 1 -> 18496
32 64 3 groups 4 -> 4672
32 32 3 groups 32 -> 320
32 64 1 groups 1 -> 2112

The layer gives the hand-computed maps Y0\mathbf{Y}_0 and Y1\mathbf{Y}_1, and the parameter counts agree with Cout(Cin/g⋅k2+1)C_{\text{out}}(C_{\text{in}}/g\cdot k^2+1). The depthwise layer (32 groups) has weight shape (32,1,3,3)(32,1,3,3).

Try it in Python

The first cell is the hand calculation in NumPy, with a loop over output channels and positions. The second applies a 1×11\times1 convolution as one matrix product and counts the parameters of the layers in this lesson.

A multi-channel convolution by hand

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell prints the two maps worked out above, the channel sums 00 and 11 at the top-left position, and 1818 parameters. Change b or a slice of K and predict the maps first.

1×1 convolutions and parameter counts

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell prints the maps (1−202)\begin{pmatrix}1&-2\\0&2\end{pmatrix} and (12227)\begin{pmatrix}12&2\\2&7\end{pmatrix}, the pixel (3,5,2)(3,5,2) mapped to (1,12)(1,12), and the counts 590,080590{,}080, 70,01670{,}016, 18,49618{,}496 and 2,4322{,}432.

Common mistakes

Quiz

Check your understanding

  1. A layer is nn.Conv2d(16, 32, 3), with biases. How many learned numbers does it have?

  2. What is the shape of the weight tensor of nn.Conv2d(3, 8, 5) in PyTorch?

  3. A batch of shape (N,3,32,32)(N,3,32,32) goes through nn.Conv2d(3, 16, 3), valid mode, stride 1. What is the shape of the output?

  4. A 1×11\times1 convolution with 64 input channels and 16 output channels is applied to a tensor of shape (N,64,H,W)(N,64,H,W). What does it do?

  5. A depthwise 3×33\times3 convolution on 32 channels uses one filter per channel and no biases. How many weights does it have?

Exercises

  1. A kernel block has two 2×22\times2 slices, (1001)\begin{pmatrix}1&0\\0&1\end{pmatrix} for channel 0 and (2211)\begin{pmatrix}2&2\\1&1\end{pmatrix} for channel 1, and a bias of −3-3. The window is (1234)\begin{pmatrix}1&2\\3&4\end{pmatrix} in channel 0 and (0110)\begin{pmatrix}0&1\\1&0\end{pmatrix} in channel 1. What is the output value?
    Show answerChannel 0: 1⋅1+2⋅0+3⋅0+4⋅1=51\cdot1+2\cdot0+3\cdot0+4\cdot1=5. Channel 1: 0⋅2+1⋅2+1⋅1+0⋅1=30\cdot2+1\cdot2+1\cdot1+0\cdot1=3. Add both sums and the bias: 5+3−3=55+3-3=5.
  2. A 3×32×323\times32\times32 image (a tensor of shape (C,H,W)(C,H,W)) goes through nn.Conv2d(3, 16, 3), valid mode, stride 1. What are the output shape, the number of learned numbers and the number of multiply-adds?
    Show answerThe output is (16,30,30)(16,30,30), because 32−3+1=3032-3+1=30. Parameters: 16⋅(3⋅9+1)=44816\cdot(3\cdot9+1)=448. Multiply-adds: 30⋅30⋅16⋅27=388,80030\cdot30\cdot16\cdot27=388{,}800.
  3. With the matrix W=(10−1211)\mathbf{W}=\begin{pmatrix}1&0&-1\\2&1&1\end{pmatrix} and bias b=(0,−1)\mathbf{b}=(0,-1) of this lesson, what does the 1×11\times1 convolution give for a pixel with channel values (4,1,2)(4,1,2)?
    Show answerThe first output is 1⋅4+0⋅1−1⋅2+0=21\cdot4+0\cdot1-1\cdot2+0=2. The second is 2⋅4+1⋅1+1⋅2−1=102\cdot4+1\cdot1+1\cdot2-1=10. So the output vector is (2,10)(2,10).
  4. A block squeezes 128 channels to 32 with a 1×11\times1 convolution, applies a 3×33\times3 convolution from 32 to 32, and expands back to 128 with another 1×11\times1 convolution. Count all parameters (with biases) and compare them with one 3×33\times3 layer from 128 to 128.
    Show answer128128 to 3232: 32⋅129=4,12832\cdot129=4{,}128. The 3×33\times3 layer: 32⋅(32⋅9+1)=9,24832\cdot(32\cdot9+1)=9{,}248. 3232 to 128128: 128⋅33=4,224128\cdot33=4{,}224. Total 17,60017{,}600. The single layer has 128⋅(128⋅9+1)=147,584128\cdot(128\cdot9+1)=147{,}584, about 8.4 times more.
  5. Compare a plain 3×33\times3 layer from 64 to 128 channels with a depthwise 3×33\times3 layer followed by a 1×11\times1 layer from 64 to 128 (both with biases).
    Show answerPlain: 128⋅(64⋅9+1)=73,856128\cdot(64\cdot9+1)=73{,}856. Depthwise: 64⋅(9+1)=64064\cdot(9+1)=640. Pointwise: 128⋅65=8,320128\cdot65=8{,}320. The pair has 8,9608{,}960, about 8.2 times fewer parameters than the plain layer.

Next: P5.6 shrinks the height and width with pooling and shows how far each unit of a deep layer can “see”. P5.7 builds and trains a small CNN from layers like these.

Key takeaways

  • A kernel has as many slices as the input has channels: Cin×k×kC_{\text{in}}\times k\times k. At each position it multiplies every slice with its channel's window, adds all Cink2C_{\text{in}}k^2 products into one number and adds one bias. The kernel slides over height and width only, never along the channels.
  • CoutC_{\text{out}} kernels, each with its own bias, give CoutC_{\text{out}} feature maps, which are stacked into the output volume (Cout,H′,W′)(C_{\text{out}},H',W'). The next layer's CinC_{\text{in}} is this layer's CoutC_{\text{out}}.
  • In PyTorch the weight has shape (Cout,Cin,k,k)(C_{\text{out}},C_{\text{in}},k,k) and the bias (Cout,)(C_{\text{out}},), so a layer has Cout(Cink2+1)C_{\text{out}}(C_{\text{in}}k^2+1) learned numbers: 18,496 for 32 to 64 channels with 3×33\times3 kernels. The multiply-adds are the output size times CoutCink2C_{\text{out}}C_{\text{in}}k^2.
  • A 1×11\times1 convolution applies one Cout×CinC_{\text{out}}\times C_{\text{in}} matrix, plus a bias, to the channel vector of every pixel. It mixes channels but not positions, keeps the height and width, and is the cheap way to change the number of channels (bottlenecks, projection shortcuts).
  • Grouped convolutions let each kernel read only Cin/gC_{\text{in}}/g channels. Depthwise (one filter per channel) followed by a 1×11\times1 convolution gives 2,432 parameters where a plain 3×33\times3 layer from 32 to 64 channels has 18,496. In deeper layers a channel is a learned feature map, not a colour.
Found a mistake? Tell us