TExcelTAD
Home › Math for Deep Learning & LLMs › Padding, Stride and Output Shapes

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 nn, kernel size kk, padding pp (zeros added on each side), stride ss and dilation dd:

nout=⌊n+2p−d(k−1)−1s⌋+1n_{\text{out}} = \left\lfloor\frac{n + 2p - d(k - 1) - 1}{s}\right\rfloor + 1

With d=1d = 1 this is ⌊(n+2p−k)/s⌋+1\lfloor (n + 2p - k)/s \rfloor + 1. In 2-D the formula applies to height and width separately.

Setting Effect
p=0p = 0 ("valid") output shrinks by k−1k - 1
p=(k−1)/2p = (k - 1)/2, s=1s = 1 ("same", odd kk) output size equals input size
s=2s = 2 output roughly halves (downsampling)
d=2d = 2 kernel covers 2k−12k - 1 positions with kk weights
python · try it yourself
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 3×33 \times 3 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:

nout=(n−1)s−2p+d(k−1)+1n_{\text{out}} = (n - 1)s - 2p + d(k - 1) + 1

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.

python · try it yourself
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.ConvTranspose2d has an output_padding argument to resolve the ambiguity the floor creates.
  • Vision transformers turn an image into tokens with a "patchify" convolution with k=s=16k = s = 16: non-overlapping 16×1616 \times 16 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 224×224224 \times 224 image passes through a 7×77 \times 7 convolution with stride 2 and padding 3. What is the output size?

Answer

112×112112 \times 112.

Solution

⌊(224+6−7)/2⌋+1=⌊111.5⌋+1=112\lfloor (224 + 6 - 7)/2 \rfloor + 1 = \lfloor 111.5 \rfloor + 1 = 112.

Exercise 2: Same padding

What padding keeps the size unchanged for a 5×55 \times 5 kernel with stride 1, and for a 3×33 \times 3 kernel with dilation 2?

Answer

p=2p = 2 in both cases.

Solution

We need 2p=d(k−1)2p = d(k - 1): 2p=42p = 4 for k=5,d=1k = 5, d = 1, and 2p=2⋅2=42p = 2 \cdot 2 = 4 for k=3,d=2k = 3, d = 2.

Exercise 3: Patchify (code)

How many tokens does a ViT get from a 224×224224 \times 224 image with 16×1616 \times 16 patches? Use the formula.

Answer
Solution

k=s=16k = s = 16, p=0p = 0: (224−16)/16+1=14(224 - 16)/16 + 1 = 14 per side, 142=19614^2 = 196.

python · try it yourself
n = (224 - 16) // 16 + 1
print(n, n * n)
14 196

Test yourself

Input length 32, kernel 3, padding 1, stride 2. Output length?

  1. 15
  2. 16
  3. 30
  4. 32

For stride 1 and an odd kernel size kk, which padding gives 'same' output size?

  1. kk
  2. (k−1)/2(k - 1)/2
  3. 0
  4. 2k2k

A transposed convolution is used to…

  1. downsample
  2. upsample, mapping a small feature map to a larger one
  3. normalize
  4. pool