P5.2 ended with a layer of 32 kernels on a greyscale image: learned numbers and 32 feature maps of size . Those maps are not one picture any more. They are a stack of 32 pictures, a tensor of shape in the order. The next layer has to read all 32 of them. A 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 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 , the PyTorch order, and a batch has shape . The channel count of the input is written .
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 kernel for an RGB image holds weights, shaped .
At one position, the window is a block of pixels too: a patch from every channel. The rule is P5.2’s rule, repeated for each channel and then added up:
- Multiply each channel’s window with the matching slice of the kernel, element by element.
- Add all the products, from all channels, into one number.
- Add the bias.
That gives one output value. For and , it is 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 , and then the block is the single slice of P5.2.
A small example by hand
Take an input with two channels of size (a tensor of shape ) and kernels.
The first kernel block, which makes output channel 0, has one slice per input channel and a bias of :
(The first index of is the output channel , the second is the input channel .)
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:
( means multiply element by element.) The output value is the two sums plus the bias: . Sliding to the other three positions gives the whole map of output channel 0. A second kernel block, with its own slices , and bias , gives output channel 1. At the top-left position its sums are and , so the value is . The two maps are
The input volume became an output volume . Each map has the size 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.
Things to try. Step through the four positions with output 0 selected and check . 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 learned numbers.
The formula, and what a layer has
Write for the pixel at row and column of input channel (indices from 0). In P5.2 the kernel entries were with as the column. Now is the channel, so the row and column inside the kernel are called and , and the kernel gets two more indices, the output channel and the input channel : . The output is
Read it from the inside out: for one channel, P5.2’s sliding sum; then add over channels; then add the bias of that output channel. With it is exactly P5.2’s formula. The map has size for every .
Shapes. For a layer with input and output channels:
- input , output with and in valid mode;
- weight , one block for each output channel;
- bias , one number per output channel, added at every position of that channel’s map.
The 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 is this layer’s .
Parameters. Each block has weights and one bias, and there are blocks:
The widget’s layer has . P5.2’s layer, 32 kernels on a grey image, has . A layer from a colour image to 32 maps with kernels has . A layer that reads those 32 maps and makes 64 has . As in P5.2, none of these depends on the height and width of the image.
Multiply-adds. Each output value needs multiplications (the bias addition is not counted). There are output values, so
For P5.2’s layer, , which is the of one kernel times 32. For the colour layer on a image (): . 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 per output.
The output volume also has to be stored, because backpropagation (P4.8) needs it. Its size is 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 is the feature map made by kernel 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 , then , then ), 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 . A kernel has one weight per input channel, so each of the kernels is just 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 . Put the weights in a matrix of shape with , and the biases in . Then the formula above reads
That is the dense layer of P4.5, applied to the channel vector of every pixel with the same and . A convolution is a linear layer that shares its weights across all positions.
Example: three channels, a image and two output channels, with and . The top-left pixel has channel values :
The same matrix is applied to the other three pixels, and the output has the same height and width as the input, , because .
Running the Code tab confirms this on random numbers: a Conv2d with 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 is a convolution with (the greyscale weights of P5.1).
What it is used for.
- Changing the number of channels cheaply. A layer from to has parameters: from 32 to 64 channels, against for a layer.
- Bottlenecks. Before an expensive layer, a layer squeezes the channels down. After it, another layer expands them again. A block with channels, squeezed to , a layer on channels and expanded back to has parameters, against for one layer from 256 to 256 channels. That is about 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 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 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 channels. In a grouped convolution with groups, the input channels and the output channels are each split into equal groups, and every output channel reads only the input channels of its own group. Both and must be divisible by . Each kernel then has slices, so
and the weight shape in PyTorch is . For 32 to 64 channels with kernels, gives against for . The multiply-adds shrink by the same factor . The groups cannot see each other, so something else has to mix the channels.
The extreme case (with a multiple of it, usually equal) is a depthwise convolution: one filter per channel, and no mixing between channels at all. Follow it with a convolution (also called a pointwise convolution), which does the mixing, and you have a depthwise-separable convolution. For 32 to 64 channels:
parameters, against for the plain layer, about times fewer. Without biases the counts are against , a ratio of exactly . 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 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,
where is the single-channel valid cross-correlation of P5.2, and is the slice of kernel block for channel .
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: , where . The bias gradient is .
Code
The worked example in PyTorch. Tensors are , and the weight is .
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 -> 2112The layer gives the hand-computed maps and , and the parameter counts agree with . The depthwise layer (32 groups) has weight shape .
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 convolution as one matrix product and counts the parameters of the layers in this lesson.
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 and at the top-left position, and parameters. Change b or a slice of K and predict the maps first.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell prints the maps and , the pixel mapped to , and the counts , , and .
Common mistakes
Quiz
Check your understanding
A layer is
nn.Conv2d(16, 32, 3), with biases. How many learned numbers does it have?Each kernel block reads all 16 input channels, and there is one block per output channel, so the total is . Dropping the biases gives the weights-only count. Swapping the two channel counts describes a layer from 32 to 16 channels. Counting only per block is the single-channel layer of P5.2, which ignores the other 15 channels.
What is the shape of the weight tensor of
nn.Conv2d(3, 8, 5)in PyTorch?PyTorch orders the axes as output channels, input channels, kernel height, kernel width. Putting the input channels first swaps the two channel axes. A shape with no input-channel axis is the single-channel kernel of P5.2. Height, width, input, output is not PyTorch's order.
A batch of shape goes through
nn.Conv2d(3, 16, 3), valid mode, stride 1. What is the shape of the output?The number of output channels is the number of kernel blocks, whatever the input has. Valid mode shrinks each side by . Keeping would need padding (P5.4). A kernel block adds its three channels together into one map, so the channels do not multiply into 48.
A convolution with 64 input channels and 16 output channels is applied to a tensor of shape . What does it do?
Each pixel's 64 channel values are mapped to 16 values with the same weights at every position, and the height and width stay the same. A window never reads neighbouring pixels, so nothing is averaged or shrunk. It is useful because it mixes channels and changes their number. One filter per channel with no mixing is a depthwise convolution, which keeps the channel count.
A depthwise convolution on 32 channels uses one filter per channel and no biases. How many weights does it have?
The weight shape is , which is numbers. An ordinary layer from 32 to 32 channels has because every kernel reads all 32 channels, which a depthwise layer avoids. A single shared filter would not be depthwise. One number per channel would be a filter.
Exercises
- A kernel block has two slices, for channel 0 and for channel 1, and a bias of . The window is in channel 0 and in channel 1. What is the output value?
Show answer
Channel 0: . Channel 1: . Add both sums and the bias: . - A image (a tensor of shape ) 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 answer
The output is , because . Parameters: . Multiply-adds: . - With the matrix and bias of this lesson, what does the convolution give for a pixel with channel values ?
Show answer
The first output is . The second is . So the output vector is . - A block squeezes 128 channels to 32 with a convolution, applies a convolution from 32 to 32, and expands back to 128 with another convolution. Count all parameters (with biases) and compare them with one layer from 128 to 128.
Show answer
to : . The layer: . to : . Total . The single layer has , about 8.4 times more. - Compare a plain layer from 64 to 128 channels with a depthwise layer followed by a layer from 64 to 128 (both with biases).
Show answer
Plain: . Depthwise: . Pointwise: . The pair has , 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.