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

The convolution operation

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

Why this matters for machine learning

A convolution applies the same small set of weights at every position of an image, which gives a layer that finds a pattern wherever it appears with a handful of learned numbers instead of hundreds of thousands. Every convolutional network is built from this one operation.

  • Hand-made kernels for blurring, sharpening and finding edges are convolutions, and they are the first layer of many vision pipelines. (P5.3: Kernels as feature detectors)
  • A convolutional network stacks learned kernels, so the first layers learn edge and colour detectors on their own. (P5.7: Build a CNN)
  • Looking at what trained kernels respond to shows what a CNN has learned. (P5.8: What do CNNs learn?)
  • The same slide-and-multiply over a sequence is a one-dimensional convolution, used for time series and audio. (P6.13: Temporal convolutions and time series, coming soon)

Before this: Images as tensors, Dot product and cosine similarity, The forward pass in matrix form, Backpropagation: step by step with numbers

After this lesson you can

  • Compute a feature map by hand with a sliding kernel, and state its size as H−k+1H-k+1 by W−k+1W-k+1 for valid mode with stride 1
  • Explain why deep learning libraries compute a cross-correlation, what flipping the kernel would change, and why it does not matter for a learned kernel
  • Count the parameters of a convolution and of a dense layer on the same image, and explain locality and weight sharing
  • State translation equivariance, show where it breaks at the border, and write the gradient of the loss with respect to the kernel

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 784⋅676+676=530,660784\cdot676+676=530{,}660 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 3×33\times3 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 5×55\times5 image with values from 0 (dark) to 9 (bright).
  • The kernel is a small grid of numbers, here 3×33\times3. 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 −1-1 and whose right column is +1+1. The kernel is chosen by hand, and is an example of a vertical-edge detector (P5.3 explains why it works).

X=(1208921198102792119902187)K=(−101−101−101)\begin{aligned} \mathbf{X}&=\begin{pmatrix}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\end{pmatrix}\\[4pt] \mathbf{K}&=\begin{pmatrix}-1&0&1\\-1&0&1\\-1&0&1\end{pmatrix} \end{aligned}

(This K\mathbf{K} 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):

window=(120211102)products=(−100−201−102)sum=−1−2+1−1+2=−1\begin{aligned} \text{window}&=\begin{pmatrix}1&2&0\\2&1&1\\1&0&2\end{pmatrix}\\[4pt] \text{products}&=\begin{pmatrix}-1&0&0\\-2&0&1\\-1&0&2\end{pmatrix}\\[4pt] \text{sum}&=-1-2+1-1+2=-1 \end{aligned}

Second position. Move one pixel right, to columns 1 to 3. Now the window covers the edge:

window=(208119027)products=(−208−109007)sum=−2+8−1+9+7=21\begin{aligned} \text{window}&=\begin{pmatrix}2&0&8\\1&1&9\\0&2&7\end{pmatrix}\\[4pt] \text{products}&=\begin{pmatrix}-2&0&8\\-1&0&9\\0&0&7\end{pmatrix}\\[4pt] \text{sum}&=-2+8-1+9+7=21 \end{aligned}

The first window is flat and dark, so the left and right columns nearly cancel: −1-1. The second window has a dark left column and a bright right column, so the sum is large: 2121. 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:

Y=(−12123−1232212121)\mathbf{Y}=\begin{pmatrix}-1&21&23\\-1&23&22\\1&21&21\end{pmatrix}

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.

Image, 5×5, values 0 to 9 (dark to bright). The blue frame is the window at the selected position.
1208921198102792119902187
Kernel (edit the numbers)
Products at the window (pixel × weight)
1×−1−12×000×102×−1−21×001×111×−1−10×002×12

Position 1 of 9: row 0, column 0. Sum = (−1) + 0 + 0 + (−2) + 0 + 1 + (−1) + 0 + 2 = −1.

Feature map, 3×3 (= 5 − 3 + 1 in each direction). Tap a cell, or use the arrow keys, to move the window.
Kernel presets:

The window moves one pixel at a time and never leaves the image, so the map is smaller than the image. Blue cells are positive, grey cells negative; the number is always shown.

