残差网络

Dive into Deep Learning · §7.4

残差网络:ResNet、ResNeXt 与 DenseNet
退化悖论 · 嵌套函数类 · 加性快捷连接 · ResNet-18 · 分组卷积与连结

深层普通网络中的退化悖论

动机与优化谜题

  • 更深的普通网络训练集拟合更差:56 层普通卷积网络最终的训练损失(\approx 0.28)高于 20 层普通网络(0.20),排除过拟合。
  • 构造性存在证明:复制 20 层网络并令其余 36 层为恒等映射 f(\mathbf{x}) = \mathbf{x},证明损失 \le 0.20 的更深解必然存在——只是 SGD 无法跨普通非线性层逼近 f(\mathbf{x}) = \mathbf{x}。

嵌套函数类保证单调改进

理论框架

考虑一组尝试逼近目标映射 f^* 的模型族 \mathcal{F}_1, \mathcal{F}_2, \ldots, \mathcal{F}_K:

  • 非嵌套类(\mathcal{F} \not\subseteq \mathcal{F}'):扩充层而不保留既有映射,可能使整个函数类偏离 f^*。
  • 嵌套类(\mathcal{F} \subseteq \mathcal{F}'):保证可达最优损失绝不随深度恶化: \mathcal{F} \subseteq \mathcal{F}' \implies \min_{f \in \mathcal{F}'} L(f) \le \min_{f \in \mathcal{F}} L(f)
  • 优化鸿沟:普通层 \textrm{ReLU}(\textrm{BN}(\mathbf{W}\mathbf{x})) 在 \mathbf{x} \ge 0 上能够表示 \mathbf{x},理论上函数类已嵌套——但恒等映射藏在 SGD 难以抵达的棘手内部权重配置处。

残差块:学习对恒等映射的修正

残差块

残差块不再强迫堆叠块直接参数化目标映射 f(\mathbf{x}),而是学习残差修正 g(\mathbf{x}) = f(\mathbf{x}) - \mathbf{x},并通过快捷连接把输入加回:

  • 恒等映射位于原点(g(\mathbf{x}) = \mathbf{0}): f(\mathbf{x}) = \mathbf{x} + g(\mathbf{x})
  • 轻松退化为恒等映射:只需将残差分支 g 的权重(或末层批量规范化的 \gamma_2, \beta_2)推向零即可恢复 \mathbf{x}。
  • 围绕恒等映射的预条件:即使 g(\mathbf{x}) \neq \mathbf{0},在 \mathbf{x} 附近学习微小扰动修正也远比从零学习近恒等坐标变换良态。

贯穿深度的恒等梯度高速路

反向雅可比分析

\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)

  • 加性单位阵 \mathbf{I}:展开为 \mathbf{x}_L = \mathbf{x}_\ell + \sum g_k,使上游梯度 \partial L / \partial \mathbf{x}_L 无需连乘中间权重矩阵即可直达早期层 \mathbf{x}_\ell。

恒等快捷连接与 1×1 投影快捷连接

块拓扑

ResNet 基础 Residual 块堆叠两层无偏置 3\times 3 卷积与批量规范化,在第二个 ReLU 前加上快捷路径,维度变化时改用 1\times 1 投影:

  • 恒等快捷连接(左,同形状):当 c_{\textrm{o}} = c_{\textrm{i}} 且步幅 s = 1 时直接相加 \mathbf{x},零额外参数。
  • 投影快捷连接(右,下采样):当 c_{\textrm{o}} \neq c_{\textrm{i}} 或步幅 s = 2 时,步幅 s 的 1\times 1 卷积 + 批量规范化将 \mathbf{x} 投影到匹配的空间尺寸与通道宽度。
  • 零分支条件:令第二个批量规范化的 \gamma_2 = \beta_2 = 0,在训练与评估模式下均可将残差分支清零,在 \mathbf{x} \ge 0 上恢复 \textrm{ReLU}(\mathbf{x}) = \mathbf{x}。

实现残差块

代码实现

设置 use_1x1conv 或 strides != 1 会启用 1\times 1 投影快捷连接 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)

验证保形与步幅 2 下采样

块形状检查

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])

