Padding, Stride, and Dilation

Dive into Deep Learning · §6.3

Padding, Stride, and Dilation
boundary control · spatial downsampling · dilated footprints · receptive-field growth

Three Geometric Dilemmas of Basic Convolutions

Motivation & Spatial Trade-Offs

  • Border erosion \to Padding (p): Ten unpadded 5 \times 5 layers shrink a 240 \times 240 image to 200 \times 200 (losing 30% of its area); padding p = (k-1)/2 preserves resolution.
  • Slow linear RF growth \to Stride (s): Stride-1 3 \times 3 layers need >110 layers to span 224 \times 224; stride s > 1 grows reach geometrically.
  • Full-res context \to Dilation (d): Spaces kernel taps d pixels apart without adding parameters.

Why Unpadded Convolutions Under-Sample Border Pixels

Boundary Pixel Utilization

Even in a single unpadded k \times k layer, pixels near the edge of the frame participate in far fewer sliding windows than interior pixels:

  • Interior vs. corner disparity: Any interior pixel at distance \ge k-1 from the border participates in k^2 windows (25 windows for a 5 \times 5 kernel), an edge pixel appears in at most k windows, and a corner pixel appears in only 1 window.
  • Cumulative center bias: Across stacked layers, unpadded convolutions exponentially down-weight information located near the perimeter of the image.

Zero Padding Restores Borders and Output Dimensions

Symmetric Per-Side Padding

Surrounding the input with p_\textrm{h} rows of zeros on both top and bottom and p_\textrm{w} columns on both left and right expands the effective input grid to (n_\textrm{h} + 2p_\textrm{h}) \times (n_\textrm{w} + 2p_\textrm{w}):

\textrm{Output shape} = (n_\textrm{h} + 2p_\textrm{h} - k_\textrm{h} + 1) \times (n_\textrm{w} + 2p_\textrm{w} - k_\textrm{w} + 1)

  • Shape-preserving (“same”) padding: Setting p_\textrm{h} = (k_\textrm{h}-1)/2 and p_\textrm{w} = (k_\textrm{w}-1)/2 cancels the k - 1 shrinkage so the output matches n_\textrm{h} \times n_\textrm{w}.
  • Example (3 \times 3 input, p=1, 2 \times 2 kernel): Padding expands 3 \times 3 \to 5 \times 5, yielding a 4 \times 4 output instead of 2 \times 2.

Why Convolutional Kernels Are Almost Always Odd

Grid Alignment Under Symmetric Padding

  • Odd k \in \{1, 3, 5, 7\}: k - 1 is even, so p = (k-1)/2 pads both sides equally and centers every window on input pixel (i, j).
  • Why even k is awkward: k - 1 is odd, forcing asymmetric padding (p_{\textrm{left}} \ne p_{\textrm{right}}) and a half-pixel coordinate shift between layers.

Verifying Shape-Preserving Padding in Code

Batch-and-Channel Wrapper Helper

Built-in 2D convolutional layers expect 4D tensors carrying batch and channel axes. Our helper comp_conv2d wraps a 2D matrix (H, W) with singleton batch/channel dimensions and returns the 2D spatial output:

def comp_conv2d(conv2d, X):
    """Apply a convolutional layer to a single-channel 2D input."""
    Y = conv2d(X.reshape((1, 1) + X.shape))  # input (1, 1, h, w)
    return Y.reshape(Y.shape[2:])
X = torch.rand(size=(8, 8))
conv2d = nn.LazyConv2d(1, kernel_size=3, padding=1)
comp_conv2d(conv2d, X).shape
torch.Size([8, 8])

Boundary Pitfalls: Zero Padding as a Dark Frame

Implicit Positional Leakage vs. Reflect/Replicate Padding

img = d2l.ones((5, 5))
d2l.corr2d(F.pad(img, (1, 1, 1, 1)), d2l.ones((3, 3)))
tensor([[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.]])
  • Border darkening (9 \to 6 \to 4): Zero padding creates an artificial dark frame that leaks absolute spatial position to deep layers.
  • Generative fix: Reflect or replicate padding preserves constant intensity up to the border.