The sliding kernel on the 5 by 5 image. The blue frame is the window at the selected position. Under the image, the left grid is the kernel (edit any number, or pick a preset) and the right grid shows each pixel times its weight, which add up to the output value. Below that is the feature map: tap a cell or use the arrow keys to move the window, or use the previous and next buttons to go through all positions in reading order. The bias button adds one number to every output. The buttons switch between 3 by 3 and 2 by 2 kernels (the map becomes 3 by 3 or 4 by 4), between three small images, and between sliding the kernel as it is and sliding it rotated by 180 degrees.

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 −2-2 and 22 on the Edge image, but 1818, 00 and −18-18 down the rows of the map on the Plus image. The 2×22\times2 kernel gives a 4×44\times4 map, and “Flip the kernel” negates every output of the vertical-edge kernel.

The rule and the output size

Write Xi,jX_{i,j} for the pixel in row ii and column jj, counting from 0, and Ka,cK_{a,c} for the kernel entry in row aa and column cc. For a kernel of size k×kk\times k and a bias bb, the feature map entry at row ii and column jj is

Yi,j=b+∑a=0k−1∑c=0k−1Ka,c Xi+a, j+c.Y_{i,j}=b+\sum_{a=0}^{k-1}\sum_{c=0}^{k-1}K_{a,c}\,X_{i+a,\,j+c}.

Read it as: take the window whose top-left pixel is (i,j)(i,j), 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 0,1,…,H−k0,1,\dots,H-k, which is H−k+1H-k+1 places, and the same holds for the columns. So for an image with HH rows and WW columns, the map has

(H−k+1)×(W−k+1).(H-k+1)\times(W-k+1).

For the example, 5−3+1=35-3+1=3, so the map is 3×33\times3. For a 28×2828\times28 digit with a 3×33\times3 kernel it is 26×2626\times26, and with a 5×55\times5 kernel it is 24×2424\times24. 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 k−1k-1 in each direction. If kk 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: 3×33\times3 is the common choice, with 5×55\times5 and 7×77\times7 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 2×22\times2 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 (022240242322222)\begin{pmatrix}0&22&24\\0&24&23\\2&22&22\end{pmatrix}: 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 Ka,cflip=Kk−1−a, k−1−cK^{\text{flip}}_{a,c}=K_{k-1-a,\,k-1-c}. For the example kernel, the rows are identical and the columns swap, so Kflip\mathbf{K}^{\text{flip}} has +1+1 on the left and −1-1 on the right, and the map is negated:

Yflip=(1−21−231−23−22−1−21−21).\mathbf{Y}^{\text{flip}}=\begin{pmatrix}1&-21&-23\\1&-23&-22\\-1&-21&-21\end{pmatrix}.

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 k×kk\times k 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 28×2828\times28 image mapped to a 26×2626\times26 output (the size of a valid 3×33\times3 convolution):

  • Dense layer (P4.5): 784⋅676=529,984784\cdot676=529{,}984 weights and 676676 biases, in total 530,660 learned numbers.
  • One 3×33\times3 kernel with a bias: 9+1=9+1= 10 learned numbers.

The kernel is the same size for a 28×2828\times28 image and for a 1000×10001000\times1000 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 99 multiply-adds for each of the 676676 outputs, 6,0846{,}084 in all, against 529,984529{,}984 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): 3232 kernels on this image are 32⋅10=32032\cdot10=320 learned numbers, which gives 3232 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 x=(3,1,4,1)\mathbf{x}=(3,1,4,1) and the one-dimensional kernel (1,−1)(1,-1), slid without flipping. Each output is an entry minus the next one: (3−1, 1−4, 4−1)=(2,−3,3)(3-1,\ 1-4,\ 4-1)=(2,-3,3). As a matrix product:

(1−10001−10001−1)(3141)=(2−33)\begin{aligned} &\begin{pmatrix}1&-1&0&0\\0&1&-1&0\\0&0&1&-1\end{pmatrix}\begin{pmatrix}3\\1\\4\\1\end{pmatrix}\\ &\quad=\begin{pmatrix}2\\-3\\3\end{pmatrix} \end{aligned}

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 3⋅4=123\cdot4=12 of a full matrix.

