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

Padding, stride and dilation

P5.435 min●○○ BeginnerReviewed Dec 3, 2026

Why this matters for machine learning

Padding, stride and dilation decide the size of every feature map in a CNN, and with it the memory, the compute and how much of the image each output can see.

Before this: The convolution operation

After this lesson you can

  • Compute the output size of a convolution from the input size, kernel size, padding, stride and dilation, and say when PyTorch would reject the combination
  • Choose the padding that keeps the size for an odd kernel at stride 1, with and without dilation, and say what padding='same' allows
  • Say which input rows a strided convolution never reads, and why border pixels are read less often without padding
  • Count the parameters and the multiply-adds of a convolution and say which of the three settings change each

A 3×33\times3 convolution with no padding takes two rows and two columns off the map. Apply it to a 32×3232\times32 image 15 times in a row and a 2×22\times2 map is left. A 16th layer would have nothing to slide over. And in a single layer, a pixel in the corner of the image is read by one window, while a pixel in the middle is read by nine.

Three small settings, padding, stride and dilation, fix both problems and decide the size of every feature map after the first layer. This lesson builds the one formula that gives the output size, checks it against PyTorch, and shows what each setting costs. It assumes the sliding dot product of P5.2.

The two problems of valid mode

P5.2 slid a k×kk\times k kernel over an H×HH\times H image and let it stop as soon as it reached the edge. That is valid mode: the kernel always sits fully inside the image, so there are H−k+1H-k+1 positions along each side. Two things follow.

The map shrinks. A 5×55\times5 image with a 3×33\times3 kernel gives a 3×33\times3 map. Every layer loses k−1k-1 rows and columns, and the loss adds up over layers.

Borders are read less. Count how many windows read each pixel of a 5×55\times5 image (running the kernel in valid mode gives these counts):

[1232124642369632464212321]\begin{bmatrix} 1&2&3&2&1\\ 2&4&6&4&2\\ 3&6&9&6&3\\ 2&4&6&4&2\\ 1&2&3&2&1 \end{bmatrix}

The corner is read once and the centre nine times. Whatever sits at the edge of the picture has a smaller say in the output than whatever sits in the middle.

Padding: a margin of zeros

Zero padding adds pp rows and columns of zeros on every side of the input before the kernel slides. The padded input has size H+2pH+2p along each side, and the kernel now starts and ends over the margin.

With p=1p=1 on the same 5×55\times5 image, the 3×33\times3 kernel has 5 positions along each side, so the output is 5×55\times5, and the read counts become

[4666469996699966999646664]\begin{bmatrix} 4&6&6&6&4\\ 6&9&9&9&6\\ 6&9&9&9&6\\ 6&9&9&9&6\\ 4&6&6&6&4 \end{bmatrix}

The corner is now read four times (the border is no longer ignored, though it is still read less than the middle). The size is kept.

Zeros are not information. They only give the kernel something to stand on at the edge, so padding does not make the map richer. The widget later in this lesson shows both pictures, and you can switch to the read counts.

“Same” padding

For an odd kernel and stride 1, the padding that keeps the size is

p=k−12,p=\frac{k-1}{2},

which is 1 for k=3k=3, 2 for k=5k=5 and 3 for k=7k=7. It is called same padding because the output has the same size as the input. (With stride 1 and no dilation, the output size is H+2p−k+1H+2p-k+1, and this equals HH exactly when 2p=k−12p=k-1.) An even kernel would need half a pixel on each side, so it needs an uneven split. Odd kernels have a centre pixel and a symmetric margin, which is why 3×33\times3, 5×55\times5 and 7×77\times7 are the usual sizes.

In PyTorch, nn.Conv2d takes padding in three forms:

  • an integer or a pair of integers: that many zeros on each side;
  • 'valid': no padding;
  • 'same': pad so that the output size equals the input size. The documentation says this mode does not support any stride other than 1, and nn.Conv2d(1, 1, 3, stride=2, padding='same') raises a ValueError.

