A handwritten digit is a grid of 28 by 28 pixels, 784 numbers. A dense layer (P4.5) that turns those 784 numbers into a map of 26 by 26 values has learned numbers. Every output has its own weight for every pixel, so it has no idea which pixels are neighbours, and a pattern it learns in one corner is unknown in the other corners.
A convolution gives the same size of map with 10 learned numbers: nine weights in a grid and one bias. It looks at a small patch at a time and uses the same weights for every patch. This lesson shows how that works on a grid small enough to compute by hand, what the 10 numbers buy and what they cost.
Scope: one greyscale image (one channel), one kernel, and the simplest way of sliding it. Colour images and many kernels come in P5.5. Padding, stride and dilation are in P5.4. Classic hand-made kernels, such as blurs and edge detectors, are catalogued in P5.3.
Slide a window, take a dot product
Three words first.
- The image is a grid of numbers, one per pixel. To keep the arithmetic small, this lesson uses a image with values from 0 (dark) to 9 (bright).
- The kernel is a small grid of numbers, here . It is also called a filter. In a network its entries are the learned weights.
- The window is a patch of the image with the same size as the kernel.
To compute one output value, place the window on the image, multiply it with the kernel element by element, and add the nine products. That sum is the output for that position. Then move the window one pixel and repeat.
Here is the image, and a kernel whose left column is and whose right column is . The kernel is chosen by hand, and is an example of a vertical-edge detector (P5.3 explains why it works).
(This is the kernel; attention in Part 7 reuses the letter for keys.) The image is dark on the left (values 0 to 2) and bright on the right (7 to 9), so there is a vertical edge between the third and fourth columns.
First position. The window sits on the top-left corner, rows 0 to 2 and columns 0 to 2. Multiply element by element, then add (the zero products are left out of the sum):
Second position. Move one pixel right, to columns 1 to 3. Now the window covers the edge:
The first window is flat and dark, so the left and right columns nearly cancel: . The second window has a dark left column and a bright right column, so the sum is large: . The kernel computes the right column of the window minus the left column.
Slide through all nine positions (three across, three down) and write the sums in a grid. This grid is the feature map:
The two right-hand columns of the map are large: the kernel responds strongly where it sees dark on the left and bright on the right. The left column is near 0, where the window sees only the flat dark area. The widget lets you step through every position and change the kernel.
Things to try. Step through all nine positions with the vertical-edge preset and check the map above. The horizontal-edge preset gives values between and on the Edge image, but , and down the rows of the map on the Plus image. The kernel gives a map, and “Flip the kernel” negates every output of the vertical-edge kernel.
The rule and the output size
Write for the pixel in row and column , counting from 0, and for the kernel entry in row and column . For a kernel of size and a bias , the feature map entry at row and column is
Read it as: take the window whose top-left pixel is , multiply by the kernel, add everything up, and add the bias. If you list the window and the kernel as two long vectors, the sum is their dot product (P1.B3). A large output means the window lines up with the kernel: bright where the kernel is positive and dark where it is negative. The score also grows with brightness, so it is not a normalised match.
Output size. The window must lie fully inside the image. Its top-left corner can be in row , which is places, and the same holds for the columns. So for an image with rows and columns, the map has
For the example, , so the map is . For a digit with a kernel it is , and with a kernel it is . This way of sliding is called valid (the window never leaves the image) with stride 1 (it moves one pixel at a time). The map is smaller than the image by in each direction. If is larger than the image there is no valid position at all. P5.4 shows how padding keeps the size, how a larger stride skips positions, and how dilation spreads the kernel out.
Kernels are usually small and odd: is the common choice, with and also used. An odd size has a centre pixel, so an output can be tied to the middle of its window. An even size has no middle pixel, which is why the widget’s kernel is only for seeing the size rule.
The bias. A convolution layer has one bias per kernel. The same number is added to every position. Adding a bias of 1 to the example makes the map : all nine values go up by one.
What happens after. The layer’s output is passed through an activation such as ReLU (P4.4), value by value, as in a dense layer. People call both the grid of sums and the activated grid a feature map, or an activation map. One kernel gives one map. A layer with many kernels gives many maps, one per kernel (P5.5).
Cross-correlation or convolution?
The operation above, with the kernel used as it is, is called cross-correlation. The mathematical convolution of signal processing first rotates the kernel by 180 degrees, which means reversing both its rows and its columns, and then slides it. Write the rotated kernel as . For the example kernel, the rows are identical and the columns swap, so has on the left and on the right, and the map is negated:
PyTorch’s documentation for nn.Conv2d writes the layer’s output as the bias plus the weight ⋆ the input, where ⋆ is “the valid 2D cross-correlation operator”: the weights are used as stored, with no flip. Despite the name, PyTorch’s convolutional layers do not flip the kernel.
Why the difference does not matter for learning. The kernel in a network is not chosen by a person. It is learned. If a library flipped the kernel before sliding it, training would simply find the flipped version of the kernel that the no-flip version finds, and the layer would compute the same function. The two conventions describe the same family of functions, and one convention can be rewritten as the other by flipping every kernel. The flip is extra work with no benefit, so libraries leave it out. One reason signal processing uses the flip is that it makes the operation commutative and associative, which helps when you combine filters on paper. A learned layer does not need that.
The difference does matter in one case: when you take a kernel from somewhere else, such as a textbook or a pretrained model that used the other convention. An asymmetric kernel, like the edge detector here, then gives the negative of the expected map.
Locality and weight sharing
A convolutional layer rests on two ideas:
- Locality. Each output depends only on a window, not on the whole image. Pixels far apart do not interact in one layer.
- Weight sharing. Every position uses the same kernel, so one detector is learned once and looks everywhere.
Count what these save, on a image mapped to a output (the size of a valid convolution):
- Dense layer (P4.5): weights and biases, in total 530,660 learned numbers.
- One kernel with a bias: 10 learned numbers.
The kernel is the same size for a image and for a image. The dense layer grows with the product of the input and output sizes. The work of computing the layer does grow with the image: a convolution needs multiply-adds for each of the outputs, in all, against for the dense layer.
The saving is real, but it is not free. One kernel finds one pattern, so a real layer uses many kernels (P5.5): kernels on this image are learned numbers, which gives maps. Locality and sharing are also a bet about images: that useful patterns are small and look the same wherever they are. This kind of built-in assumption is called an inductive bias. A dense layer can do everything a convolution can, by setting the right weights, and so it is more flexible, but it has to find those weights from data. The convolution starts with the structure built in.
Go deeper A convolution is a sparse matrix with tied weights
The linear-algebra map (P1.B15) showed this on four numbers. Take and the one-dimensional kernel , slid without flipping. Each output is an entry minus the next one: . As a matrix product:
Each row holds the kernel, moved one place to the right. Most entries are zero, and the non-zero entries are the same two numbers in every row: the layer has 2 learned numbers against the of a full matrix.
The image of this lesson is the same, once you list its 25 pixels row by row. The layer is then a matrix whose every row has nine non-zero entries, copies of the nine kernel weights, and sixteen zeros. It is a dense layer in which most weights are fixed at zero and the rest are tied together. That is the sense in which a convolution is a special dense layer. Libraries do not build this matrix, because sliding the kernel needs far less memory.
Translation equivariance
Because the same kernel is used everywhere, moving a pattern in the image moves its response in the feature map by the same amount. This property is called translation equivariance: shifting the input and then applying the convolution gives the same result as applying the convolution and then shifting the output.
Try it. A bright L-shaped object sits on a dark image. The kernel is the vertical-edge kernel of this lesson. The map has a solid core (the valid positions) and a faded ring around it.
Three observations from the widget:
- In the middle of the image, the pattern of 14 non-zero values moves exactly as the L moves. From the start, one step up or left, or up to two steps down or right, keeps the ring empty, and none of the response is lost.
- Move the L to a border. The pattern of responses still moves with it, but some of it lands in the faded ring and is not in the map. On the left edge only 7 of the 14 values remain in the core. Equivariance holds for the response of the whole image, but a valid map stores only the windows that fit.
- The numbers themselves do not change when the L moves, only their position. The layer detects the same pattern wherever it is.
Equivariance is not invariance. Invariant would mean that the map stays the same when the object moves. A convolution layer’s map moves with the object. Later layers can turn “where” into “whether”, for example by taking the largest value over a region (pooling, P5.6) or over the whole map, and that is where a network gets close to invariance, not exactly and not by the convolution alone. Equivariance also covers shifts only. Rotating or resizing an object changes its pattern, and a kernel that found the original may not find the rotated one. With a stride larger than 1, only shifts by multiples of the stride keep the exact pattern (P5.4).
How the kernel is learned: its gradient
A network learns its kernel by gradient descent (P4.8), so we need for a loss . The same kernel entry was used at every output position. P4.8’s rule for a value used in several places is that the gradients from each use add up. Let be the gradient that arrives from the layers above, one number per feature-map entry. Entry multiplies pixel in output , so
The first sum has the form of the layer itself: it is the image cross-correlated with , with playing the role of the kernel. Its size, , is the size of the kernel, as it must be. The bias gradient is the sum of because the bias was added to every output. In the widget below, the gradients are orange (the colour used for gradients everywhere on this site), and the image values are blue.
The gradient with respect to the input is also needed, to pass the gradient on to earlier layers. It is a convolution as well; the box below gives it.
Go deeper The gradient with respect to the input, and the transposed matrix
Each input pixel was used by every window that contains it, so its gradient adds up the contributions from all those outputs. This is a cross-correlation of , padded with zeros by on every side, with the kernel rotated by 180 degrees. For the example image, with coming from above, this gives the input gradient
which matches PyTorch’s autograd. The kernel gradient is with bias gradient (the Code tab checks the kernel gradient against autograd).
In matrix language (the first Go-deeper box), a layer passes the gradient back as (P4.8, P1.B10). The transpose of the sliding matrix is again a sliding matrix, with the kernel rotated, which is the same statement. Because the same transposed matrix maps a small map back to a larger image, it is also the idea behind the transposed convolution that upsamples (P5.13).
Go deeper How libraries compute a convolution
Sliding a window in a loop is slow in Python and not the way libraries do it. One way, called im2col, copies every window into a column, so that the nine pixels of each window become one column of a matrix, and then multiplies the kernel (as one row of nine numbers) with that matrix. For the example, PyTorch’s unfold gives a matrix (nine pixels in each of nine windows), and the product with the flattened kernel gives the same map as before. Libraries use several algorithms and choose among them depending on the sizes and the hardware. The result is the same as the loop here, up to rounding.
Depth: three ways to see it
Intuition
Think of a stamp that you press onto every spot of a page, one spot at a time, and at each spot you write down how well the stamp matches what is under it. The stamp is the kernel. It is the same stamp everywhere, so it finds its pattern wherever it appears, and the page of notes is the feature map.
The picture breaks in several places. A stamp is pressed on whole spots, and the kernel slides by one pixel, so neighbouring windows overlap heavily. The match score is a plain dot product, so a bright patch gives a big score with an all-positive kernel, whether or not it has the shape. And one stamp finds one pattern: a layer needs many kernels to see many things.
Math
For an image of size and a kernel with bias , the valid, stride-1 cross-correlation is
with and . True convolution replaces by , which gives .
Equivariance. Let shift an image by one pixel. For windows that stay inside the image on both sides, for a shift down, because the sum depends on the window’s content and not on .
Gradient. The chain rule over every output that uses gives the sum of the body, because and .
Counts. One kernel with a bias has learned numbers whatever the image size, and needs multiply-adds.
Code
A convolution layer in PyTorch, on the example of this lesson. Tensors are here: a batch of 1, one channel. The weight of nn.Conv2d has shape .
import torch
import torch.nn as nn
import torch.nn.functional as F
x = torch.tensor([[1, 2, 0, 8, 9],
[2, 1, 1, 9, 8],
[1, 0, 2, 7, 9],
[2, 1, 1, 9, 9],
[0, 2, 1, 8, 7]], dtype=torch.float32)
x = x.reshape(1, 1, 5, 5) # (N, C, H, W)
conv = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3)
with torch.no_grad():
conv.weight[:] = torch.tensor([[-1., 0., 1.]] * 3).reshape(1, 1, 3, 3)
conv.bias.zero_()
y = conv(x)
print("input (N,C,H,W):", tuple(x.shape))
print("weight (out,in,k,k):", tuple(conv.weight.shape))
print("output (N,C,H,W):", tuple(y.shape))
print(y[0, 0].detach().int())
print("conv parameters:", sum(p.numel() for p in conv.parameters()))
print("dense 784 -> 676:", sum(p.numel() for p in nn.Linear(784, 676).parameters()))
G = torch.tensor([[1., 0., -1.], [2., 1., 0.], [0., -1., 1.]])
y.backward(G.reshape(1, 1, 3, 3))
print("dL/dK:")
print(conv.weight.grad[0, 0].int())
print("dL/db:", conv.bias.grad.item())
print("x xcorr G:")
print(F.conv2d(x, G.reshape(1, 1, 3, 3))[0, 0].int())Output from a local run with PyTorch 2.9.1:
input (N,C,H,W): (1, 1, 5, 5)
weight (out,in,k,k): (1, 1, 3, 3)
output (N,C,H,W): (1, 1, 3, 3)
tensor([[-1, 21, 23],
[-1, 23, 22],
[ 1, 21, 21]], dtype=torch.int32)
conv parameters: 10
dense 784 -> 676: 530660
dL/dK:
tensor([[8, 2, 4],
[3, 2, 4],
[3, 3, 3]], dtype=torch.int32)
dL/db: 3.0
x xcorr G:
tensor([[8, 2, 4],
[3, 2, 4],
[3, 3, 3]], dtype=torch.int32)The layer gives the hand-computed map, the parameter counts are 10 and 530,660, and autograd’s gradient of the kernel equals the image cross-correlated with .
Try it in Python
The first cell is the hand calculation in NumPy: a loop over positions, with the flipped kernel and a bias. The second checks the parameter counts, the shift rule, and the gradient formula against finite differences on random numbers.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell prints the map worked out above, its negative for the flipped kernel, and the map plus one for bias 1. Change K or x and predict the map before you run it.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives against ; True for the moved L; 14 non-zero values for the L in the middle and 7 at the left edge; and a kernel-gradient error of about against finite differences, with the bias gradient both ways. The error depends on the random numbers and on the step .
Common mistakes
Quiz
Check your understanding
A image goes through one kernel, valid mode, stride 1. What is the shape of the feature map?
The window can start in rows to , which is places, and the same for columns. A map equal to the input in size needs padding, which is the subject of P5.4. Subtracting the kernel size without adding 1 miscounts the starting positions by one. A window of 5 pixels needs 5 rows, not 4, and the rule is for .
What does PyTorch's
nn.Conv2dcompute from the image and its weights?PyTorch's documentation defines the layer through the valid cross-correlation operator, so the kernel is used as stored. Rotating the kernel first is the textbook convolution, which libraries do not do because a learned kernel makes the rotation pointless. A single dot product over the whole image would give one number, not a map. A matrix product is a different operation, with no sliding window.
One kernel with a bias is applied to a image (valid mode). How many learned numbers does the layer have?
The same nine weights and one bias are used at every position, so the count is , whatever the size of the image. The feature map has values, but they are outputs, not parameters. A count that grows with the number of pixels describes a dense layer, which has separate weights for every connection, and is the opposite of weight sharing.
An object in the middle of an image moves 2 pixels to the right. What happens to the feature map of a convolutional layer (valid mode, stride 1)?
Each output depends only on the content of its window, so moving the content moves the response with it: this is translation equivariance. Staying the same would be invariance, which one layer does not give. The map does not change completely, because the same pattern under the same kernel gives the same numbers in a new place. A sign change comes from rotating the kernel, not from moving the object.
The upstream gradient of a layer with a feature map is 1 at every position. What is for the layer's single bias?
The one bias was added to all nine outputs, and the gradients of values used several times add up (P4.8), so . Having a single bias does not mean a single use. The bias gradient does not depend on the image, but it still depends on . The kernel size would matter for the kernel gradient, not for the bias gradient.
Exercises
- For the image of this lesson and the horizontal-edge kernel , what is the output at the window with top-left pixel in row 2 and column 2 (rows 2 to 4, columns 2 to 4)?
Show answer
The window is . The kernel gives the bottom row minus the top row: . - An image has 32 rows and 48 columns, and the kernel has 5 rows and 3 columns. What is the size of the valid, stride-1 map?
Show answer
The same rule applies in each direction: rows and columns, so . - Slide a kernel over the window . What are the outputs of cross-correlation and of true convolution?
Show answer
Cross-correlation: . Convolution rotates the kernel to first: . The two differ, which is why the convention matters when you reuse a kernel written for the other one. - A image goes to a map. How many learned numbers does a dense layer need, and how many does one kernel with a bias need? What changes from the case?
Show answer
Dense: . One kernel: , the same as before, since the kernel does not depend on the image size. The dense count grows with the product of input and output sizes, and the number of multiply-adds of the convolution grows with the size of the map, . - A image has the values to row by row, . A kernel gives a map, and the upstream gradient is . What are the gradient of the kernel and of the bias?
Show answer
The kernel gradient is the image cross-correlated with : entry is , entry is , entry is , and entry is . So . The bias gradient is the sum of , which is .
Next: P5.3 uses hand-made kernels to blur, sharpen and find edges, and shows what the sums of the weights mean. P5.4 adds padding, stride and dilation to the output-size rule. P5.5 stacks many kernels and many channels.