TExcelTAD

Training a Tiny U-Net

The semantic segmentation lesson ended with a per-pixel random forest that separated shapes from the background almost perfectly but could not tell a square from a circle: on 100 test scenes its mIoU was 0.397, with shape IoUs between 0.15 and 0.25. Its features saw at most a 17 x 17 window, and the class of a shape is in its whole outline. This lesson trains the network that fixes both problems at once, U-Net, on the same generated scenes, on a CPU in about 20 seconds, and measures what its parts are worth. It ends with the other big family of segmenters, DeepLab, and its dilated convolutions.

The architecture

Ronneberger, Fischer and Brox designed U-Net in 2015 for biomedical images, where labelled data are scarce and boundaries must be exact. It has two halves:

  • An encoder (contracting path): blocks of two 3×33 \times 3 convolutions, each block followed by 2×22 \times 2 max pooling. The resolution halves and the number of channels doubles at every step, so deep features see large regions ("this outline has corners") but at a coarse grid.
  • A decoder (expanding path): at every step a 2×22 \times 2 transposed convolution doubles the resolution, then the result is concatenated with the encoder feature map of the same size (the skip connection) and passed through another block of two convolutions. A final 1×11 \times 1 convolution gives KK class scores per pixel.

The skip connections carry the fine, early features (where exactly the edges are) around the bottleneck to the decoder, which combines them with the coarse, deep features (what the region is). Drawn with the encoder going down and the decoder going up, the network looks like a U.

enc1: 16 ch64 x 64 enc2: 32 ch32 x 32 bottom: 64 ch16 x 16 dec2: 32+32 in32 x 32 dec1: 16+16 in64 x 64 pool pool up2 up1 skip: concatenate enc2 skip: concatenate enc1 image 3 x 64 x 64then 1 x 1 conv: 4 x 64 x 64 each box = two 3 x 3 conv + BatchNorm + ReLU

The original U-Net used unpadded convolutions (so its output was smaller than its input and images were processed as overlapping tiles), four pooling steps and 64 to 1,024 channels, about 31 million parameters. The tiny version here uses padding (output size = input size), two pooling steps and 16 to 64 channels. The building blocks (convolution, BatchNorm, ReLU, transposed convolution) are taught in Deep Learning and batch normalisation; here they are only assembled. U-Net's skips concatenate channels, unlike the residual connections of a ResNet (residual connections), which add.

Is two pooling steps enough context? Each 3×33 \times 3 convolution adds 2 pixels to the receptive field at the current resolution, so the encoder's receptive field is 1+2⋅2+2⋅2⋅2+2⋅2⋅4=291 + 2 \cdot 2 + 2 \cdot 2 \cdot 2 + 2 \cdot 2 \cdot 4 = 29 pixels, plus the pooling steps and the decoder's convolutions; together it comfortably covers the largest shape (24 pixels). The receptive field lesson has the general formula.

python · try it yourself
import torch
from torch import nn
import torch.nn.functional as F
torch.manual_seed(0)

def block(cin, cout):                          # two 3 x 3 convolutions, as in the U-Net paper (with padding)
    return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU(),
                         nn.Conv2d(cout, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU())

class TinyUNet(nn.Module):
    def __init__(self, k=4, c=16, skips=True):
        super().__init__()
        m = 2 if skips else 1                   # a skip doubles the decoder's input channels
        self.skips = skips
        self.enc1, self.enc2, self.bottom = block(3, c), block(c, 2 * c), block(2 * c, 4 * c)
        self.up2, self.dec2 = nn.ConvTranspose2d(4 * c, 2 * c, 2, stride=2), block(2 * c * m, 2 * c)
        self.up1, self.dec1 = nn.ConvTranspose2d(2 * c, c, 2, stride=2), block(c * m, c)
        self.head = nn.Conv2d(c, k, 1)          # 1 x 1 convolution: K class scores per pixel

    def forward(self, x):
        s1 = self.enc1(x)                       # 16 x 64 x 64
        s2 = self.enc2(F.max_pool2d(s1, 2))     # 32 x 32 x 32
        b = self.bottom(F.max_pool2d(s2, 2))    # 64 x 16 x 16
        u = self.up2(b)                         # 32 x 32 x 32
        u = self.dec2(torch.cat([u, s2], 1) if self.skips else u)
        u = self.up1(u)                         # 16 x 64 x 64
        u = self.dec1(torch.cat([u, s1], 1) if self.skips else u)
        return self.head(u)                     # 4 x 64 x 64