For an even kernel, padding='same' pads unevenly. In PyTorch 2.9.1 the extra zero goes on the right and bottom (checked by comparing with manual padding for k=2k=2).

Other ways to fill the margin

Zeros are the default, but the margin can be filled otherwise. nn.Conv2d has a padding_mode argument. On one row [1,2,3,4][1,2,3,4] with two cells added on each side:

  • zeros: [0,0,1,2,3,4,0,0][0,0,1,2,3,4,0,0]
  • reflect: [3,2,1,2,3,4,3,2][3,2,1,2,3,4,3,2] (a mirror that does not repeat the edge pixel)
  • replicate: [1,1,1,2,3,4,4,4][1,1,1,2,3,4,4,4] (the edge pixel repeated)
  • circular: [3,4,1,2,3,4,1,2][3,4,1,2,3,4,1,2] (the row wraps around)

Zeros form a border of one constant value that the network can learn to detect, and the outputs at the edge mix real pixels with values that were never in the picture. Reflect and replicate keep the margin close to the pixels next to it. Reflect needs the padding to be smaller than the size of the input (PyTorch raises an error otherwise). Circular padding suits data that really wraps around, such as an angle axis. Zeros are the default of nn.Conv2d, and the rest of this lesson uses them.

Stride: jump instead of slide

Stride ss is the number of pixels the window moves between two outputs. Stride 1 is the sliding of P5.2. With stride 2 the window moves two pixels, so the output has about half as many rows and half as many columns.

Take an 88-wide row, a kernel of 3, no padding and stride 2. The windows start at positions 0, 2 and 4 (counting from 0) and cover pixels 00–22, 22–44 and 44–66. A fourth window would start at 6 and run to 8, which is past the end. So the output has 3 values and the last pixel, number 7, is never read. Counting how many windows read each pixel gives [1,1,2,1,2,1,1,0][1,1,2,1,2,1,1,0]: the zero is the skipped pixel, and the twos are pixels shared by two windows.

This is the floor in the formula you will meet in a moment: the output has as many values as whole windows fit. When the room left over after the last window is not zero, the last rows and columns of the input are left out. Stride is also a way to downsample: it can take the place of a stride-1 convolution followed by pooling (P5.6), with one layer that learns its own downsampling. On a 32×3232\times32 map, 3×33\times3 kernel, p=1p=1, going from stride 1 to stride 2 turns a 32×3232\times32 output into a 16×1616\times16 one, and the work drops by a factor of 4.

A stride larger than the effective kernel size (see the next section) skips pixels inside the image too. A 1×11\times1 kernel with stride 2 reads every other pixel, [1,0,1,0,1,0][1,0,1,0,1,0] on a row of 6. Dilation can cause the same at a smaller stride: with k=3k=3, d=2d=2 and s=2s=2 on a row of 9, the counts are [1,0,2,0,3,0,2,0,1][1,0,2,0,3,0,2,0,1], because every window reads only even positions.

Dilation: spread the taps apart

Dilation dd is the gap between the taps of the kernel. With d=1d=1 the taps touch, as in an ordinary kernel. With d=2d=2 a 3×33\times3 kernel reads pixels two apart: on one row it reads positions 00, 22 and 44 and skips 11 and 33. The 9 weights are the same weights, but they now look at a 5×55\times5 window. Some libraries call this the à trous (“with holes”) convolution, and the PyTorch documentation uses that name.

The window that a dilated kernel spans is the effective kernel size

keff=d(k−1)+1.k_{\text{eff}}=d(k-1)+1.

The first and last tap are d(k−1)d(k-1) pixels apart, and the +1+1 counts the pixel at the start. For k=3k=3: d=1d=1 gives 3, d=2d=2 gives 5, d=4d=4 gives 9.

