Track feature map sizes through a stack of dilated convolutions

Before you train a CNN you need to know the spatial size after every layer, or the flatten and linear layers will not line up. Dilation spreads the kernel taps apart, so a 3x3 kernel with dilation 2 covers a 5x5 area.

Write conv_output_sizes(size, layers). size is the input height (an int). layers is a list of (kernel, stride, padding, dilation) tuples. Each layer gives out = floor((size + 2*padding - dilation*(kernel - 1) - 1) / stride) + 1. Return the list of sizes after each layer.

If a layer would give a size below 1, append 0 for that layer and stop.

Signaturedef conv_output_sizes(size, layers)

Example

conv_output_sizes(32, [(3, 1, 1, 1), (3, 2, 0, 2)]) is [32, 14].

Understand the idea

Each conv layer shrinks or keeps the feature map depending on kernel size, stride, padding and dilation. Dilation spreads the kernel taps apart with gaps, so a 3-tap kernel with dilation 2 actually spans 5 pixels. That effective span replaces the raw kernel size in the size formula. Worked example: input 10. Layer (kernel 3, stride 1, padding 0, dilation 2): span = 2 * (3 - 1) + 1 = 5, out = floor((10 + 0 - 4 - 1) / 1) + 1 = 6. Next layer (3, 2, 1, 1): out = floor((6 + 2 - 2 - 1) / 2) + 1 = floor(2.5) + 1 = 3. Answer [6, 3]. Rule: out = floor((size + 2 * padding - dilation * (kernel - 1) - 1) / stride) + 1, applied layer by layer with each output becoming the next input. If a layer's result is below 1, record 0 and stop. Getting this wrong is why a flatten and linear head refuses to line up. Dilated convs are used in segmentation models and audio models like WaveNet to see wide context cheaply.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleconv_output_sizes(32, [(3, 1, 1, 1), (3, 2, 0, 2)])
  • Sample 2: plain stackconv_output_sizes(64, [(7, 2, 3, 1), (3, 2, 1, 1), (3, 1, 1, 1)])
  • Test 3: dilated stackconv_output_sizes(40, [(3, 1, 2, 2), (3, 1, 4, 4), (5, 2, 0, 3)])
  • Test 4: collapses to zeroconv_output_sizes(9, [(3, 1, 0, 2), (3, 1, 0, 4), (3, 1, 0, 1)])