Residual Networks

Dive into Deep Learning · §7.4

Residual Networks: ResNet, ResNeXt, and DenseNet
the degradation paradox · nested function classes · additive shortcuts · ResNet-18 · grouped convs & concatenation

The Degradation Paradox in Deep Plain Networks

Motivation & Optimization Puzzle

  • Deeper plain nets fit training data worse: A 56-layer plain convnet ends with higher training loss (\approx 0.28) than a 20-layer plain convnet (0.20), ruling out overfitting.
  • Constructive existence proof: Copying the 20-layer net and setting the remaining 36 layers to the identity f(\mathbf{x}) = \mathbf{x} proves a deeper solution \le 0.20 exists—SGD simply fails to approximate f(\mathbf{x}) = \mathbf{x} across plain nonlinear layers.

Nested Function Classes Guarantee Monotonic Improvement

Theoretical Framing

Consider a sequence of model families \mathcal{F}_1, \mathcal{F}_2, \ldots, \mathcal{F}_K trying to approximate a target mapping f^*:

  • Non-nested classes (\mathcal{F} \not\subseteq \mathcal{F}'): Expanding a layer without preserving existing mappings can shift the whole class away from f^*.
  • Nested classes (\mathcal{F} \subseteq \mathcal{F}'): Guarantees that the best achievable loss never worsens with depth: \mathcal{F} \subseteq \mathcal{F}' \implies \min_{f \in \mathcal{F}'} L(f) \le \min_{f \in \mathcal{F}} L(f)
  • The optimization gap: A plain layer \textrm{ReLU}(\textrm{BN}(\mathbf{W}\mathbf{x})) can represent \mathbf{x} on \mathbf{x} \ge 0, so plain classes are nested in theory—but the identity sits at an awkward interior weight configuration that SGD fails to reach.

Residual Blocks: Learning Corrections to the Identity

The Residual Block

Instead of forcing a stacked block to parameterize the desired mapping f(\mathbf{x}) directly, a residual block learns the residual correction g(\mathbf{x}) = f(\mathbf{x}) - \mathbf{x} and adds the input back via a shortcut connection:

  • Identity sits at the origin (g(\mathbf{x}) = \mathbf{0}): f(\mathbf{x}) = \mathbf{x} + g(\mathbf{x})
  • Trivial to drive a block to identity: Driving the block’s transformation to \mathbf{x} requires only pushing the weights (or final BatchNorm scale \gamma_2, \beta_2) of the residual branch g toward zero.
  • Preconditioning around the identity: Even when g(\mathbf{x}) \neq \mathbf{0}, learning small perturbative refinements around \mathbf{x} is much better conditioned than learning a full near-identity coordinate transformation from scratch.

The Identity Gradient Highway Across Depth

Backward Jacobian Analysis

\frac{\partial L}{\partial \mathbf{x}_\ell} = \frac{\partial L}{\partial \mathbf{x}_L} \left(\mathbf{I} + \frac{\partial}{\partial \mathbf{x}_\ell} \sum_{k=\ell+1}^L g_k(\mathbf{x}_{k-1})\right)

  • Additive identity \mathbf{I}: Unrolls \mathbf{x}_L = \mathbf{x}_\ell + \sum g_k, routing upstream gradients \partial L / \partial \mathbf{x}_L straight to early layers \mathbf{x}_\ell without multiplying through intermediate weight matrices.

Identity vs. 1×1 Projection Shortcuts

Block Topology

ResNet’s basic Residual block stacks two bias-free 3\times 3 convolutions with batch normalization, adds the shortcut before the second ReLU, and uses a 1\times 1 projection whenever dimensions change:

  • Identity shortcut (left, same shape): When c_{\textrm{o}} = c_{\textrm{i}} and stride s = 1, \mathbf{x} is added directly with zero extra parameters.
  • Projection shortcut (right, downsampling): When c_{\textrm{o}} \neq c_{\textrm{i}} or stride s = 2, a stride-s 1\times 1 convolution + BatchNorm projects \mathbf{x} to match spatial size and channel width.
  • Zero-branch condition: Setting the second BatchNorm’s \gamma_2 = \beta_2 = 0 zeroes out the residual branch in both training and eval modes, recovering \textrm{ReLU}(\mathbf{x}) = \mathbf{x} for \mathbf{x} \ge 0.

Implementing the Residual Block

Code Implementation

Setting use_1x1conv or strides != 1 enables the 1\times 1 projection shortcut conv3 + bn3:

class Residual(nn.Module):
    """The Residual block of ResNet models."""
    def __init__(self, num_channels, use_1x1conv=False, strides=1):
        super().__init__()
        # No conv biases: the batch normalization after each conv removes them
        self.conv1 = nn.LazyConv2d(num_channels, kernel_size=3, padding=1,
                                   stride=strides, bias=False)
        self.conv2 = nn.LazyConv2d(num_channels, kernel_size=3, padding=1,
                                   bias=False)
        # Auto-enable 1x1 conv when downsampling so the residual shape matches.
        if use_1x1conv or strides != 1:
            self.conv3 = nn.LazyConv2d(num_channels, kernel_size=1,
                                       stride=strides, bias=False)
            self.bn3 = nn.LazyBatchNorm2d()
        else:
            self.conv3 = None
        self.bn1 = nn.LazyBatchNorm2d()
        self.bn2 = nn.LazyBatchNorm2d()

    def forward(self, X):
        Y = F.relu(self.bn1(self.conv1(X)))
        Y = self.bn2(self.conv2(Y))
        if self.conv3:
            X = self.bn3(self.conv3(X))
        Y += X
        return F.relu(Y)

Verifying Shape Preservation and Stride-2 Downsampling

Block Shape Checks

blk = Residual(3)
X = d2l.randn(4, 3, 6, 6)
blk(X).shape
torch.Size([4, 3, 6, 6])
blk = Residual(6, use_1x1conv=True, strides=2)
blk(X).shape
torch.Size([4, 6, 3, 3])

Controlled Test: 20- vs. 56-Layer Plain and ResNets

Reproducing Degradation

To test degradation cleanly on 28\times 28 Fashion-MNIST, we build DeepNet (6n+2 layers: a 16-ch 3\times 3 stem, three stages of n blocks at widths 16, 32, 64, and a pooled linear head) and compare plain_block vs. Residual at n=3 (20 layers) and n=9 (56 layers):

  • Plain networks degrade (56 > 20 loss): The 56-layer plain network (red dashed) sits strictly above the 20-layer plain network (blue dashed) at every epoch, ending at 0.25\text{--}0.30 vs. 0.20 training loss.
  • Residual shortcuts reverse the ordering (56 < 20 loss): Adding shortcuts without a single extra trunk parameter drops the 56-layer ResNet (red solid) to 0.15\text{--}0.17, beating both 20-layer models (\approx 0.19).

ResNet-18 Architecture: Stem, Four Stages, Pooled Head

ResNet-18 Architecture

At full scale, ResNet wraps four residual stages inside GoogLeNet’s stem–body–head template:

  • 4× downsampling stem (1 weight layer): A 64-channel 7\times 7 stride-2 conv (p=3) + BatchNorm + ReLU + 3\times 3 stride-2 max-pool (p=1) maps 96\times 96 \to 24\times 24.
  • Four residual stages (16 weight layers): Each stage stacks 2 Residual blocks at widths (64, 128, 256, 512). Stage 1 keeps 24\times 24; stages 2–4 open with a stride-2 projection block (24 \to 12 \to 6 \to 3).
  • Pooled head (1 weight layer): Global average pooling + 512 \to 10 linear layer (1 + 16 + 1 = 18 layers, 11.18M parameters).

Stage Construction and Shape Trace in ResNet-18

Stage Template & Shapes

In ResNet.stage, the first block of stages 2, 3, and 4 (not first_block) halves height and width while doubling channels:

def stage(self, num_residuals, num_channels, first_block=False):
    blk = []
    for i in range(num_residuals):
        if i == 0 and not first_block:
            blk.append(Residual(num_channels, use_1x1conv=True, strides=2))
        else:
            blk.append(Residual(num_channels))
    return nn.Sequential(*blk)
Sequential             (1, 64, 24, 24)
Sequential             (1, 64, 24, 24)
Sequential             (1, 128, 12, 12)
Sequential             (1, 256, 6, 6)
Sequential             (1, 512, 3, 3)
Sequential             (1, 10)

Training ResNet-18 on Fashion-MNIST

Experimental Evidence

Because batch normalization follows every convolution, ResNet-18 trains reliably at peak learning rate \eta_0 = 0.1 over 10 epochs on 96\times 96 Fashion-MNIST:

  • High accuracy at 4\times fewer weights than VGG: Reaches \approx 93\% validation accuracy with 11.2\text{M} parameters (319\text{M} multiply-adds at 96\times 96), matching quarter-width VGG (43.1\text{M} parameters at 224\times 224).
  • Memorization gap without modern regularization: ResNet-18 drives training loss below 0.01 while validation loss plateaus near 0.27—motivating the data augmentation and regularization recipes of §7.6.

ResNeXt: Wider Bottlenecks via Grouped Convolutions

ResNeXt & Cardinality

Doubling channel width quadruples dense convolution cost (c_{\textrm{i}} c_{\textrm{o}} k^2). ResNeXt (Xie et al., 2017) widens the internal bottleneck at matched cost by partitioning the 3\times 3 convolution into g independent groups (cardinality):

  • Grouped 3\times 3 savings: Splitting b bottleneck channels into g groups of b/g channels cuts 3\times 3 weights by a factor of g, from 9b^2 to 9(b/g)^2 \cdot g = 9b^2/g.
  • All-to-all 1\times 1 mixing: Sandwiches the grouped 3\times 3 layer between two dense 1\times 1 convolutions (c \to b and b \to c, costing 2cb weights) so groups exchange information every block.
  • Wider at matched cost: ResNet-50 (c=256, b=64, g=1) uses 2(256)(64) + 9(64^2) = 69{,}632 weights; ResNeXt-50 (b=128, g=32) doubles bottleneck width to 128 using 2(256)(128) + 9(128^2)/32 = 70{,}144 weights (+0.7%), cutting ImageNet top-1 error from 23.9% to 22.2%.

Implementing the ResNeXt Block

ResNeXt Code

ResNeXtBlock generalizes Residual and ResNet-50’s bottleneck into one reusable module:

class ResNeXtBlock(nn.Module):
    """The ResNeXt block."""
    def __init__(self, num_channels, groups, bot_mul, use_1x1conv=False,
                 strides=1):
        super().__init__()
        bot_channels = int(round(num_channels * bot_mul))
        # No conv biases: the batch normalization after each conv removes them
        self.conv1 = nn.LazyConv2d(bot_channels, kernel_size=1, stride=1,
                                   bias=False)
        self.conv2 = nn.LazyConv2d(bot_channels, kernel_size=3,
                                   stride=strides, padding=1,
                                   groups=groups, bias=False)
        self.conv3 = nn.LazyConv2d(num_channels, kernel_size=1, stride=1,
                                   bias=False)
        self.bn1 = nn.LazyBatchNorm2d()
        self.bn2 = nn.LazyBatchNorm2d()
        self.bn3 = nn.LazyBatchNorm2d()
        # Auto-enable 1x1 conv when downsampling so the residual shape matches.
        if use_1x1conv or strides != 1:
            self.conv4 = nn.LazyConv2d(num_channels, kernel_size=1,
                                       stride=strides, bias=False)
            self.bn4 = nn.LazyBatchNorm2d()
        else:
            self.conv4 = None

    def forward(self, X):
        Y = F.relu(self.bn1(self.conv1(X)))
        Y = F.relu(self.bn2(self.conv2(Y)))
        Y = self.bn3(self.conv3(Y))
        if self.conv4:
            X = self.bn4(self.conv4(X))
        return F.relu(Y + X)

DenseNet: Concatenation vs. Quadratic Activation Memory

DenseNet & Skip Topologies

Instead of summing \mathbf{x}_k = \mathbf{x}_{k-1} + g_k(\mathbf{x}_{k-1}), DenseNet (Huang et al., 2017) concatenates every layer’s output of growth rate r channels onto all preceding feature maps:

  • Explicit feature reuse: \mathbf{x}_k = [\mathbf{x}_{k-1},\; f_k(\mathbf{x}_{k-1})] After n layers on a c-channel input, the tensor has c + n r channels, and transition layers (1\times 1 conv + 2\times 2 avg-pool) compress width between dense blocks.
  • Why additive shortcuts won in practice (Memory Pitfall): A naive DenseNet allocates a fresh concatenated buffer of width c + (i-1)r at every layer i=1,\ldots,n for backprop, costing \sum_{i=1}^n (c + (i-1)r) = nc + \frac{n(n-1)}{2}r = \Theta(n^2 r) activation memory (e.g., 10{,}368 channels vs. ResNet’s 3{,}072 at n=24, c=64, r=32).

Pre-Activation ResNets and U-Net Skip Connections

Variants & Extensions

  • Pre-activation ResNet (He et al., 2016b): Moves \textrm{BN} \to \textrm{ReLU} \to \textrm{Conv} inside g(\mathbf{x}) and drops the post-add ReLU for an exact \mathbf{I} Jacobian across arbitrary depth.
  • ResNet-D shortcut (He et al., 2019): Prepends 2 \times 2 stride-2 AvgPool before a stride-1 1 \times 1 conv so 100% of pixels are sampled instead of 25%.

Concept Check: Shortcuts, ResNeXt Cost & DenseNet Memory

Concept Check

Work out these three design calculations:

  1. Stride-2 shortcut pitfall (ResNet-D): In a stride-2 Residual block on a 24\times 24 feature map, conv3 is a 1\times 1 convolution with stride 2. What fraction of the 24\times 24 input spatial positions does conv3 actually read, and how does ResNet-D fix this?
  2. ResNet-50 vs. ResNeXt-50 block FLOPs: For c = 512, verify that a ResNet-50 bottleneck (b = 128, g = 1) and a ResNeXt-50 block (b = 256, g = 32) have nearly identical parameter counts.
  3. DenseNet channel growth: A dense block receives c = 64 channels and runs n = 4 layers with growth rate r = 32. How many output channels emerge, and how many total input channels are read across all 4 convolutions?

Answers:

  1. A stride-2 1\times 1 kernel samples only every even row and column—1/4 (25%) of the spatial pixels, discarding the other 75\%. ResNet-D prepends a parameter-free 2\times 2 stride-2 average-pooling layer before a stride-1 1\times 1 conv so all pixels contribute.
  2. ResNet-50: 2(512)(128) + 9(128^2) = 131{,}072 + 147{,}456 = 278{,}528 weights. ResNeXt-50: 2(512)(256) + 9(256^2)/32 = 262{,}144 + 18{,}432 = 280{,}576 weights (<0.8\% difference for 2\times bottleneck width).
  3. Output width is 64 + 4(32) = 192 channels. The 4 layers read 64 + 96 + 128 + 160 = 448 concatenated input channels.

Summary: Key Takeaways on Residual Networks

Summary

  • ResNet (\mathbf{x} + g(\mathbf{x})): Places the identity at g=0 (\mathcal{F} \subseteq \mathcal{F}'), curing deep plain-net degradation at O(n \cdot c) activation memory.
  • ResNeXt (g groups): Cuts 3 \times 3 weights to 9b^2/g, doubling bottleneck width b at matched FLOPs.
  • DenseNet ([\mathbf{x}, f(\mathbf{x})]): Concatenates features with growth rate r at O(n^2 r) naive activation memory.