Strided Convolutions: Downsampling the Grid

Stepping the Sliding Window by s > 1 Pixels

Instead of evaluating the kernel at every pixel (s = 1), a vertical stride s_\textrm{h} and horizontal stride s_\textrm{w} shift the window by s_\textrm{h} rows and s_\textrm{w} columns per step:

  • Example (s_\textrm{h} = 3, s_\textrm{w} = 2 on padded 3 \times 3):
    • Top-left window (gray): 0\cdot 0 + 0\cdot 1 + 0\cdot 2 + 0\cdot 3 = 0.
    • Shift 2 columns right (blue): 0\cdot 0 + 0\cdot 1 + 1\cdot 2 + 2\cdot 3 = 8.
    • Shift 3 rows down (orange): 0\cdot 0 + 6\cdot 1 + 0\cdot 2 + 0\cdot 3 = 6.
  • Compute savings: Evaluating every s-th row and column cuts output activations and multiply-adds by a factor of s_\textrm{h} s_\textrm{w}.

Deriving the Strided Output-Shape Formula

Counting Valid Steps Plus the Starting Position

h_\textrm{o} = \left\lfloor \frac{n_\textrm{h} + 2p_\textrm{h} - k_\textrm{h}}{s_\textrm{h}} \right\rfloor + 1

  • Step counting: After placing the first window of size k at index 0, the remaining n + 2p - k pixels fit \lfloor (n+2p-k)/s \rfloor steps of size s.
  • With “same” padding (2p = k - 1): Simplifies to h_\textrm{o} = \lceil n / s \rceil, cleanly dividing resolution by s.

Strided Downsampling in Code and Design Patterns

Three Canonical Padding-and-Stride Regimes

conv2d = nn.LazyConv2d(1, kernel_size=3, padding=1, stride=2)
comp_conv2d(conv2d, X).shape
torch.Size([4, 4])
  • Three standard regimes: Preserve resolution (k=3, p=1, s=1), halve resolution at stage boundaries (k=3, p=1, s=2), or partition into non-overlapping tokens (p=0, s=k).

Geometric Receptive-Field Growth Under Stride

How Early Strides Multiply All Downstream Kernels

r = 1 + \sum_{i=1}^{L} (k_i - 1) \prod_{j=1}^{i-1} s_j

  • Cumulative multiplier \prod_{j < i} s_j: Every early stride multiplies the spatial reach of all layers above it (and is independent of padding p).
  • Linear vs. geometric reach: Three 3 \times 3 layers cover r = 7 at s=(1,1,1) vs. r = 15 at s=(2,2,1).

Dilated Convolutions: Expanding Footprints at Stride 1

Spacing Kernel Taps Apart by Dilation Rate d