model = TinyUNet()
x = torch.rand(2, 3, 64, 64)                    # a batch of two RGB 64 x 64 images
s1 = model.enc1(x); s2 = model.enc2(F.max_pool2d(s1, 2)); b = model.bottom(F.max_pool2d(s2, 2))
u2 = model.up2(b)
print("enc1", tuple(s1.shape), "enc2", tuple(s2.shape), "bottom", tuple(b.shape))
print("up2", tuple(u2.shape), "-> with the skip", tuple(torch.cat([u2, s2], 1).shape))
print("output", tuple(model(x).shape))
for name, part in model.named_children():
    print(f"  {name:7s} {sum(p.numel() for p in part.parameters()):6,d} parameters")
print(f"total {sum(p.numel() for p in model.parameters()):,}; without skips "
      f"{sum(p.numel() for p in TinyUNet(skips=False).parameters()):,}")
enc1 (2, 16, 64, 64) enc2 (2, 32, 32, 32) bottom (2, 64, 16, 16)
up2 (2, 32, 32, 32) -> with the skip (2, 64, 32, 32)
output (2, 4, 64, 64)
  enc1     2,832 parameters
  enc2    14,016 parameters
  bottom  55,680 parameters
  up2      8,224 parameters
  dec2    27,840 parameters
  up1      2,064 parameters
  dec1     7,008 parameters
  head        68 parameters
total 117,732; without skips 106,212

The shapes follow the figure: 64, 32, 16 pixels on the way down, back up to 64, and the skip doubles the channels the decoder receives (32 from up2 plus 32 from enc2). Most of the parameters sit in the bottom block, where the channels are widest, and the 1×11 \times 1 head that does the actual classification has just 16⋅4+4=6816 \cdot 4 + 4 = 68. Without skips the decoder blocks get half the input channels, so the network is about 10 % smaller.

Training on generated scenes

The training data are 300 make_scene images (seed 0) with their exact label maps: 0 for background, 1 square, 2 circle, 3 triangle. The test set is the 100 scenes from seed 1 that the per-pixel baseline was scored on, never seen in training. The loss is the per-pixel cross-entropy (F.cross_entropy on logits N×4×64×64N \times 4 \times 64 \times 64 against integer maps N×64×64N \times 64 \times 64), optimised with Adam under a one-cycle learning-rate schedule for 15 epochs of 15 batches. The training loop lesson explains each line of the loop.

The evaluation builds the 4×44 \times 4 pixel confusion matrix with one bincount and reports per-class IoU and mIoU pooled over the 409,600 test pixels (segmentation metrics). It adds one diagnostic: accuracy on the boundary band (pixels within 2 pixels of a class change, found with a morphological gradient) versus everywhere else, because boundaries are where segmenters differ.

python · try it yourself
import numpy as np, cv2
import torch
from torch import nn
import torch.nn.functional as F
cv2.setLogLevel(0)
torch.manual_seed(0)

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

def scenes(seed, n):
    """n scenes as tensors: images (n, 3, 64, 64) in 0..1, label maps (n, 64, 64), 0 = background."""
    rng = np.random.default_rng(seed)
    X, Y = [], []
    for _ in range(n):
        img, boxes, labels, masks = make_scene(rng)
        y = np.zeros((64, 64), np.int64)
        for c, m in zip(labels, masks):
            y[m] = c + 1
        X.append(img); Y.append(y)
    return torch.tensor(np.array(X)).permute(0, 3, 1, 2).float() / 255, torch.tensor(np.array(Y))

def block(cin, cout):
    return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU(),
                         nn.Conv2d(cout, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU())