The 5×55\times5 image of this lesson is the same, once you list its 25 pixels row by row. The layer is then a 9×259\times25 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 9×99\times9 image. The kernel is the vertical-edge kernel of this lesson. The map has a solid 7×77\times7 core (the valid positions) and a faded ring around it.

Move the bright L one pixel at a time. The kernel is the vertical-edge kernel of the lesson and does not change.

Image, 9×9. L at row 3, column 3.
999
Feature map: solid 7×7 core, faded ring around it.
00000000000000000000000000000000000090−900000000189−18−90000000189−18−9000000099−9−9000000000000000000000000000000000000000000000000

Moved by (+0, +0) pixels (rows, columns) from the start. All 14 nonzero responses of the L are inside the map.

Move a small bright L around a 9 by 9 image with the arrow buttons. The solid 7 by 7 block of the feature map is what a valid convolution computes. The faded ring is the responses of windows that would hang over the edge of the image, which a valid convolution does not compute. In the middle of the image the whole pattern of responses moves with the L. Near an edge, some responses fall in the ring, marked with a red cross and a dashed frame, and the map no longer holds the whole pattern.

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 ∂L/∂Ka,c\partial L/\partial K_{a,c} for a loss LL. The same kernel entry Ka,cK_{a,c} 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 Gi,j=∂L/∂Yi,jG_{i,j}=\partial L/\partial Y_{i,j} be the gradient that arrives from the layers above, one number per feature-map entry. Entry Ka,cK_{a,c} multiplies pixel Xi+a, j+cX_{i+a,\,j+c} in output (i,j)(i,j), so

∂L∂Ka,c=∑i,jGi,j Xi+a, j+c,∂L∂b=∑i,jGi,j.\begin{aligned} \frac{\partial L}{\partial K_{a,c}}&=\sum_{i,j}G_{i,j}\,X_{i+a,\,j+c},\\ \frac{\partial L}{\partial b}&=\sum_{i,j}G_{i,j}. \end{aligned}

The first sum has the form of the layer itself: it is the image cross-correlated with G\mathbf{G}, with G\mathbf{G} playing the role of the kernel. Its size, H−(H−k+1)+1=kH-(H-k+1)+1=k, is the size of the kernel, as it must be. The bias gradient is the sum of G\mathbf{G} 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.

Pick a kernel entry. Its gradient adds up one term for every place where that entry was used.

Gradient of the 3×3 kernel, orange (tap an entry)
Image (blue frame: the 3×3 block of pixels that sits under this kernel entry, one pixel per output position)
1208921198102792119902187
Upstream gradient G (orange) times that block of pixels (blue), term by term
1×110×20−1×002×241×110×100×10−1×001×22

Gradient of kernel entry (0, 0) = sum of the nine terms = 8. The bias gradient is the sum of G = 3.

G is made up for the demonstration. The same numbers fill the gradient grid at the top: it is the image cross-correlated with G.

The gradient of the kernel. The 3 by 3 orange grid is the gradient of each kernel entry. Choose an entry to see how it is built: the blue frame on the image is the block of pixels that this entry touched, one pixel for each output position, and each term is the upstream gradient (orange, made up for this demonstration) times that pixel (blue). The nine terms add up to the gradient of the entry.

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 Xp,qX_{p,q} was used by every window that contains it, so its gradient adds up the contributions Gi,jKp−i, q−jG_{i,j}K_{p-i,\,q-j} from all those outputs. This is a cross-correlation of G\mathbf{G}, padded with zeros by k−1k-1 on every side, with the kernel rotated by 180 degrees. For the example image, with G=(10−12100−11)\mathbf{G}=\begin{pmatrix}1&0&-1\\2&1&0\\0&-1&1\end{pmatrix} coming from above, this gives the 5×55\times5 input gradient

