A convolution with no padding takes two rows and two columns off the map. Apply it to a image 15 times in a row and a 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 kernel over an 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 positions along each side. Two things follow.
The map shrinks. A image with a kernel gives a map. Every layer loses rows and columns, and the loss adds up over layers.
Borders are read less. Count how many windows read each pixel of a image (running the kernel in valid mode gives these counts):
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 rows and columns of zeros on every side of the input before the kernel slides. The padded input has size along each side, and the kernel now starts and ends over the margin.
With on the same image, the kernel has 5 positions along each side, so the output is , and the read counts become
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
which is 1 for , 2 for and 3 for . 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 , and this equals exactly when .) 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 , and 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, andnn.Conv2d(1, 1, 3, stride=2, padding='same')raises aValueError.
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 ).
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 with two cells added on each side:
- zeros:
- reflect: (a mirror that does not repeat the edge pixel)
- replicate: (the edge pixel repeated)
- circular: (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 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 -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 –, – and –. 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 : 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 map, kernel, , going from stride 1 to stride 2 turns a output into a 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 kernel with stride 2 reads every other pixel, on a row of 6. Dilation can cause the same at a smaller stride: with , and on a row of 9, the counts are , because every window reads only even positions.
Dilation: spread the taps apart
Dilation is the gap between the taps of the kernel. With the taps touch, as in an ordinary kernel. With a kernel reads pixels two apart: on one row it reads positions , and and skips and . The 9 weights are the same weights, but they now look at a 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
The first and last tap are pixels apart, and the counts the pixel at the start. For : gives 3, gives 5, gives 9.
Dilation is not the same as a larger kernel. A kernel has 25 weights and reads every pixel in its window, while a kernel with 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 along each side, and the kernel covers of it. The first window starts at index 0, the next at , then , and so on, and the last window must end inside the padded input: . The number of windows is
This is the formula in the PyTorch nn.Conv2d documentation. The documentation writes the 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 . 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):
- , , valid, stride 1: .
- , , , : , so .
- , , : .
- , , , valid: , so .
If the formula gives or less, the kernel does not fit in the padded input and PyTorch raises a RuntimeError. For example, a kernel on a input gives .
Which rows are never read? Let be the remainder of the numerator divided by , . The last window ends cells before the end of the padded input, so the last padded cells are never read. Of those, are padding zeros, so real rows and columns at the end are skipped. This is the whole story when 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 , , and : and one row is lost. (With on the same row, and the last two rows are lost: windows cover – and –.) With the numerator is and again, but now that zero is padding and no real row is lost (reads , 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.
Things to try, each of which the formula predicts:
- Press Valid: 3×3 on 8. The output is . Switch to the read counts: the corner is read once and the centre pixels nine times.
- Press Same: p = 1. The output is , the same as the input, and the corner is now read four times.
- Press Floor: 8, s = 2. The output is 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.
- Press Dilated: d = 2. The taps are spread out over a window, the output is , and the weight count is still 9.
- Press Too big: k = 5 on 3. The red message appears: the formula gives .
- From the Valid preset, set and . 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 input channels and output channels has parameters, and , and are not in the formula (P5.5 explains the channels). With one channel in and one out, a layer has 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 multiply-adds, so a layer costs
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 map and one channel pair, the cost of a kernel is:
- valid: ;
- : ;
- , : , a quarter of the previous line;
- , valid: ;
- , : , the same as , , with a window.
So padding makes the output, and the cost, larger, stride makes them smaller by about , and dilation costs nothing in weights or multiply-adds beyond what its output size implies. A kernel with on the same map costs , nearly three times as much as the dilated .
A worked stack
Sizes through a short stack, starting from a image. Each line is the formula with the layer’s settings (PyTorch gives the same shapes):
- , , : .
- , , : . The remainder is 1, so the last row and column of the map are never read.
- , , : .
- , , , : , size kept (same padding for a dilated kernel).
So . 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 valid layers on a image can have at most 15 layers (the map is then ).
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 the kernel is allowed to overlap the image by a single pixel at each end. Every pixel is then read by exactly windows along a row, and the output is larger than the input: . This is mode='full' in NumPy and SciPy, and nn.Conv2d gives it too (a width of 8 becomes 9, 10 and 12 for , 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 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 , which is : 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 , , the offsets cover every integer from to 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 and a window with effective kernel size starting at ends at . It fits when , so
Since , this is the formula above. Same padding. At stride 1, , which equals when . This is a whole number when is odd (or is even). For , : .
Unread cells. The last window ends at padded index with , so the last padded cells are never read and of them are real pixels. Cells inside the image can also be unread: when , or when the taps of all windows miss a residue class (for , , only even positions are read). The widget finds them by counting.
Cost. Parameters: . Multiply-adds: . In 2-D the number of windows that read the pixel is , where is the 1-D count along the rows and along the columns.
Code
PyTorch shapes for the settings of this lesson, on a tensor of shape . 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 , 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 layers fit on a image.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the cell gives shapes , , , , and for the six settings, each equal to the formula. The 1-D read counts for are (valid), (), () and (, ), and the outer product for is the matrix at the top of the lesson.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Running the cell gives , then 15 valid layers with a map left.
Common mistakes
Quiz
Check your understanding
An input is , with a kernel, no padding, stride 1 and dilation 1. What is the output size?
The formula gives . The size forgets the for the first window. The size would need padding . The size would need padding .
A kernel has dilation 3 and stride 1. What padding keeps the output the same size as the input?
The effective kernel size is , so the padding needed is . The padding is the one for an undilated kernel and ignores the dilation. With the output is 2 pixels smaller than the input along each axis, and with it is 2 pixels larger.
A row of 8 pixels is read by a kernel of 3 with stride 2 and no padding. Which pixels are never read?
The windows start at 0, 2 and 4 and cover pixels 0 to 6, so the output has 3 values and pixel 7 is left out. Pixel 0 is read by the first window. A fourth window would run past the end, which is why one pixel is missed. Every second pixel would be skipped only if the kernel were 1 wide.
A layer uses and a kernel on a map. The stride is changed from 1 to 2. What happens to the number of weights and to the multiply-adds?
The weights depend on the kernel size and the channels, not on the stride. The output goes from to , so the multiply-adds go from to , a quarter, because both sides are halved. A stride acts on both axes, so the factor is not a half. The multiply-adds follow the output size and do change.
Which statement about PyTorch's
padding='same'innn.Conv2dis correct?The documentation says this mode does not support any stride other than 1, and creating a stride-2 layer with it raises a ValueError. It does not keep the size for any stride. It does not change the amount of padding with the stride, and no rounding is offered for strides above 1.
Exercises
- A layer has , , , and . What is the output size?
Show answer
. This is the size after the first layer of ResNet-18 in torchvision (a convolution with stride 2 and padding 3 on a image). - What padding keeps the size of a map for a kernel with dilation 2 and stride 1? What is the effective kernel size?
Show answer
The effective kernel size is , so . This equals . - A layer maps 3 channels to 16 channels with a kernel, , on a map. How many parameters does it have and how many multiply-adds? What are they with stride 2?
Show answer
Parameters: , the same for any stride. Multiply-adds: with stride 1, and with stride 2, a quarter. - A map goes through four layers: (, , ), (, , ), (, , ) and (, , ). What is the size after each layer? In which layer is a real row never read?
Show answer
. In the third layer the numerator is , which is odd, so and : one real row and column are skipped. In the fourth, too, but , so the one unread cell is a padding zero and no real row is lost. - A input goes into a kernel with dilation 4 and no padding. What does the formula give? What would fix it?
Show answer
, so PyTorch raises an error: the effective kernel size is 9, larger than the 7 pixels of input. Padding gives (a single window), gives , and a smaller dilation also works ( has and gives ).
Next: P5.5 gives the kernel its channels, so that a layer reads colour images and produces many feature maps, and 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.