Dilation is not the same as a larger kernel. A 5×55\times5 kernel has 25 weights and reads every pixel in its window, while a 3×33\times3 kernel with d=2d=2 has 9 weights and reads 9 pixels spread over the same window. The cost is that it ignores what lies between the taps. The benefit is a wider view at no extra weights, which is why dilated convolutions are used when a wide view matters (WaveNet for audio, with dilated 1-D convolutions, and several segmentation networks are examples). How far each output “sees” is the receptive field of P5.6.

One formula for everything

Put the three settings together. The padded input has length H+2pH+2p along each side, and the kernel covers keffk_{\text{eff}} of it. The first window starts at index 0, the next at ss, then 2s2s, and so on, and the last window must end inside the padded input: js+keff−1≤H+2p−1js+k_{\text{eff}}-1\le H+2p-1. The number of windows is

Hout=⌊H+2p−d(k−1)−1s⌋+1H_{\text{out}}=\Big\lfloor\frac{H+2p-d(k-1)-1}{s}\Big\rfloor+1

This is the formula in the PyTorch nn.Conv2d documentation. The documentation writes the +1+1 inside the floor, which gives the same value, since adding a whole number to a number before rounding down is the same as adding it after. The width follows the same rule with WW. When height and width differ, the settings can be pairs, one for each axis (for instance kernel_size=(3, 5)), and the formula is applied to each axis separately.

Examples, all computed by the formula (and matched by nn.Conv2d):

  • H=28H=28, k=5k=5, valid, stride 1: ⌊23⌋+1=24\lfloor 23\rfloor+1=24.
  • H=32H=32, k=3k=3, p=1p=1, s=2s=2: 32+2−2−1=3132+2-2-1=31, so ⌊31/2⌋+1=16\lfloor31/2\rfloor+1=16.
  • H=8H=8, k=3k=3, s=2s=2: ⌊5/2⌋+1=3\lfloor 5/2\rfloor+1=3.
  • H=9H=9, k=3k=3, d=2d=2, valid: 9−4−1=49-4-1=4, so 4+1=54+1=5.

If the formula gives 00 or less, the kernel does not fit in the padded input and PyTorch raises a RuntimeError. For example, a 5×55\times5 kernel on a 3×33\times3 input gives 3−5+1=−13-5+1=-1.

Which rows are never read? Let rr be the remainder of the numerator divided by ss, r=(H+2p−d(k−1)−1) mod sr=(H+2p-d(k-1)-1)\bmod s. The last window ends rr cells before the end of the padded input, so the last rr padded cells are never read. Of those, pp are padding zeros, so max⁡(0,r−p)\max(0,r-p) real rows and columns at the end are skipped. This is the whole story when s≤keffs\le k_{\text{eff}} and the dilation is 1 (or the stride is 1): the windows then overlap or touch, so nothing inside is missed. With a larger stride, or with a dilation that shares a factor with the stride, cells inside the image are also never read, and the widget crosses them out too. For H=8H=8, k=3k=3, s=2s=2 and p=0p=0: r=1r=1 and one row is lost. (With s=3s=3 on the same row, r=2r=2 and the last two rows are lost: windows cover 00–22 and 33–55.) With p=1p=1 the numerator is 77 and r=1r=1 again, but now that zero is padding and no real row is lost (reads [1,2,1,2,1,2,1,1][1,2,1,2,1,2,1,1], output 4).

See it: the output-size calculator

The widget shows one axis of the formula on a square image. Move the five sliders, or use a preset. The left grid is the padded input: the hatched cells are padding zeros, and the frame marks the real image. The blue cells are the taps of the kernel at the output position you pick (use the Output position slider, which is also the keyboard way, or tap a cell of the output grid), and the dashed box is the window they span. A red cross marks an input pixel that no window ever reads. The line above shows the formula with your numbers put in. Switch to “How often each pixel is read” to see the counts of this lesson as shade and number.