(−1020−1−3−141−1−30300−2010101−1−11),\begin{pmatrix}-1&0&2&0&-1\\-3&-1&4&1&-1\\-3&0&3&0&0\\-2&0&1&0&1\\0&1&-1&-1&1\end{pmatrix},

which matches PyTorch’s autograd. The kernel gradient is (824324333)\begin{pmatrix}8&2&4\\3&2&4\\3&3&3\end{pmatrix} with bias gradient 33 (the Code tab checks the kernel gradient against autograd).

In matrix language (the first Go-deeper box), a layer y=Mx\mathbf{y}=\mathbf{M}\mathbf{x} passes the gradient back as M⊤g\mathbf{M}^\top\mathbf{g} (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 9×99\times9 matrix (nine pixels in each of nine windows), and the product with the flattened kernel gives the same 3×33\times3 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 X\mathbf{X} of size H×WH\times W and a k×kk\times k kernel K\mathbf{K} with bias bb, the valid, stride-1 cross-correlation is

Yi,j=b+∑a=0k−1∑c=0k−1Ka,c Xi+a, j+c,Y_{i,j}=b+\sum_{a=0}^{k-1}\sum_{c=0}^{k-1}K_{a,c}\,X_{i+a,\,j+c},

with 0≤i≤H−k0\le i\le H-k and 0≤j≤W−k0\le j\le W-k. True convolution replaces Ka,cK_{a,c} by Kk−1−a, k−1−cK_{k-1-a,\,k-1-c}, which gives ∑Ka,cXi+k−1−a, j+k−1−c\sum K_{a,c}X_{i+k-1-a,\,j+k-1-c}.

Equivariance. Let SS shift an image by one pixel. For windows that stay inside the image on both sides, Y[SX]i,j=Y[X]i−1,jY[S\mathbf{X}]_{i,j}=Y[\mathbf{X}]_{i-1,j} for a shift down, because the sum depends on the window’s content and not on (i,j)(i,j).

Gradient. The chain rule over every output that uses Ka,cK_{a,c} gives the sum of the body, because ∂Yi,j/∂Ka,c=Xi+a, j+c\partial Y_{i,j}/\partial K_{a,c}=X_{i+a,\,j+c} and ∂Yi,j/∂b=1\partial Y_{i,j}/\partial b=1.

Counts. One kernel with a bias has k2+1k^2+1 learned numbers whatever the image size, and needs (H−k+1)(W−k+1) k2(H-k+1)(W-k+1)\,k^2 multiply-adds.

Code

A convolution layer in PyTorch, on the example of this lesson. Tensors are (N,C,H,W)(N,C,H,W) here: a batch of 1, one channel. The weight of nn.Conv2d has shape (out channels,in channels,k,k)(\text{out channels},\text{in channels},k,k).

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 G\mathbf{G}.

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.

Slide a kernel by hand

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.

Parameters, shifts and the kernel gradient

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

Running the cell gives 530,660530{,}660 against 1010; 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 4×10−94\times10^{-9} against finite differences, with the bias gradient 7.83587.8358 both ways. The error depends on the random numbers and on the step 10−610^{-6}.

Common mistakes

Quiz

Check your understanding

  1. A 28×2828\times28 image goes through one 5×55\times5 kernel, valid mode, stride 1. What is the shape of the feature map?

  2. What does PyTorch's nn.Conv2d compute from the image and its weights?

  3. One 3×33\times3 kernel with a bias is applied to a 100×100100\times100 image (valid mode). How many learned numbers does the layer have?

  4. 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)?

  5. The upstream gradient G=∂L/∂Y\mathbf{G}=\partial L/\partial\mathbf{Y} of a layer with a 3×33\times3 feature map is 1 at every position. What is ∂L/∂b\partial L/\partial b for the layer's single bias?