对照实验:20 层与 56 层普通网络及残差网络

复现退化现象

为在 28\times 28 Fashion-MNIST 上干净检验退化,构造 DeepNet(6n+2 层:16 通道 3\times 3 输入主干、宽度 16/32/64 的三阶段各 n 块与汇聚线性头),在 n=3(20 层)与 n=9(56 层)上对比 plain_block 与 Residual:

  • 普通网络退化(56 > 20 损失):56 层普通网络(红虚线)每轮都严格位于 20 层普通网络(蓝虚线)上方,最终训练损失为 0.25\text{--}0.30 对比 0.20。
  • 残差连接逆转排序(56 < 20 损失):主干零增参即可让 56 层 ResNet(红实线)降至 0.15\text{--}0.17,击败两个 20 层模型(\approx 0.19)。

ResNet-18 架构:输入主干、四阶段与汇聚头

ResNet-18 架构

在完整尺度上,ResNet 将四个残差阶段嵌入 GoogLeNet 的输入主干–主体–分类头模板:

  • 4× 下采样输入主干(1 权重层):64 通道步幅 2 的 7\times 7 卷积(p=3)+ BN + ReLU + 步幅 2 的 3\times 3 最大汇聚(p=1),将 96\times 96 \to 24\times 24。
  • 四残差阶段(16 权重层):每阶段在宽度 (64, 128, 256, 512) 下堆叠 2 个 Residual 块。第 1 阶段保持 24\times 24;第 2–4 阶段以步幅 2 投影块开头(24 \to 12 \to 6 \to 3)。
  • 汇聚分类头(1 权重层):全局平均汇聚 + 512 \to 10 线性层(1 + 16 + 1 = 18 层,11.18M 参数)。

ResNet-18 的阶段构造与形状追踪

阶段模板与形状

在 ResNet.stage 中,第 2、3、4 阶段的首个块(not first_block)将高宽减半并使通道翻倍:

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)

在 Fashion-MNIST 上训练 ResNet-18

实验证据

由于每层卷积后都有批量规范化,ResNet-18 在 96\times 96 Fashion-MNIST 上以峰值学习率 \eta_0 = 0.1 训练 10 轮十分稳定:

  • 以少于 VGG 4\times 的权重达高准确率:以 11.2\text{M} 参数(96\times 96 下 319\text{M} 次乘加)达到 \approx 93\% 验证准确率,追平四分之一宽度 VGG(224\times 224 下 43.1\text{M} 参数)。
  • 缺乏现代正则化下的记忆鸿沟:ResNet-18 训练损失低于 0.01 而验证损失停在 0.27 附近——引出 §7.6 的数据增广与正则化方案。

ResNeXt:借分组卷积拓宽瓶颈

ResNeXt 与基数

通道宽度翻倍会使稠密卷积开销增至四倍(c_{\textrm{i}} c_{\textrm{o}} k^2)。ResNeXt(Xie 等,2017)将 3\times 3 卷积划分为 g 个独立分组(基数),在同等开销下拓宽内部瓶颈:

  • 分组 3\times 3 节省:把 b 个瓶颈通道分成 g 组(每组 b/g 通道),将 3\times 3 权重按因子 g 缩减,从 9b^2 降至 9(b/g)^2 \cdot g = 9b^2/g。
  • 全对全 1\times 1 混合:将分组 3\times 3 层夹在两层稠密 1\times 1 卷积(c \to b 与 b \to c,耗 2cb 权重)之间,使各组在每个块内交换信息。
  • 同等开销更宽瓶颈:ResNet-50(c=256, b=64, g=1)用 2(256)(64) + 9(64^2) = 69{,}632 权重;ResNeXt-50(b=128, g=32)将瓶颈宽翻倍至 128,仅用 2(256)(128) + 9(128^2)/32 = 70{,}144 权重(+0.7%),ImageNet top-1 错误率从 23.9% 降至 22.2%。

实现 ResNeXt 块

ResNeXt 代码

