Lesson 3.3 — Residual & Multiscale Networks
From local edges to global context
Deep CNNs vary spatial resolution, channel capacity, and receptive field across stages. High resolution preserves boundaries and localization; downsampling compresses spatial detail to reduce compute; image classification needs one label per image whereas segmentation needs one label per pixel.
Addition & projection shortcut
01 · Residual Block Shape Inspector (Conv + Bias, No BN)
02 · Identity vs. Projection Shortcut (4×4)
PyTorch BasicBlock
import torch
from torch import nn
class BasicBlock(nn.Module):
def __init__(self, ci, co, stride=1):
super().__init__()
self.f = nn.Sequential(
nn.Conv2d(ci, co, 3, stride, 1, bias=False),
nn.BatchNorm2d(co),
nn.ReLU(),
nn.Conv2d(co, co, 3, 1, 1, bias=False),
nn.BatchNorm2d(co),
)
self.p = (
nn.Identity()
if ci == co and stride == 1
else nn.Sequential(nn.Conv2d(ci, co, 1, stride, bias=False), nn.BatchNorm2d(co))
)
def forward(self, x):
return torch.relu(self.f(x) + self.p(x))
BasicBlock, Bottleneck & stage layout
03 · ResNet Stage Architecture Explorer
Feature Pyramid
Imagine a segmentation model locating a thin stripe on a work surface. In run A the stripe occupies column 0; in run B it occupies column 1. Each pooling window covers two adjacent columns and two rows.