Exercises

  1. For the image of this lesson and the horizontal-edge kernel (−1−1−1000111)\begin{pmatrix}-1&-1&-1\\0&0&0\\1&1&1\end{pmatrix}, 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 answerThe window is (279199187)\begin{pmatrix}2&7&9\\1&9&9\\1&8&7\end{pmatrix}. The kernel gives the bottom row minus the top row: (1+8+7)−(2+7+9)=16−18=−2(1+8+7)-(2+7+9)=16-18=-2.
  2. 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 answerThe same rule applies in each direction: 32−5+1=2832-5+1=28 rows and 48−3+1=4648-3+1=46 columns, so 28×4628\times46.
  3. Slide a 2×22\times2 kernel (1234)\begin{pmatrix}1&2\\3&4\end{pmatrix} over the window (5678)\begin{pmatrix}5&6\\7&8\end{pmatrix}. What are the outputs of cross-correlation and of true convolution?
    Show answerCross-correlation: 5⋅1+6⋅2+7⋅3+8⋅4=705\cdot1+6\cdot2+7\cdot3+8\cdot4=70. Convolution rotates the kernel to (4321)\begin{pmatrix}4&3\\2&1\end{pmatrix} first: 5⋅4+6⋅3+7⋅2+8⋅1=605\cdot4+6\cdot3+7\cdot2+8\cdot1=60. The two differ, which is why the convention matters when you reuse a kernel written for the other one.
  4. A 64×6464\times64 image goes to a 62×6262\times62 map. How many learned numbers does a dense layer need, and how many does one 3×33\times3 kernel with a bias need? What changes from the 28×2828\times28 case?
    Show answerDense: 4096⋅3844+3844=15,748,8684096\cdot3844+3844=15{,}748{,}868. One kernel: 1010, 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, 3844⋅9=34,5963844\cdot9=34{,}596.
  5. A 3×33\times3 image has the values 11 to 99 row by row, (123456789)\begin{pmatrix}1&2&3\\4&5&6\\7&8&9\end{pmatrix}. A 2×22\times2 kernel gives a 2×22\times2 map, and the upstream gradient is G=(201−1)\mathbf{G}=\begin{pmatrix}2&0\\1&-1\end{pmatrix}. What are the gradient of the kernel and of the bias?
    Show answerThe kernel gradient is the image cross-correlated with G\mathbf{G}: entry (0,0)(0,0) is 2⋅1+0⋅2+1⋅4+(−1)⋅5=12\cdot1+0\cdot2+1\cdot4+(-1)\cdot5=1, entry (0,1)(0,1) is 2⋅2+0⋅3+1⋅5+(−1)⋅6=32\cdot2+0\cdot3+1\cdot5+(-1)\cdot6=3, entry (1,0)(1,0) is 2⋅4+0⋅5+1⋅7+(−1)⋅8=72\cdot4+0\cdot5+1\cdot7+(-1)\cdot8=7, and entry (1,1)(1,1) is 2⋅5+0⋅6+1⋅8+(−1)⋅9=92\cdot5+0\cdot6+1\cdot8+(-1)\cdot9=9. So (1379)\begin{pmatrix}1&3\\7&9\end{pmatrix}. The bias gradient is the sum of G\mathbf{G}, which is 22.

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.

Key takeaways

  • A convolutional layer slides a k×kk\times k kernel over the image. At each position it multiplies the window and the kernel element by element, adds the nine (or k2k^2) products and a bias, and writes the sum into the feature map. This is a dot product of the window with the kernel (P1.B3).
  • In valid mode with stride 1 the map has (H−k+1)×(W−k+1)(H-k+1)\times(W-k+1) entries, because the window must fit inside the image. Padding and stride change this (P5.4).
  • What PyTorch calls convolution does not flip the kernel, which makes it a cross-correlation. True convolution rotates the kernel by 180 degrees first. For a learned kernel the two give the same family of functions, so the library skips the flip.
  • Locality (each output sees only a k×kk\times k patch) and weight sharing (the same kernel at every position) give k2+1k^2+1 learned numbers for one kernel with a bias: 10 for a 3×33\times3 kernel, against 530,660 for a dense layer from 28×2828\times28 pixels to a 26×2626\times26 map.
  • Shifting the input shifts the feature map by the same amount (translation equivariance), except where part of the response falls over the border. The gradient of the kernel is the input cross-correlated with the upstream gradient: each kernel entry adds up the contributions from every position where it was used.
Found a mistake? Tell us