out = ⌊(H + 2p − d(k − 1) − 1) / s⌋ + 1
⌊(8 + 2·0 − 1·(3 − 1) − 1) / 2⌋ + 1 = ⌊5 / 2⌋ + 1 = 3

Input 8×8 → output 3×3. Effective kernel size: d(k − 1) + 1 = 3.

Warning. 1 of the 8 input rows (and the same columns) are never read: row 7, the last one. Rows are counted from 0.

Padded input (8×8)
Output (3×3), tap a cell
  • padding zero
  • kernel tap
  • ✕ never read

This position reads 9 cells (the taps; some may be padding zeros), spread over a 3×3 window. Weights in the kernel: 9, whatever p, s and d are. Multiply-adds for one input and one output channel: 3×3×3×3 = 81.

Output-size calculator. Sliders: input size H, kernel size k, padding p, stride s, dilation d (the same values are used for height and width). Left: the zero-padded input, with hatched padding cells, a frame around the real image, the taps of the kernel at the chosen output position in blue with a dashed window, and a red cross on every input pixel that is never read. Right: the output map with the chosen position filled. Above the grids: the formula with the numbers put in and a red message when PyTorch would raise an error. Switching the view shows how many windows read each input pixel. Nothing is animated, so Lite Mode shows the same.

Things to try, each of which the formula predicts:

  1. Press Valid: 3×3 on 8. The output is 6×66\times6. Switch to the read counts: the corner is read once and the centre pixels nine times.
  2. Press Same: p = 1. The output is 8×88\times8, the same as the input, and the corner is now read four times.
  3. Press Floor: 8, s = 2. The output is 3×33\times3 and a red cross marks the last row and the last column. Raise the padding to 1: the cross disappears, because the leftover is now a padding zero.
  4. Press Dilated: d = 2. The taps are spread out over a 5×55\times5 window, the output is 5×55\times5, and the weight count is still 9.
  5. Press Too big: k = 5 on 3. The red message appears: the formula gives −1-1.
  6. From the Valid preset, set k=1k=1 and s=2s=2. Every other row and column is unread, so the cross marks fill the image in a pattern: a stride larger than the kernel skips pixels inside the image.

The widget draws one axis of a square image; in 2-D a pixel is read (reads along the rows)×(reads along the columns) times, which is the outer product of the two 1-D counts.

What it costs

Parameters do not change. A convolution with CinC_{\text{in}} input channels and CoutC_{\text{out}} output channels has k2CinCout+Coutk^2C_{\text{in}}C_{\text{out}}+C_{\text{out}} parameters, and pp, ss and dd are not in the formula (P5.5 explains the channels). With one channel in and one out, a 3×33\times3 layer has 9+1=109+1=10 parameters for every combination, and PyTorch confirms it. The same weights are reused at every position (P5.2), so a bigger map does not need more of them.

Multiply-adds do change. Each output value takes k2Cink^2C_{\text{in}} multiply-adds, so a layer costs

Hout Wout  k2 Cin CoutH_{\text{out}}\,W_{\text{out}}\;k^2\,C_{\text{in}}\,C_{\text{out}}

multiply-adds. The settings act only through the output size. This counts the padded zeros as if they were real values, which is how the formula is usually used. On a 32×3232\times32 map and one channel pair, the cost of a 3×33\times3 kernel is:

  • valid: 302⋅9=810030^2\cdot9=8100;
  • p=1p=1: 322⋅9=921632^2\cdot9=9216;
  • p=1p=1, s=2s=2: 162⋅9=230416^2\cdot9=2304, a quarter of the previous line;
  • d=2d=2, valid: 282⋅9=705628^2\cdot9=7056;
  • d=2d=2, p=2p=2: 322⋅9=921632^2\cdot9=9216, the same as d=1d=1, p=1p=1, with a 5×55\times5 window.