Follow either row from left to right. In each left-hand pooling window, exactly half the pixels belong to the stripe. The coarse map preserves that fraction while losing which half contained it. Upsampling repeats the same coarse value over both possible locations. Any decoder that sees only this identical coarse map must give the same answer for both inputs.
A feature pyramid gives the decoder a second source of evidence. A coarse feature can respond to a larger region, while a lateral feature from an earlier layer still distinguishes nearby locations. In a typical top-down pyramid, level combines the two at matching spatial resolution:
Here is the encoder feature at the finer level. The lateral projection matches the channel count for addition. The toy pooling diagram isolates the loss of position; a learned encoder's channels can retain additional information.
Move a target across pooling-window boundaries
04 · Multiscale Feature Pyramid (8 → 4 → 2 → 1)
Interpolation & transposed convolution
05 · Upsampling & Transposed Convolution (2×2 Input)
PyTorch interpolation & ConvTranspose2d
import torch
from torch import nn
from torch.nn import functional as F
x = torch.tensor([[[[1.0, 0.5], [0.25, 0.75]]]])
print(F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False))
up = nn.ConvTranspose2d(1, 1, 3, stride=2, bias=False)
with torch.no_grad():
up.weight.copy_(torch.tensor([[[[1.0, 0.5, 1.0], [0.5, 1.0, 0.5], [1.0, 0.5, 1.0]]]]))
print(up(x).shape) # (1, 1, 5, 5)
Encoder, decoder & skip fusion
A U-Net keeps an encoder feature map at each skip level. On the way back up, the decoder aligns its coarser features with that earlier map. At one pixel it now has two descriptions of the same location: one computed with broader context and one captured at finer resolution.
| Operation at the merge | What arrives | What the next layer sees |
|---|---|---|
| Residual addition | Two aligned maps with channels each | channels. Each pair of corresponding values has already been added. |
| U-Net concatenation | An encoder map with channels and an aligned decoder map with channels | channels. A following convolution learns how to combine the two sources. |
In the stripe example above, a decoder using only the pooled values must make the same prediction for both runs. A fine-resolution skip can carry the distinguishing column into the merge. The training loss determines whether the decoder learns to use that cue.
06 · U-Net Skip Connection Mapper
Pixel-level classification · IoU & Dice
For class c, IoU divides the intersection of the predicted and reference masks by their union. Dice divides twice the intersection by the sum of both mask sizes. True negatives contribute to pixel accuracy, while foreground IoU and Dice depend only on the masks. If both masks are empty, the displayed ratios have zero denominator. The experiment below excludes empty-union classes from mean IoU.
Compare All background with a shifted foreground prediction. Step through the intersection and the two types of foreground error.
07 · Segmentation IoU & Dice Explorer (6×6 Mask)
Engineering Lab · Robot Workspace Segmentation
Default PyTorch results over 160 Adam updates with class weights [0.12, 1, 1]: Skip
achieves validation CE 1.090059 → 0.029916 and mIoU = 0.925229, vs.
No-Skip validation CE 1.099799 → 0.391355 and mIoU = 0.444820.
08 · What Does a U-Net Skip Preserve?
Complete PyTorch implementation (unet0303.py)
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1)
torch.set_default_dtype(torch.float64)
def rng(seed):
x = seed
def next_value():
nonlocal x
x = (1664525 * x + 1013904223) % 2**32
return x / 2**32
return next_value
def dataset(n, seed, noise):
r = rng(seed)
X, Y = [], []
for _ in range(n):
a, b, c, d = [1 + int(5 * r()) for _ in range(4)]
xx, yy = [], []
for y in range(8):
for x in range(8):
label = 2 if abs(y - c) + abs(x - d) <= 1 else (1 if a <= y < a + 2 and b <= x < b + 2 else 0)
yy.append(label)
xx.append([0.15, 0.55, 0.90][label] + noise * (2 * r() - 1))
X.append(xx)
Y.append(yy)
return torch.tensor(X).reshape(n, 1, 8, 8), torch.tensor(Y, dtype=torch.long).reshape(n, 8, 8)
class MiniUNet(nn.Module):
def __init__(self, seed=3, skip=True):
super().__init__()
self.skip = skip
self.enc = nn.Conv2d(1, 3, 3, padding=1)
self.low = nn.Conv2d(3, 3, 3, padding=1)
self.head = nn.Conv2d(6, 3, 1)
r = rng(seed + 2000)
with torch.no_grad():
for layer in [self.enc, self.low, self.head]:
layer.weight.copy_(torch.tensor([0.6 * (r() - 0.5) for _ in range(layer.weight.numel())]).reshape(layer.weight.shape))
layer.bias.zero_()
def forward(self, x):
e = torch.tanh(self.enc(x))
p = F.avg_pool2d(e, 2)
b = torch.tanh(self.low(p))
u = F.interpolate(b, scale_factor=2, mode="nearest")
return self.head(torch.cat([e if self.skip else e * 0, u], dim=1))
def metrics(model, x, y):
with torch.no_grad():
l = model(x)
pred = l.argmax(1)
cm = torch.bincount((3 * y + pred).flatten(), minlength=9).reshape(3, 3)
tp = cm.diag()
union = cm.sum(0) + cm.sum(1) - tp
valid = union > 0
iou = tp[valid] / union[valid]
return dict(loss=F.cross_entropy(l, y).item(), miou=iou.mean().item(), cm=cm.tolist())
def run(seed=3, noise=0.12, lr=0.03, updates=160, skip=True):
x, y = dataset(24, seed, noise)
v, t = dataset(12, seed + 1000, noise)
m = MiniUNet(seed, skip)
opt = torch.optim.Adam(m.parameters(), lr=lr)
hist = []
for k in range(updates + 1):
if k % 10 == 0 or k == updates:
hist.append(dict(t=k, tr=metrics(m, x, y)["loss"], **metrics(m, v, t)))
if k == updates:
break
ids = torch.arange((k % 4) * 6, (k % 4 + 1) * 6)
opt.zero_grad()
F.cross_entropy(m(x[ids]), y[ids], weight=torch.tensor([0.12, 1.0, 1.0])).backward()
opt.step()
return hist
if __name__ == "__main__":
for skip in (True, False):
h = run(skip=skip)
print(skip, h[0]["loss"], h[-1]["loss"], h[-1]["miou"], h[-1]["cm"])