class TinyUNet(nn.Module):
    def __init__(self, k=4, c=16, skips=True):
        super().__init__()
        m = 2 if skips else 1
        self.skips = skips
        self.enc1, self.enc2, self.bottom = block(3, c), block(c, 2 * c), block(2 * c, 4 * c)
        self.up2, self.dec2 = nn.ConvTranspose2d(4 * c, 2 * c, 2, stride=2), block(2 * c * m, 2 * c)
        self.up1, self.dec1 = nn.ConvTranspose2d(2 * c, c, 2, stride=2), block(c * m, c)
        self.head = nn.Conv2d(c, k, 1)

    def forward(self, x):
        s1 = self.enc1(x)
        s2 = self.enc2(F.max_pool2d(s1, 2))
        b = self.bottom(F.max_pool2d(s2, 2))
        u = self.dec2(torch.cat([self.up2(b), s2], 1) if self.skips else self.up2(b))
        u = self.dec1(torch.cat([self.up1(u), s1], 1) if self.skips else self.up1(u))
        return self.head(u)

def evaluate(model, X, Y, k=4):
    model.eval()
    with torch.no_grad():
        P = model(X).argmax(1)
    M = torch.bincount(Y.ravel() * k + P.ravel(), minlength=k * k).reshape(k, k).double()   # rows = truth
    iou = M.diag() / (M.sum(0) + M.sum(1) - M.diag())
    Yn = Y.numpy().astype(np.uint8)                 # boundary band: pixels within 2 px of a class change
    band = torch.tensor(np.array([cv2.morphologyEx(y, cv2.MORPH_GRADIENT, np.ones((5, 5), np.uint8)) > 0 for y in Yn]))
    return iou, float((P == Y)[band].float().mean()), float((P == Y)[~band].float().mean())

SKIPS = True
Xtr, Ytr = scenes(0, 300)                           # 300 training scenes
Xte, Yte = scenes(1, 100)                           # the 100 test scenes of the per-pixel baseline
model = TinyUNet(skips=SKIPS)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
epochs, batch = 15, 20
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=5e-3, total_steps=epochs * len(Xtr) // batch)
g = torch.Generator().manual_seed(0)
for epoch in range(epochs):
    model.train()
    perm, total = torch.randperm(len(Xtr), generator=g), 0.0
    for i in range(0, len(Xtr), batch):
        idx = perm[i:i + batch]
        loss = F.cross_entropy(model(Xtr[idx]), Ytr[idx])     # per-pixel cross-entropy
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
        total += loss.item() * len(idx)
    if epoch % 5 == 4:
        print(f"epoch {epoch + 1:2d}  train loss {total / len(Xtr):.3f}")

iou, band_acc, inner_acc = evaluate(model, Xte, Yte)
print(f"skip connections: {SKIPS}, parameters: {sum(p.numel() for p in model.parameters()):,}")
for name, v in zip(["background"] + CLASSES, iou.tolist()):
    print(f"IoU {name:10s} {v:.3f}")
print(f"mIoU {iou.mean().item():.3f} on 100 test scenes")
print(f"accuracy near boundaries {band_acc:.3f}, elsewhere {inner_acc:.3f}")
epoch  5  train loss 0.242
epoch 10  train loss 0.040
epoch 15  train loss 0.025
skip connections: True, parameters: 117,732
IoU background 0.998
IoU square     0.989
IoU circle     0.967
IoU triangle   0.986
mIoU 0.985 on 100 test scenes
accuracy near boundaries 0.989, elsewhere 1.000

From an mIoU of 0.397 to 0.985 on the same test scenes. All three shape classes are now above 0.96: the network has learned what distinguishes the outlines, which the per-pixel features could not express. The remaining errors are concentrated at the edges: the accuracy is 0.989 in the 2-pixel band around boundaries against 1.000 (rounded) elsewhere. Circles are the hardest class (IoU 0.967), and a look at the predictions would show why: a small circle drawn on a pixel grid is almost a square with its corners cut.