So padding makes the output, and the cost, larger, stride makes them smaller by about s2s^2, and dilation costs nothing in weights or multiply-adds beyond what its output size implies. A 5×55\times5 kernel with p=2p=2 on the same map costs 322⋅25=2560032^2\cdot25=25600, nearly three times as much as the dilated 3×33\times3.

A worked stack

Sizes through a short stack, starting from a 32×3232\times32 image. Each line is the formula with the layer’s settings (PyTorch gives the same shapes):

  1. k=5k=5, p=0p=0, s=1s=1: ⌊27⌋+1=28\lfloor 27\rfloor+1=28.
  2. k=3k=3, p=0p=0, s=2s=2: ⌊25/2⌋+1=13\lfloor 25/2\rfloor+1=13. The remainder is 1, so the last row and column of the 28×2828\times28 map are never read.
  3. k=3k=3, p=1p=1, s=2s=2: ⌊13/2⌋+1=7\lfloor 13/2\rfloor+1=7.
  4. k=3k=3, d=2d=2, p=2p=2, s=1s=1: 7+4−4−1+1=77+4-4-1+1=7, size kept (same padding for a dilated kernel).

So 32→28→13→7→732\to28\to13\to7\to7. For a design, the usual recipe is to use same padding to keep the size inside a block and a stride of 2 (or pooling, P5.6) at the places where you want to halve it. Without any padding, a stack of 3×33\times3 valid layers on a 32×3232\times32 image can have at most 15 layers (the map is then 2×22\times2).

Transposed convolution. Everything above makes maps smaller or keeps their size. The layer that makes them larger is the transposed convolution (nn.ConvTranspose2d), which is used to upsample in segmentation and in image generators. P5.13 covers it.

Go deeper Full convolution and the transposed convolution

With padding p=k−1p=k-1 the kernel is allowed to overlap the image by a single pixel at each end. Every pixel is then read by exactly kk windows along a row, and the output is larger than the input: H+k−1H+k-1. This is mode='full' in NumPy and SciPy, and nn.Conv2d gives it too (a width of 8 becomes 9, 10 and 12 for k=2k=2, 3 and 5). The transposed convolution of P5.13 is related: it runs the shape arithmetic in the other direction, which is why it can upsample.

Go deeper Stacked dilations leave holes

One layer with d=2d=2 ignores the pixels between its taps. Stack two such layers and the offsets that can reach an output pixel are the sums of two taps from {−2,0,2}\{-2,0,2\}, which is {−4,−2,0,2,4}\{-4,-2,0,2,4\}: only 5 of the 9 offsets along each axis (25 of 81 in 2-D). Half of the pixels in the window are never used by either layer. Using different rates breaks the pattern: with rates 11, 22, 44 the offsets cover every integer from −7-7 to 77 along each axis. Networks that use dilation often vary the rate for this reason. P5.6 works out receptive fields in general.

Padding, stride and dilation: three ways to see it

Intuition

Think of reading a long strip of paper through a card with a window. The card is the kernel. Padding is blank paper glued to both ends of the strip, so the card can sit half over the end. Stride is how far you slide the card each time: a larger step means fewer positions and a shorter result. Dilation is a card with the holes punched apart: it covers more of the strip with the same number of holes.

The picture breaks in two places. The blank paper is zeros the network can see, and a network can learn that a column of zeros means “edge”, which a real margin would not tell it. And the holes in a dilated card see nothing of what lies between them, while a larger window with all its holes would.

Math

The padded length is H+2pH+2p and a window with effective kernel size keff=d(k−1)+1k_{\text{eff}}=d(k-1)+1 starting at jsjs ends at js+keff−1js+k_{\text{eff}}-1. It fits when js+keff−1≤H+2p−1js+k_{\text{eff}}-1\le H+2p-1, so

j≤H+2p−keffs,Hout=⌊H+2p−keffs⌋+1.\begin{aligned} j&\le\frac{H+2p-k_{\text{eff}}}{s},\\ H_{\text{out}}&=\left\lfloor\frac{H+2p-k_{\text{eff}}}{s}\right\rfloor+1 . \end{aligned}

