Padding, Stride and Output Shapes
Every CNN architecture is, on paper, a sequence of shape calculations. Padding controls what happens at the borders, stride controls how far the filter jumps, and dilation spreads the filter out. One formula covers them all, and getting it right is the difference between a network that runs and one that crashes with a shape mismatch.
The output-size formula
For an input of length , kernel size , padding (zeros added on each side), stride and dilation :
With this is . In 2-D the formula applies to height and width separately.
| Setting | Effect |
|---|---|
| ("valid") | output shrinks by |
| , ("same", odd ) | output size equals input size |
| output roughly halves (downsampling) | |
| kernel covers positions with weights |
import numpy as np
def out_size(n, k, p=0, s=1, d=1):
return (n + 2 * p - d * (k - 1) - 1) // s + 1
def conv1d(x, w, p=0, s=1, d=1):
x = np.pad(x, p); k = len(w); span = d * (k - 1) + 1
return np.array([sum(w[j] * x[i + j * d] for j in range(k)) for i in range(0, len(x) - span + 1, s)])
x = np.arange(1, 11, dtype=float); w = np.array([1.0, 1.0, 1.0])
for p, s, d in [(0, 1, 1), (1, 1, 1), (1, 2, 1), (0, 1, 2), (2, 3, 1)]:
y = conv1d(x, w, p, s, d)
print(f"p={p} s={s} d={d}: formula {out_size(10, 3, p, s, d)}, actual {len(y)}, output {y}")p=0 s=1 d=1: formula 8, actual 8, output [ 6. 9. 12. 15. 18. 21. 24. 27.]
p=1 s=1 d=1: formula 10, actual 10, output [ 3. 6. 9. 12. 15. 18. 21. 24. 27. 19.]
p=1 s=2 d=1: formula 5, actual 5, output [ 3. 9. 15. 21. 27.]
p=0 s=1 d=2: formula 6, actual 6, output [ 9. 12. 15. 18. 21. 24.]
p=2 s=3 d=1: formula 4, actual 4, output [ 1. 9. 18. 27.]
Padding
Without padding, a deep stack of convolutions shrinks the image by 2 pixels per layer and border pixels take part in fewer outputs than central ones. "Same" padding keeps the size and lets architectures be described purely by where they downsample. Zero padding is usual; reflection or circular padding avoid artificial edges in image generation.
Stride
A stride of 2 computes every second output, reducing the spatial size and the compute by about 4 in 2-D. Strided convolutions have largely replaced pooling for downsampling in modern CNNs. With stride, the formula's floor means some input positions at the end may be ignored.
Transposed convolution
Generators and segmentation networks need to upsample. A transposed convolution is the linear map whose matrix is the transpose of a strided convolution's matrix, so it maps the small shape back to the large one:
It is exactly the operation that the backward pass of a strided convolution performs on gradients (Backpropagation Through Convolutions). Uneven overlap of the kernel can produce checkerboard artifacts; resize-then-convolve avoids them.
import numpy as np
n, k, s = 8, 3, 2
m = (n - k) // s + 1
T = np.zeros((m, n))
for i in range(m):
T[i, i * s:i * s + k] = [1.0, 2.0, 1.0]
print("strided conv matrix:", T.shape, " transposed conv matrix:", T.T.shape)
print("transposed conv of [1, 0, 0]:", T.T @ np.array([1.0, 0.0, 0.0]))
print("formula for transposed output size:", (m - 1) * s + (k - 1) + 1)strided conv matrix: (3, 8) transposed conv matrix: (8, 3)
transposed conv of [1, 0, 0]: [1. 2. 1. 0. 0. 0. 0. 0.]
formula for transposed output size: 7
The transposed convolution gives length 7, not the original 8: the stride-2 convolution never used the last input position (the floor in the formula), and this ambiguity is what output_padding resolves.
In software
nn.Conv2d(..., padding="same")computes the padding for you (stride 1 only);nn.ConvTranspose2dhas anoutput_paddingargument to resolve the ambiguity the floor creates.- Vision transformers turn an image into tokens with a "patchify" convolution with : non-overlapping patches.
- Shape bugs are easiest to catch by passing a dummy tensor through the network and printing every layer's output shape.
Exercises
Exercise 1: ResNet stem
A image passes through a convolution with stride 2 and padding 3. What is the output size?
Answer
.
Solution
.
Exercise 2: Same padding
What padding keeps the size unchanged for a kernel with stride 1, and for a kernel with dilation 2?
Answer
in both cases.
Solution
We need : for , and for .
Exercise 3: Patchify (code)
How many tokens does a ViT get from a image with patches? Use the formula.
Answer
Solution
, : per side, .
n = (224 - 16) // 16 + 1
print(n, n * n)14 196
Test yourself
Input length 32, kernel 3, padding 1, stride 2. Output length?
- 15
- 16
- 30
- 32
For stride 1 and an odd kernel size , which padding gives 'same' output size?
- 0
A transposed convolution is used to…
- downsample
- upsample, mapping a small feature map to a larger one
- normalize
- pool