When a task demands a wide receptive field without losing spatial resolution (e.g., per-pixel semantic segmentation), dilation inserts spaces of d - 1 pixels between adjacent kernel taps:

  • Effective kernel size k': A k \times k kernel with dilation rate d spans: k' = k + (k - 1)(d - 1) = d(k - 1) + 1
  • Zero extra parameters or FLOPs: At d = 2, a 3 \times 3 kernel spans a 5 \times 5 footprint (k' = 2(2)+1 = 5) using only 9 weights and 9 multiply-adds per pixel instead of 25.

Unified Shape Formula: Padding, Stride & Dilation

Substituting Effective Kernel Size k’ = d(k - 1) + 1

Replacing k with k' = d(k - 1) + 1 in the strided output-shape formula yields one master equation governing every convolutional layer along an axis:

n_\textrm{out} = \left\lfloor \frac{n + 2p - d(k - 1) - 1}{s} \right\rfloor + 1

conv2d = nn.LazyConv2d(1, kernel_size=3, dilation=2)
conv5 = nn.LazyConv2d(1, kernel_size=5)
comp_conv2d(conv2d, X).shape, comp_conv2d(conv5, X).shape
(torch.Size([4, 4]), torch.Size([4, 4]))
  • Sanity check: On an 8 \times 8 unpadded input (p=0, s=1), a 3 \times 3 kernel at dilation d=2 has effective size k' = 5 and produces the exact same 4 \times 4 output shape as a dense 5 \times 5 kernel.

Strided vs. Dilated Towers: Reach vs. Density

Comparing Strides (2, 2, 1) Against Dilations (1, 2, 4)

Replacing k_i - 1 with k'_i - 1 = d_i(k_i - 1) in our receptive-field formula shows that doubling dilation rates d_i = 2^{i-1} at stride 1 grows the receptive field exponentially (r = 2^{L+1} - 1 for 3 \times 3 kernels):

  • (a) Strided tower (s = 2, 2, 1, d = 1, 1, 1): Reaches r = 1 + 2 + 4 + 8 = 15 input pixels, subsampling to every 4th spatial location (16\times cheaper in 2D).
  • (b) Dilated tower (s = 1, 1, 1, d = 1, 2, 4): Reaches the exact same r = 1 + 2(1) + 2(2) + 2(4) = 15 input pixels through identical tap wiring, while evaluating every spatial position at full resolution.

Systems Pitfall: Dilation Gridding Artifacts

Why Constant Dilation Schedules Create Blind Lattices

  • The gridding hazard: Constant dilation d = (4, 4, 4, 4) samples only offsets (i+4a, j+4b), reading just 81 of 1{,}089 pixels (7.4\%) inside its 33 \times 33 box.
  • Blind to thin structures: Small objects falling between the 4-pixel lattice lines never touch a weight.
  • Exponential fix: Doubling schedule d = (1, 2, 4, 8) bridges every gap for 100\% dense coverage (r = 31).

Concept Check: Shapes and Receptive Fields

Concept Check

Test your mastery of the unified shape and receptive-field equations:

  1. Unpadded vs. padded stack: What output shape comes out when a 28 \times 28 image passes through three unpadded 5 \times 5 layers at stride 1? What per-side padding p preserves 28 \times 28 through all three?
  2. ResNet-style stem: A 224 \times 224 image passes through a 7 \times 7 conv (p=3, s=2) followed by a 3 \times 3 conv (p=1, s=2). What is the output spatial shape after each layer, and what is the receptive field r of a unit after the second layer?
  3. Dilated shape-preserving padding: For a 3 \times 3 kernel with dilation d = 4 and stride s = 1, what per-side padding p preserves the input height and width?

Answers: (1) Each unpadded 5 \times 5 layer subtracts 4 pixels: 28 \to 24 \to 20 \to 16 (16 \times 16). Padding p = (5-1)/2 = 2 on each side keeps 28 \times 28. (2) Layer 1 output: \lfloor(224+6-7)/2\rfloor + 1 = 112 \times 112. Layer 2 output: \lfloor(112+2-3)/2\rfloor + 1 = 56 \times 56. Receptive field after Layer 2: r = 1 + (7-1)(1) + (3-1)(2) = 1 + 6 + 4 = 11 pixels. (3) The effective kernel size is k' = 4(3-1)+1 = 9, so shape-preserving padding requires p = (k'-1)/2 = 4 pixels per side.

Summary & Key Takeaways

Section Synthesis

Hyperparameter Effect on Output Size n_\textrm{out} Effect on Receptive Field r Systems & Architectural Role
Padding (p per side) Adds 2p to effective input length None (r is independent of p) Prevents border shrinkage; p = (k-1)/2 preserves H \times W at s=1
Stride (s) Divides output length by s (\approx \lceil n/s \rceil) Multiplies reach of all subsequent layers by s Cuts activations & MACs by s^2; grows RF geometrically
Dilation (d) Expands kernel k \to k' = d(k-1)+1 Adds d(k-1) \prod_{j<i} s_j to r Exponential RF growth at full resolution (0 extra params)
Master Formula \lfloor (n + 2p - d(k-1) - 1)/s \rfloor + 1 1 + \sum_{i=1}^L d_i(k_i - 1)\prod_{j<i} s_j Governs all 1D, 2D, and 3D convolutional & pooling layers

Next (§6.4): Extending convolutions from single-channel 2D grids to 3D stacks of input and output channels, accounting for the c_\textrm{i} c_\textrm{o} compute/memory cost, and building 1 \times 1 bottleneck layers.