Sub topic 8
Encoder-Decoder Networks and Upsampling
This chapter assumes you can read PyTorch code and know how convolution, stride, padding and pooling change a feature map's size. It also assumes you know what a classification backbone such as a ResNet produces. The chapter shows how to turn that backbone into a model that predicts a class for every pixel.
Why a classifier cannot segment as it is
A classification network shrinks the image on purpose. Each stride-2 convolution or pooling layer halves the height and width. After five of them, a 512×512 image becomes a 16×16 grid of features. That grid has strong semantic content but little spatial detail. Segmentation needs a prediction at every pixel, so the network must recover the lost resolution.
Two ideas make this work:
- Make the network fully convolutional, so it outputs a map instead of one vector.
- Add a decoder that upsamples the coarse features back toward the input size.
Fully convolutional networks
A fully convolutional network (FCN) has no fully connected layers. The classifier head's dense layers become 1×1 convolutions. A 1×1 convolution applies the same linear map to the feature vector at every location. Its output is a grid of class scores, called logits.
Two consequences follow:
- The network accepts any input size, because convolutions do not depend on image dimensions.
- The raw output is coarse. The ratio between input size and output size is the output stride. A stride of 32 means each output cell covers a 32×32 patch of pixels.
The original FCN paper upsampled these coarse logits directly. FCN-32s did this from the last layer only. FCN-16s and FCN-8s added scores from earlier, finer layers. This is the first form of a skip connection.
The encoder-decoder shape
The encoder is the downsampling path, usually a pretrained backbone. The decoder is the upsampling path. Skip connections carry high-resolution features from the encoder to the matching decoder stage.
The encoder knows what is in the image but not exactly where. Early encoder layers know where edges are but not what they belong to. The skip connection lets the decoder combine both.
Upsampling methods
| Method | Learnable | How it works | Typical issue |
|---|---|---|---|
| Nearest neighbor | No | Copies each value into a block | Blocky output |
| Bilinear interpolation | No | Weighted average of the four nearest values | Smooth but cannot add detail |
| Transposed convolution | Yes | Scatters each input value through a kernel into a larger output | Checkerboard artifacts when kernel size is not divisible by stride |
| Pixel shuffle | Yes | A convolution produces extra channels that are rearranged into space | Needs a channels-to-space layout to be learned |
| Max unpooling | No | Puts values back at the positions the max pool recorded | Needs stored indices (SegNet) |
For a transposed convolution the output size is (in - 1) * stride - 2 * padding + kernel. With kernel 2, stride 2 and padding 0, the size exactly doubles. Kernel 4, stride 2 and padding 1 also doubles it.
Two ways to use skip connections
- Addition (FCN): add the upsampled coarse scores to scores from a finer layer. Channel counts must match, and the result is cheap.
- Concatenation (U-Net): stack the encoder feature map and the upsampled decoder map along the channel axis, then convolve. The decoder learns how to mix them. This uses more memory but preserves more detail, and it is the usual choice for medical and small-dataset work.
A runnable two-level U-Net
The model below doubles resolution with transposed convolutions and concatenates skips. It uses padding 1 in each 3×3 convolution so sizes stay aligned.
import torch
from torch import nn
def block(c_in, c_out):
return nn.Sequential(
nn.Conv2d(c_in, c_out, 3, padding=1, bias=False),
nn.BatchNorm2d(c_out),
nn.ReLU(inplace=True),
nn.Conv2d(c_out, c_out, 3, padding=1, bias=False),
nn.BatchNorm2d(c_out),
nn.ReLU(inplace=True),
)
class TinyUNet(nn.Module):
def __init__(self, in_ch=3, num_classes=3, base=16):
super().__init__()
self.enc1 = block(in_ch, base)
self.enc2 = block(base, base * 2)
self.bottleneck = block(base * 2, base * 4)
self.pool = nn.MaxPool2d(2)
self.up2 = nn.ConvTranspose2d(base * 4, base * 2, kernel_size=2, stride=2)
self.dec2 = block(base * 4, base * 2)
self.up1 = nn.ConvTranspose2d(base * 2, base, kernel_size=2, stride=2)
self.dec1 = block(base * 2, base)
self.head = nn.Conv2d(base, num_classes, kernel_size=1)
def forward(self, x):
e1 = self.enc1(x) # (B, base, H, W)
e2 = self.enc2(self.pool(e1)) # (B, 2base, H/2, W/2)
b = self.bottleneck(self.pool(e2)) # (B, 4base, H/4, W/4)
d2 = self.dec2(torch.cat([self.up2(b), e2], dim=1))
d1 = self.dec1(torch.cat([self.up1(d2), e1], dim=1))
return self.head(d1) # (B, num_classes, H, W)
model = TinyUNet(num_classes=3)
x = torch.rand(2, 3, 64, 96) # H and W must be divisible by 4
target = torch.randint(0, 3, (2, 64, 96))
target[:, :4, :] = 255 # pixels to ignore
logits = model(x)
loional.cross_entropy(logits, target, ignore_index=255)
loss.backward()
print(logits.shape, float(loss))The printch.Size([2, 3, 64, 96]): one score per class at every input pixel. The loss ised on logits, not on softmax probabilities. cross_entropy` applies the log-softmax internally.
Practues
Odd sizes break skips
Max pooling floors odd sizes. A height becomes 17, and upsampling 17 gives 34, which cannot be concatenated with arow skip. Fix it by padding the input to a multiple of the total stride, or by resizing the upsampled map to the skip's size with torch.nn.functional.interpolate(..., size=skip.shape[-2:], mode="bilinear", align_corners=False).
Output stride trades detail for context
A lower output stride gives finer boundaries but costs memory and compute at high resolution. A higher stride sees more context cheaply but blurs thin objects. Chapter material on dilated convolutions covers a way to keep context without shrinking further.
Where to compute the loss
You can upsample logits to full resolution and compare against the full-resolution mask. You can also downsample the mask and compute the loss at the output stride. The first is more accurate near edges. The second is cheaper but discards thin structures. Never downsample masks with bilinear interpolation, because it creates invalid fractional class ids. Use nearest neighbor.
Other common mistakes
- Evaluating with a different resize method than training. Keep the interpolation mode and
align_cornerssetting consistent. - Forgetting that BatchNorm statistics are unstable with batch sizes of 1 or 2. Use GroupNorm or freeze the backbone statistics.
- Bringing in pretrained weights but not the matching input normalization (mean and standard deviation).
What the decoder still cannot do
An encoder-decoder with a per-pixel softmax gives a semantic map. Every pixel gets one class, and two adjacent objects of the same class merge into one region. Separating them needs the instance methods covered in later chapters, such as Mask R-CNN. The decoder in those models is often the same idea, with a different head on top.
Exercise
You run TinyUNet on a 70×70 input and get an error from torch.cat. Explain why it happens and give two ways to fix it.
Show answer
The two max pools turn 70 into 35 and then into 17 (17.5 is floored). The decoder doubles 17 to 34, then compares it with the 35-pixel skip at that level. The sizes 34 and 35 differ, so concatenation fails. Fix 1: pad the input to a multiple of 4 (for example 72×72) and crop the output back to 70×70. Fix 2: in forward, resize the upsampled map to the skip's spatial size with torch.nn.functional.interpolate(..., size=skip.shape[-2:], mode="bilinear", align_corners=False) before concatenating.
Exercise
A transposed convolution has input height 24, kernel 4, stride 2 and padding 1. What is the output height? Why does this setting avoid uneven overlap better than kernel 3 with stride 2?
Show answer
Output height is (24 - 1) 2 - 2 1 + 4 = 48. Kernel 4 is divisible by stride 2, so every output pixel receives contributions from the same number of kernel positions. With kernel 3 and stride 2, some output pixels receive more contributions than others, which causes a checkerboard pattern.