Two warnings before celebrating. The baseline was trained on 60 scenes and the U-Net on 300, so part of the gap is data, not architecture (the forest's shape IoUs are low for a reason more data does not fix, its window size, but a fair comparison would give both the same scenes). And the generated scenes are much easier than photographs: flat colours, no texture, no occlusion, no lighting. A score of 0.98 here says the code works, not that U-Nets reach 0.98 on real data.

Are the skip connections worth it?

An ablation removes one component and retrains with everything else unchanged (data, seed, schedule). Here: the same network and training run with SKIPS = False, so the decoder sees only the upsampled bottleneck features.

python · try it yourself
import numpy as np, cv2
import torch
from torch import nn
import torch.nn.functional as F
cv2.setLogLevel(0)
torch.manual_seed(0)

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

def scenes(seed, n):
    rng = np.random.default_rng(seed)
    X, Y = [], []
    for _ in range(n):
        img, boxes, labels, masks = make_scene(rng)
        y = np.zeros((64, 64), np.int64)
        for c, m in zip(labels, masks):
            y[m] = c + 1
        X.append(img); Y.append(y)
    return torch.tensor(np.array(X)).permute(0, 3, 1, 2).float() / 255, torch.tensor(np.array(Y))

def block(cin, cout):
    return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU(),
                         nn.Conv2d(cout, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU())

class TinyUNet(nn.Module):
    def __init__(self, k=4, c=16, skips=True):
        super().__init__()
        m = 2 if skips else 1
        self.skips = skips
        self.enc1, self.enc2, self.bottom = block(3, c), block(c, 2 * c), block(2 * c, 4 * c)
        self.up2, self.dec2 = nn.ConvTranspose2d(4 * c, 2 * c, 2, stride=2), block(2 * c * m, 2 * c)
        self.up1, self.dec1 = nn.ConvTranspose2d(2 * c, c, 2, stride=2), block(c * m, c)
        self.head = nn.Conv2d(c, k, 1)

    def forward(self, x):
        s1 = self.enc1(x)
        s2 = self.enc2(F.max_pool2d(s1, 2))
        b = self.bottom(F.max_pool2d(s2, 2))
        u = self.dec2(torch.cat([self.up2(b), s2], 1) if self.skips else self.up2(b))
        u = self.dec1(torch.cat([self.up1(u), s1], 1) if self.skips else self.up1(u))
        return self.head(u)

def evaluate(model, X, Y, k=4):
    model.eval()
    with torch.no_grad():
        P = model(X).argmax(1)
    M = torch.bincount(Y.ravel() * k + P.ravel(), minlength=k * k).reshape(k, k).double()
    iou = M.diag() / (M.sum(0) + M.sum(1) - M.diag())
    Yn = Y.numpy().astype(np.uint8)
    band = torch.tensor(np.array([cv2.morphologyEx(y, cv2.MORPH_GRADIENT, np.ones((5, 5), np.uint8)) > 0 for y in Yn]))
    return iou, float((P == Y)[band].float().mean()), float((P == Y)[~band].float().mean())

SKIPS = False                                       # the only change
Xtr, Ytr = scenes(0, 300)
Xte, Yte = scenes(1, 100)
model = TinyUNet(skips=SKIPS)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
epochs, batch = 15, 20
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=5e-3, total_steps=epochs * len(Xtr) // batch)
g = torch.Generator().manual_seed(0)
for epoch in range(epochs):
    model.train()
    perm, total = torch.randperm(len(Xtr), generator=g), 0.0
    for i in range(0, len(Xtr), batch):
        idx = perm[i:i + batch]
        loss = F.cross_entropy(model(Xtr[idx]), Ytr[idx])
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
        total += loss.item() * len(idx)
    if epoch % 5 == 4:
        print(f"epoch {epoch + 1:2d}  train loss {total / len(Xtr):.3f}")

iou, band_acc, inner_acc = evaluate(model, Xte, Yte)
print(f"skip connections: {SKIPS}, parameters: {sum(p.numel() for p in model.parameters()):,}")
for name, v in zip(["background"] + CLASSES, iou.tolist()):
    print(f"IoU {name:10s} {v:.3f}")
print(f"mIoU {iou.mean().item():.3f} on 100 test scenes")
print(f"accuracy near boundaries {band_acc:.3f}, elsewhere {inner_acc:.3f}")
epoch  5  train loss 0.226
epoch 10  train loss 0.064
epoch 15  train loss 0.038
skip connections: False, parameters: 106,212
IoU background 0.996
IoU square     0.986
IoU circle     0.960
IoU triangle   0.961
mIoU 0.976 on 100 test scenes
accuracy near boundaries 0.977, elsewhere 1.000
Tiny U-Net, 100 test scenes parameters final train loss mIoU triangle IoU boundary-band accuracy
with skip connections 117,732 0.025 0.985 0.986 0.989
without skip connections 106,212 0.038 0.976 0.961 0.977

The skips help, and exactly where the theory says: at the boundaries (0.989 against 0.977, so about twice as many boundary errors without them) and on the triangle (0.986 against 0.961), whose sharp corners are fine detail. The mIoU difference is small, though (0.985 against 0.976), and on this data honest reporting has to say so. The scenes are 64 x 64 with large flat shapes, so a 16 x 16 bottleneck still holds most of the boundary information. With two pooling steps the information loss is a factor of 4 per side; real U-Nets pool four or five times (16 to 32 per side), where the decoder without skips produces visibly blurred masks. One seed and one test set also cannot separate a difference of 0.009 mIoU from noise: rerun both with several seeds before believing a gap that small (error analysis).

DeepLab: dilated convolutions instead of a decoder

U-Net recovers resolution by upsampling. The DeepLab family (Chen et al., 2015 to 2018) avoids losing it in the first place. It takes a classification backbone such as ResNet-50, removes the striding of the last stages, and to keep their receptive field large replaces their convolutions with dilated (atrous, "with holes") convolutions: a 3×33 \times 3 kernel whose taps are spaced dd pixels apart covers a (2d+1)×(2d+1)(2d + 1) \times (2d + 1) area with the same 9 weights. A stack of 3×33 \times 3 convolutions with dilations d1,…,dLd_1, \ldots, d_L has the receptive field

R=1+2∑l=1LdlR = 1 + 2 \sum_{l=1}^{L} d_l
python · try it yourself
import numpy as np
from scipy.signal import correlate2d

def dilate_kernel(w, d):
    """A 3 x 3 kernel with dilation d: the 9 weights spread out on a (2d + 1) x (2d + 1) grid, zeros between."""
    k = np.zeros((2 * d + 1, 2 * d + 1)); k[::d, ::d] = w
    return k

w = np.ones((3, 3))
for rates in [(1, 1, 1), (1, 2, 4), (2, 2, 2)]:
    x = np.zeros((41, 41)); x[20, 20] = 1.0               # one bright pixel
    for d in rates:
        x = correlate2d(x, dilate_kernel(w, d), mode="same")
    ys, xs = np.nonzero(x)
    holes = int(((x == 0)[ys.min():ys.max() + 1, xs.min():xs.max() + 1]).sum())
    print(f"dilations {rates}: receptive field {xs.max() - xs.min() + 1} x {ys.max() - ys.min() + 1}, "
          f"pixels inside it that never contribute: {holes}, weights {3 * 9}")
dilations (1, 1, 1): receptive field 7 x 7, pixels inside it that never contribute: 0, weights 27
dilations (1, 2, 4): receptive field 15 x 15, pixels inside it that never contribute: 0, weights 27
dilations (2, 2, 2): receptive field 13 x 13, pixels inside it that never contribute: 120, weights 27

Three ordinary 3×33 \times 3 layers see a 7 x 7 window; with dilations 1, 2, 4 the same 27 weights see 15 x 15, with no pixel left out. But dilations 2, 2, 2 see 13 x 13 with 120 of its 169 pixels never reaching the output: only pixels at even offsets are ever sampled. This is the gridding problem of repeated equal dilations, and the reason dilation rates are mixed (1, 2, 4, or 1, 2, 5 in "hybrid dilated convolution").

DeepLabv3 adds atrous spatial pyramid pooling (ASPP): several parallel dilated convolutions at different rates over the same feature map, plus a 1×11 \times 1 branch and a global-average-pooled branch, concatenated, so each position sees context at several scales. torchvision builds the whole family; the pretrained weights are not cached in this course's image, so the models below have random weights and show only their structure and shapes:

python · try it yourself
import torch
from torchvision.models.segmentation import deeplabv3_mobilenet_v3_large, deeplabv3_resnet50, fcn_resnet50, lraspp_mobilenet_v3_large
torch.manual_seed(0)

x = torch.rand(1, 3, 256, 256)
for build in [fcn_resnet50, deeplabv3_resnet50, deeplabv3_mobilenet_v3_large, lraspp_mobilenet_v3_large]:
    model = build(weights=None, weights_backbone=None, num_classes=4).eval()   # random weights: structure only
    with torch.no_grad():
        out = model(x)["out"]
    print(f"{build.__name__:30s} {sum(p.numel() for p in model.parameters()) / 1e6:5.1f} M parameters, out {tuple(out.shape)}")

m = deeplabv3_resnet50(weights=None, weights_backbone=None, num_classes=4).eval()
feats = {}
m.backbone.register_forward_hook(lambda mod, inp, out: feats.update(out))
with torch.no_grad():
    m(x)
print("backbone feature map:", tuple(feats["out"].shape), "-> output stride", 256 // feats["out"].shape[-1])
for name in ["layer3", "layer4"]:
    layer = getattr(m.backbone, name)
    print(f"{name} 3 x 3 dilations:", sorted({c.dilation[0] for c in layer.modules() if isinstance(c, torch.nn.Conv2d) and c.kernel_size[0] == 3}))
aspp = m.classifier[0]
print("ASPP branch dilations:", [b[0].dilation[0] for b in aspp.convs[1:4]], "+ a 1 x 1 branch and image pooling")
fcn_resnet50                    32.9 M parameters, out (1, 4, 256, 256)
deeplabv3_resnet50              39.6 M parameters, out (1, 4, 256, 256)
deeplabv3_mobilenet_v3_large    11.0 M parameters, out (1, 4, 256, 256)
lraspp_mobilenet_v3_large        3.2 M parameters, out (1, 4, 256, 256)
backbone feature map: (1, 2048, 32, 32) -> output stride 8
layer3 3 x 3 dilations: [1, 2]
layer4 3 x 3 dilations: [2, 4]
ASPP branch dilations: [12, 24, 36] + a 1 x 1 branch and image pooling

All four return scores at the input resolution (they upsample bilinearly at the end). The ResNet-50 backbone, normally stride 32, stops at stride 8 here: a 256 x 256 input leaves a 32 x 32 map of 2,048 channels, because layer3 and layer4 use dilations 2 and 4 instead of striding (the first block of each stage keeps the previous rate, hence the 1 and 2 in the lists). That costs compute (layer4 now runs on a map 16 times larger) and memory, which is why DeepLabv3+ goes back to output stride 16 and adds a small U-Net-like decoder with one skip connection. The ASPP rates 12, 24 and 36 belong to output stride 8 (they halve to 6, 12, 18 at stride 16). For pretrained use you would load torchvision's weights trained on a COCO subset with the 20 Pascal VOC classes (plus background) on your own machine:

python
# Not run here: needs the pretrained weights (a download of about 160 MB)
from torchvision.models.segmentation import deeplabv3_resnet50, DeepLabV3_ResNet50_Weights
weights = DeepLabV3_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1      # 21 Pascal VOC classes
model = deeplabv3_resnet50(weights=weights).eval()
batch = weights.transforms()(image_tensor).unsqueeze(0)          # resize + ImageNet normalisation
label_map = model(batch)["out"].argmax(1)[0]                     # (H, W) class ids, 0 = background
# fine-tune on your classes: model.classifier[4] = torch.nn.Conv2d(256, num_classes, 1), then train as above
Family How it keeps detail Typical use
FCN (2015) upsample coarse scores, add scores from earlier layers (FCN-8s) historical baseline
U-Net (2015) symmetric decoder with a skip at every scale medical and microscopy images, small data sets, any input size
DeepLabv3 / v3+ (2017, 2018) dilated backbone (stride 8 or 16), ASPP, light decoder scene parsing (streets, indoor)
Transformer segmenters (SegFormer, Mask2Former) attention over all positions, multi-scale features among the strongest on benchmarks, need large-scale pretraining

Which to pick follows the same logic as backbones in general (vision backbones): a pretrained encoder almost always beats training from scratch on real images, and the choice of decoder matters less than the data. Reusing a pretrained encoder is ordinary transfer learning.

Pitfalls

  • Mismatched sizes at the skip. With unpadded convolutions, or an input side that is not divisible by 2number of poolings2^{\text{number of poolings}}, the upsampled map and the encoder map differ by a pixel and torch.cat fails. Pad the input to a multiple of 16 or 32, or crop the encoder map (the original U-Net cropped).
  • Interpolating the target. Augment images and label maps together, with nearest-neighbour resizing for the labels.
  • BatchNorm with tiny batches. Segmentation batches are small (big images, little memory); BatchNorm statistics from 2 images are noisy. Use larger crops in a bigger batch, GroupNorm, or freeze BatchNorm in a pretrained encoder.
  • Train/eval mode. Evaluate in model.eval() and under torch.no_grad(); in training mode BatchNorm uses the test batch's own statistics.
  • One number, one seed. The skip ablation above moved the mIoU by 0.009, and the same code gives slightly different numbers with a different number of CPU threads. Report the spread over seeds or a confidence interval before claiming an improvement.
  • Synthetic success. 0.98 mIoU on drawn shapes says nothing about photographs; test on data like the deployment data (distribution shift).

Practice

  1. The tiny U-Net is applied to a 90 x 90 image. What goes wrong, and what is the simplest fix?
Answer

Two max-pooling steps take 90 to 45 and then to 22 (pooling rounds down). The first transposed convolution doubles 22 to 44, which cannot be concatenated with the 45-pixel enc2 map, so torch.cat fails. Pad the input to a multiple of 22=42^2 = 4 (here 92) and crop the output back, or resize the image. A 100 x 100 image works (100, 50, 25 and back).

  1. Five 3×33 \times 3 convolutions with dilations 1, 2, 4, 8, 16. What is the receptive field, and how many weights per input-output channel pair?
Answer

R=1+2⋅(1+2+4+8+16)=63R = 1 + 2 \cdot (1 + 2 + 4 + 8 + 16) = 63 pixels, with 5⋅9=455 \cdot 9 = 45 weights. Ordinary convolutions would need 31 layers for the same receptive field. Doubling dilations is the WaveNet and "context module" design.

  1. The boundary-band accuracy is 0.989 with skips and 0.977 without. By what factor do the boundary errors grow without skips?
Answer

Error rates are 1−0.989=0.0111 - 0.989 = 0.011 and 1−0.977=0.0231 - 0.977 = 0.023, a factor of about 2.1. Away from boundaries both models are at 1.000 after rounding, so practically all the difference between them is at the edges, where the skips deliver high-resolution features.

  1. You have 40 labelled CT slices. Train the tiny U-Net from scratch or fine-tune a DeepLab with an ImageNet-pretrained backbone?
Answer

With 40 images, a pretrained encoder usually wins: its early filters already detect edges and textures. A U-Net whose encoder is a pretrained ResNet (a common combination) gets both the pretrained features and the skip connections. Either way, augment heavily and split by patient, not by slice (split strategies), since slices of the same patient are near duplicates.

Test yourself

What does a U-Net skip connection do?

  1. It adds the input image to the output
  2. It concatenates an encoder feature map with the upsampled decoder map of the same resolution, so the decoder gets fine detail back
  3. It skips training of the encoder
  4. It removes the pooling layers

On the 100 test scenes, the per-pixel forest had mIoU 0.397 and the tiny U-Net 0.985. Which conclusion is justified?

  1. U-Nets reach 0.98 mIoU on real photos
  2. On these synthetic scenes the U-Net separates the shape classes, which the local per-pixel features could not; the forest also had fewer training scenes, and real data would be much harder
  3. The forest has a bug
  4. The test set leaked into training

Three 3×33 \times 3 convolutions with dilation 2 each. What is the problem?

  1. The receptive field is 7 x 7
  2. Gridding: the receptive field is 13 x 13 but only pixels at even offsets ever contribute (120 of 169 are skipped)
  3. They have more weights than ordinary convolutions
  4. They change the output size

Why does DeepLabv3 with a ResNet-50 backbone use dilated convolutions in layer3 and layer4?

  1. To reduce the parameter count
  2. To stop striding (output stride 8 instead of 32) while keeping the large receptive field the pretrained layers expect
  3. To add more classes
  4. Because ReLU needs them