ResNeXtBlock 将 Residual 与 ResNet-50 瓶颈统一为单个可复用模块:

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:连结与二次方激活内存

DenseNet 与跳跃拓扑

DenseNet(Huang 等,2017)不再相加 \mathbf{x}_k = \mathbf{x}_{k-1} + g_k(\mathbf{x}_{k-1}),而是将每层输出的增长率 r 个通道连结到此前全部特征图上:

  • 显式特征复用: \mathbf{x}_k = [\mathbf{x}_{k-1},\; f_k(\mathbf{x}_{k-1})] 在 c 通道输入上经 n 层后,张量有 c + n r 个通道;过渡层(1\times 1 卷积 + 2\times 2 平均汇聚)在稠密块间压缩宽度。
  • 为何加性快捷连接在实践中胜出(显存陷阱):朴素 DenseNet 在每层 i=1,\ldots,n 都为反向传播分配宽 c + (i-1)r 的新连结缓冲区,耗费 \sum_{i=1}^n (c + (i-1)r) = nc + \frac{n(n-1)}{2}r = \Theta(n^2 r) 激活内存(例如 n=24, c=64, r=32 时需 10{,}368 通道,对比 ResNet 仅 3{,}072)。

预激活 ResNet 与 U-Net 跳跃连接

变体与扩展

  • 预激活 ResNet(He 等,2016b):将 \textrm{BN} \to \textrm{ReLU} \to \textrm{Conv} 移入 g(\mathbf{x}) 并移除加后 ReLU,在任意深度维持精确的 \mathbf{I} 雅可比。
  • ResNet-D 快捷连接(He 等,2019):在步幅 1 的 1 \times 1 卷积前加步幅 2 的 2 \times 2 平均汇聚,采样 100% 像素而非 25%。

概念自测:快捷连接、ResNeXt 开销与 DenseNet 显存

概念自测

完成以下三道设计计算:

  1. 步幅 2 快捷连接陷阱(ResNet-D):在 24\times 24 特征图上的步幅 2 Residual 块中,conv3 是步幅为 2 的 1\times 1 卷积。conv3 实际读取了 24\times 24 输入空间位置的几分之几?ResNet-D 如何修复这一问题?
  2. ResNet-50 对比 ResNeXt-50 块 FLOPs:取 c = 512,验证 ResNet-50 瓶颈块(b = 128, g = 1)与 ResNeXt-50 块(b = 256, g = 32)的参数量几乎相同。
  3. DenseNet 通道增长:某稠密块接收 c = 64 个通道,运行 n = 4 层、增长率 r = 32。最终输出多少通道?全部 4 层卷积合计读取多少输入通道?

答案:

  1. 步幅 2 的 1\times 1 核只采样偶数行偶数列——即 1/4(25%)的空间像素,丢弃其余 75\%。ResNet-D 在步幅 1 的 1\times 1 卷积前加无参数的步幅 2 的 2\times 2 平均汇聚层,使全部像素均参与贡献。
  2. ResNet-50:2(512)(128) + 9(128^2) = 131{,}072 + 147{,}456 = 278{,}528 个权重。ResNeXt-50:2(512)(256) + 9(256^2)/32 = 262{,}144 + 18{,}432 = 280{,}576 个权重(瓶颈宽 2\times 而权重差 <0.8\%)。
  3. 输出宽度为 64 + 4(32) = 192 通道。4 层合计读取 64 + 96 + 128 + 160 = 448 个连结后的输入通道。

小结:残差网络的核心要点

小结

  • ResNet(\mathbf{x} + g(\mathbf{x})):将恒等映射置于 g=0(\mathcal{F} \subseteq \mathcal{F}'),以 O(n \cdot c) 激活内存治愈深层普通网络退化。
  • ResNeXt(g 分组):将 3 \times 3 权重降至 9b^2/g,在同等 FLOPs 下将瓶颈宽度 b 翻倍。
  • DenseNet([\mathbf{x}, f(\mathbf{x})]):以增长率 r 连结特征,朴素激活内存为 O(n^2 r)。