Since H+2p−keff=H+2p−d(k−1)−1H+2p-k_{\text{eff}}=H+2p-d(k-1)-1, this is the formula above. Same padding. At stride 1, Hout=H+2p−keff+1H_{\text{out}}=H+2p-k_{\text{eff}}+1, which equals HH when p=(keff−1)/2=d(k−1)/2p=(k_{\text{eff}}-1)/2=d(k-1)/2. This is a whole number when kk is odd (or dd is even). For k=3k=3, d=2d=2: p=2p=2.

Unread cells. The last window ends at padded index (Hout−1)s+keff−1=H+2p−1−r(H_{\text{out}}-1)s+k_{\text{eff}}-1=H+2p-1-r with r=(H+2p−keff) mod sr=(H+2p-k_{\text{eff}})\bmod s, so the last rr padded cells are never read and max⁡(0,r−p)\max(0,r-p) of them are real pixels. Cells inside the image can also be unread: when s>keffs>k_{\text{eff}}, or when the taps js+idjs+id of all windows miss a residue class (for k=3k=3, d=2d=2, s=2s=2 only even positions are read). The widget finds them by counting.

Cost. Parameters: k2CinCout+Coutk^2C_{\text{in}}C_{\text{out}}+C_{\text{out}}. Multiply-adds: HoutWoutk2CinCoutH_{\text{out}}W_{\text{out}}k^2C_{\text{in}}C_{\text{out}}. In 2-D the number of windows that read the pixel (i,j)(i,j) is uiuju_iu_j, where uiu_i is the 1-D count along the rows and uju_j along the columns.

Code

PyTorch shapes for the settings of this lesson, on a tensor of shape (N,C,H,W)=(1,1,32,32)(N,C,H,W)=(1,1,32,32). The code was run locally with PyTorch 2.9.1.

import torch
import torch.nn as nn
import torch.nn.functional as F

x = torch.zeros(1, 1, 32, 32)            # (N, C, H, W)

def size(**kw):
    """Output height and width of one nn.Conv2d on x."""
    return tuple(nn.Conv2d(1, 1, **kw)(x).shape[2:])

print("valid       ", size(kernel_size=3))
print("padding=1   ", size(kernel_size=3, padding=1))
print("'same'      ", size(kernel_size=3, padding="same"))
print("stride 2    ", size(kernel_size=3, padding=1, stride=2))
print("dilation 2  ", size(kernel_size=3, dilation=2))
print("d=2, p=2    ", size(kernel_size=3, dilation=2, padding=2))
print("k=5, s=2    ", size(kernel_size=5, stride=2))

try:
    nn.Conv2d(1, 1, 3, stride=2, padding="same")
except ValueError:
    print("'same' with stride 2: ValueError")
try:
    nn.Conv2d(1, 1, 5)(torch.zeros(1, 1, 3, 3))
except RuntimeError:
    print("5x5 kernel on 3x3: RuntimeError")

# the weights do not depend on padding, stride or dilation
for kw in (dict(), dict(padding=1), dict(stride=2), dict(dilation=2)):
    conv = nn.Conv2d(1, 1, 3, **kw)
    print(kw, "->", sum(p.numel() for p in conv.parameters()), "parameters")

# the stack of the lesson
layers = [nn.Conv2d(1, 1, 5), nn.Conv2d(1, 1, 3, stride=2),
          nn.Conv2d(1, 1, 3, stride=2, padding=1),
          nn.Conv2d(1, 1, 3, dilation=2, padding=2)]
h = x
for layer in layers:
    h = layer(h)
    print("->", tuple(h.shape[2:]))

# padding modes on one row
row = torch.tensor([[[1.0, 2.0, 3.0, 4.0]]])
for mode in ("constant", "reflect", "replicate", "circular"):
    print(f"{mode:9s}", F.pad(row, (2, 2), mode=mode).flatten().int().tolist())

