Sub topic 9
Dilated Convolutions and Multi-Scale Context
This chapter assumes you know how a convolution works, what stride and padding do, and the encoder-decoder pattern for segmentation from the previous chapter. You should be comfortable reading PyTorch code.
The problem: resolution against context
A classification backbone such as ResNet downsamples the image by 32 through strided convolutions and pooling. That is fine for one label per image. For segmentation, a 32x smaller feature map cannot place object boundaries accurately, and thin or small objects can vanish.
Each pixel's prediction needs two things that pull against each other:
- Fine spatial detail, which means high-resolution feature maps.
- Wide context, which means a large receptive field. The receptive field is the region of the input image that can influence one output value. A patch of road texture is ambiguous until the network sees the cars and buildings around it.
Encoder-decoder networks recover detail by upsampling and skip connections. Dilated convolutions take a different route. They keep the feature map large and grow the receptive field without extra downsampling.
How a dilated convolution works
A dilated (or atrous) convolution inserts gaps between the kernel taps. With dilation rate d, a kernel of size k samples inputs d pixels apart. Its effective size is:
k_eff = k + (k - 1) * (d - 1)A 3x3 kernel with d = 2 covers a 5x5 area and d = 4 covers 9x9. The parameter count and the multiply-adds per output pixel stay the same as a plain 3x3 convolution. Only the sampling pattern changes. Setting d = 1 gives an ordinary convolution.
To keep the output size, a 3x3 convolution with dilation d needs padding = d.
Computing receptive fields
For a stack of layers, each with kernel k, stride s, and dilation d, the receptive field grows by (k - 1) * d * jump at each layer. Here jump is the product of the strides of all earlier layers.
def receptive_field(layers):
# layers: list of (kernel, stride, dilation)
rf, jump = 1, 1
for k, s, d in layers:
rf += (k - 1) * d * jump
jump *= s
return rf
print(receptive_field([(3, 1, 1)] * 3)) # 7
print(receptive_field([(3, 1, 1), (3, 1, 2), (3, 1, 4)])) # 15
print(receptive_field([(3, 1, 1), (3, 1, 2), (3, 1, 5)])) # 17Three plain 3x3 layers see a 7x7 window. Rates 1, 2, 4 see 15x15 for the same cost.
Dilated backbones and output stride
In a ResNet, the later stages normally halve the resolution. To make a dilated backbone, you remove the stride from those stages and give the convolutions that follow dilation rates that compensate. The ratio of input size to feature-map size is the output stride.
| Output stride | Change to ResNet | Feature map for 512x512 input | Cost |
|---|---|---|---|
| 32 | none (standard) | 16x16 | lowest |
| 16 | last stage dilated (d=2) | 32x32 | moderate |
| 8 | last two stages dilated (d=2, d=4) | 64x64 | highest memory and compute |
Output stride 16 is a common compromise for training. Output stride 8 gives sharper results but costs noticeably more. The pretrained weights still work because the kernels keep the same shape. Only the sampling pattern changes.
The gridding artifact
Stacking dilated layers with the same rate causes gridding. The layers sample only a sparse lattice of input pixels, and neighbouring positions never contribute to each other. The next snippet shows this in one dimension.
def reachable_offsets(dilations):
offsets = {0}
for d in dilations:
offsets = {o + s * d for o in offsets for s in (-1, 0, 1)}
return sorted(offsets)
print(reachable_offsets([2, 2, 2])) # [-6, -4, -2, 0, 2, 4, 6]
print(reachable_offsets([1, 2, 5])) # every integer from -8 to 8Three layers at rate 2 see only even offsets, so odd-offset pixels are invisible to the output. Rates 1, 2, 5 cover every offset from -8 to 8 with no holes. This is the idea behind hybrid dilated convolution. Use rates that do not share a common factor greater than 1 and that keep the covered region contiguous.
Multi-scale context with ASPP
A single dilation rate sees objects at one scale. Segmentation scenes mix scales, such as a distant pedestrian and a nearby bus. Atrous Spatial Pyramid Pooling (ASPP), used in DeepLab, applies several dilated convolutions in parallel to the same feature map and fuses the results.
The DeepLabv3 version has five branches:
- A 1x1 convolution.
- Three 3x3 convolutions with rates 6, 12, 18 (for output stride 16).
- Image-level pooling: global average pooling, a 1x1 convolution, then upsampling back to the feature map size.
The branch outputs are concatenated and projected back with a 1x1 convolution. At output stride 8 the rates are doubled (12, 24, 36).
Here is a runnable PyTorch implementation:
import torch
from torch import nn
import torch.nn.functional as F
class ASPP(nn.Module):
def __init__(self, in_ch, out_ch=256, rates=(6, 12, 18)):
super().__init__()
def conv_bn_relu(k, d):
return nn.Sequential(
nn.Conv2d(in_ch, out_ch, k, padding=0 if k == 1 else d,
dilation=d, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
self.branches = nn.ModuleList(
[conv_bn_relu(1, 1)] + [conv_bn_relu(3, r) for r in rates]
)
self.pool = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_ch, out_ch, 1, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
self.project = nn.Sequential(
nn.Conv2d(out_ch * (len(rates) + 2), out_ch, 1, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
def forward(self, x):
outs = [b(x) for b in self.branches]
pooled = self.pool(x)
outs.append(F.interpolate(pooled, size=x.shape[-2:],
mode="bilinear", align_corners=False))
return self.project(torch.cat(outs, dim=1))
aspp = ASPP(in_ch=512)
x = torch.randn(2, 512, 33, 33)
print(aspp(x).shape) # torch.Size([2, 256, 33, 33])Alternatives and trade-offs
| Approach | How it gets context | Strength | Weakness |
|---|---|---|---|
| Dilated backbone | Larger receptive field at high resolution | Sharp maps, no extra parameters | High memory and compute |
| ASPP | Parallel dilated branches | Handles mixed object scales | Rates must suit the feature map size |
| Pyramid pooling (PSPNet) | Pools at several grid sizes, then upsamples | Strong global scene context | Coarse pooled features |
| Encoder-decoder with skips | Downsample, then recover detail | Cheap, good boundaries | Context depends on encoder depth |
Many models combine these. DeepLabv3+ attaches an ASPP module to a dilated encoder and adds a light decoder that merges low-level features for sharper edges.
Common errors
- Wrong padding. With
dilation=dandkernel_size=3, forgettingpadding=dshrinks the output and breaks concatenation in ASPP. - Rates that ignore resolution. Rates tuned for 513x513 crops may be too large for small inputs, so branches degenerate to 1x1.
- Mismatched output stride. Using rates 6, 12, 18 on an output-stride-8 backbone gives a smaller receptive field than the model was designed for.
- Gridding. Repeating one rate in a stack produces blocky, speckled predictions.
Exercise
A stack of four 3x3 stride-1 layers uses dilation rates 1, 2, 4, 8. What is the receptive field, and do the layers sample every pixel inside it? Then compare with rates 2, 4, 8, 16 in the first layer onward.
Show answer
Each layer adds (k-1)d = 2d, so the receptive field is 1 + 2(1+2+4+8) = 31. The reachable offsets are sums of {-d, 0, d}, and with rates 1, 2, 4, 8 they cover every integer from -15 to 15, so there are no holes. With rates 2, 4, 8, 16 the field is 1 + 2*30 = 61, but every reachable offset is even, so odd-offset pixels are never seen. This is gridding, caused by a common factor of 2 in all rates.