Output:

valid        (30, 30)
padding=1    (32, 32)
'same'       (32, 32)
stride 2     (16, 16)
dilation 2   (28, 28)
d=2, p=2     (32, 32)
k=5, s=2     (14, 14)
'same' with stride 2: ValueError
5x5 kernel on 3x3: RuntimeError
{} -> 10 parameters
{'padding': 1} -> 10 parameters
{'stride': 2} -> 10 parameters
{'dilation': 2} -> 10 parameters
-> (28, 28)
-> (13, 13)
-> (7, 7)
-> (7, 7)
constant  [0, 0, 1, 2, 3, 4, 0, 0]
reflect   [3, 2, 1, 2, 3, 4, 3, 2]
replicate [1, 1, 1, 2, 3, 4, 4, 4]
circular  [3, 4, 1, 2, 3, 4, 1, 2]

k=5, s=2 gives ⌊27/2⌋+1=14\lfloor 27/2\rfloor+1=14, and the 27 is odd, so one row is lost. In the framework the same shapes come out for every setting the formula allows, which a check over all 6300 combinations of sizes 1 to 15, kernels 1 to 7, paddings 0 to 4, strides 1 to 4 and dilations 1 to 3 confirmed: 4916 give a valid shape, all matching the formula, and in the other 1384 the formula gives 0 or less and PyTorch raised an error.

Try it in Python

The first cell writes the convolution of P5.2 with padding, stride and dilation added, then compares its output shape with the formula and counts how many windows read each input position. The second runs the stack of this lesson and finds how many valid 3×33\times3 layers fit on a 32×3232\times32 image.

Convolution with padding, stride and dilation

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

Running the cell gives shapes 6×66\times6, 8×88\times8, 4×44\times4, 3×33\times3, 4×44\times4 and 8×88\times8 for the six settings, each equal to the formula. The 1-D read counts for H=8H=8 are [1,2,3,3,3,3,2,1][1,2,3,3,3,3,2,1] (valid), [2,3,3,3,3,3,3,2][2,3,3,3,3,3,3,2] (p=1p=1), [1,1,2,1,2,1,1,0][1,1,2,1,2,1,1,0] (s=2s=2) and [1,2,1,2,1,2,1,1][1,2,1,2,1,2,1,1] (p=1p=1, s=2s=2), and the outer product for H=5H=5 is the matrix at the top of the lesson.

A stack of layers, and how deep valid mode can go

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

Running the cell gives 32→28→13→7→732\to28\to13\to7\to7, then 15 valid layers with a 2×22\times2 map left.

Common mistakes

Quiz

Check your understanding

  1. An input is 28×2828\times28, with a 5×55\times5 kernel, no padding, stride 1 and dilation 1. What is the output size?

  2. A 3×33\times3 kernel has dilation 3 and stride 1. What padding keeps the output the same size as the input?

  3. A row of 8 pixels is read by a kernel of 3 with stride 2 and no padding. Which pixels are never read?

  4. A layer uses p=1p=1 and a 3×33\times3 kernel on a 32×3232\times32 map. The stride is changed from 1 to 2. What happens to the number of weights and to the multiply-adds?

  5. Which statement about PyTorch's padding='same' in nn.Conv2d is correct?

Exercises

  1. A layer has H=224H=224, k=7k=7, p=3p=3, s=2s=2 and d=1d=1. What is the output size?
    Show answer⌊(224+6−6−1)/2⌋+1=⌊223/2⌋+1=111+1=112\lfloor(224+6-6-1)/2\rfloor+1=\lfloor223/2\rfloor+1=111+1=112. This is the size after the first layer of ResNet-18 in torchvision (a 7×77\times7 convolution with stride 2 and padding 3 on a 224×224224\times224 image).
  2. What padding keeps the size of a map for a 5×55\times5 kernel with dilation 2 and stride 1? What is the effective kernel size?
    Show answerThe effective kernel size is 2(5−1)+1=92(5-1)+1=9, so p=(9−1)/2=4p=(9-1)/2=4. This equals d(k−1)/2=2⋅4/2=4d(k-1)/2=2\cdot4/2=4.
  3. A layer maps 3 channels to 16 channels with a 3×33\times3 kernel, p=1p=1, on a 32×3232\times32 map. How many parameters does it have and how many multiply-adds? What are they with stride 2?
    Show answerParameters: 3⋅3⋅3⋅16+16=4483\cdot3\cdot3\cdot16+16=448, the same for any stride. Multiply-adds: 32⋅32⋅9⋅3⋅16=44236832\cdot32\cdot9\cdot3\cdot16=442368 with stride 1, and 16⋅16⋅9⋅3⋅16=11059216\cdot16\cdot9\cdot3\cdot16=110592 with stride 2, a quarter.
  4. A 64×6464\times64 map goes through four layers: (k=3k=3, p=1p=1, s=1s=1), (k=3k=3, p=1p=1, s=2s=2), (k=5k=5, p=0p=0, s=2s=2) and (k=3k=3, p=1p=1, s=2s=2). What is the size after each layer? In which layer is a real row never read?
    Show answer64→64→32→14→764\to64\to32\to14\to7. In the third layer the numerator is 32−5=2732-5=27, which is odd, so r=1r=1 and p=0p=0: one real row and column are skipped. In the fourth, r=1r=1 too, but p=1p=1, so the one unread cell is a padding zero and no real row is lost.
  5. A 7×77\times7 input goes into a 3×33\times3 kernel with dilation 4 and no padding. What does the formula give? What would fix it?
    Show answer⌊(7−8−1)/1⌋+1=−1\lfloor(7-8-1)/1\rfloor+1=-1, so PyTorch raises an error: the effective kernel size is 9, larger than the 7 pixels of input. Padding p=1p=1 gives 11 (a single window), p=2p=2 gives 33, and a smaller dilation also works (d=3d=3 has keff=7k_{\text{eff}}=7 and gives 11).

Next: P5.5 gives the kernel its channels, so that a layer reads colour images and produces many feature maps, and 1×11\times1 convolutions mix channels. P5.6 takes up pooling and the receptive field, and P5.7 builds a whole CNN where the arithmetic of this lesson fixes every shape.

Key takeaways

  • A convolution with no padding shrinks the map and reads border pixels less often (on a 5×55\times5 input with a 3×33\times3 kernel, a corner pixel is read once and the centre pixel nine times). Zero padding adds pp rows and columns of zeros on each side.
  • The output size along one axis is ⌊(H+2p−d(k−1)−1)/s⌋+1\lfloor (H+2p-d(k-1)-1)/s\rfloor+1, the formula in the PyTorch documentation. d(k−1)+1d(k-1)+1 is the effective kernel size, and a result of 0 or less is an error.
  • With stride 1 and an odd kernel, p=d(k−1)/2p=d(k-1)/2 keeps the size. PyTorch's padding='same' does this for you and is not allowed with a stride other than 1.
  • A stride ss divides each side of the map by about ss. Let r=(H+2p−d(k−1)−1) mod sr=(H+2p-d(k-1)-1)\bmod s. The last rr padded cells are never read, so max⁡(0,r−p)\max(0,r-p) real rows and columns at the end are skipped: with H=8H=8, k=3k=3, s=2s=2, p=0p=0 the output is 3 and the last row (row 7) is skipped. A stride larger than the effective kernel size, or a dilation that shares a factor with the stride, can also skip rows inside the image.
  • Dilation spreads the k×kk\times k taps apart: same weights, larger window with holes. None of the three settings changes the parameter count (k2CinCout+Coutk^2C_{\text{in}}C_{\text{out}}+C_{\text{out}}); the multiply-adds follow the output size.
Found a mistake? Tell us