高效卷积网络

Dive into Deep Learning · §7.5

高效卷积网络
深度可分离分解 · 倒置瓶颈 · FLOPs 与延迟 · 复合缩放 · RepVGG 融合

硬性边缘预算:为什么 150 亿次乘加无法上线

动机与部署约束

  • 数据中心对比边缘端:VGG-16 每帧需 15.3\textrm{B} 次 MAC 与 550\textrm{ MB} fp32 权重;MobileNetV1 以 少 27\times 的 MAC(0.57\textrm{B})和 少 33\times 的权重(4.2\textrm{M})达到 70.6\% ImageNet top-1(仅低 -0.9\%)。
  • 三大支柱:深度可分离分解、复合缩放 + SE 门控,以及 RepVGG 训练到推理分支融合。

从分组卷积到深度卷积极限

通道连接矩阵

标准 k \times k 卷积随宽度呈二次方增长(c_{\textrm{i}} c_{\textrm{o}} k^2),因为每个输出通道都用独立空间滤波器卷积每个输入通道:

  • 分组卷积(g 组):将通道划为 g 个互不相交的 c_{\textrm{i}}/g \to c_{\textrm{o}}/g 块,使连接矩阵呈块对角,权重与 MAC 降至 c_{\textrm{i}} c_{\textrm{o}} k^2 / g。
  • 深度卷积极限(g = c_{\textrm{i}} = c_{\textrm{o}}):每组仅含单个通道。c_{\textrm{i}} 个通道各自由专属 k \times k 卷积核滤波(c_{\textrm{i}} k^2 个权重),零跨通道混合。

深度可分离卷积:分解空间与通道

两步分解

串联深度 k \times k 空间滤波与逐点 1 \times 1 通道混合,将一层稠密卷积拆为两个轻量步骤:

  • 第 1 步 — 深度卷积(k \times k,g = c_{\textrm{i}}):在每个输入通道内独立做空间滤波:h w c_{\textrm{i}} k^2 次乘加。
  • 第 2 步 — 逐点卷积(1 \times 1,c_{\textrm{i}} \to c_{\textrm{o}}):在每个像素处线性组合 c_{\textrm{i}} 个滤波通道:h w c_{\textrm{i}} c_{\textrm{o}} 次乘加。
  • 表达限制(秩 1 核分解):等价于将每对 (o, c) 的稠密 k\times k 滤波器限制为分解形式 \mathbf{K}_{o,c} = P_{o,c}\,\mathbf{D}_c。

深度可分离的 FLOP 与参数比

量化节省

用两步可分离开销除以标准稠密开销,即得参数量与乘加运算量的精确缩减比:

\frac{\text{Depthwise} + \text{Pointwise}}{\text{Dense}} = \frac{h w \cdot c_{\textrm{i}} k^2 + h w \cdot c_{\textrm{i}} c_{\textrm{o}}}{h w \cdot c_{\textrm{i}} c_{\textrm{o}} k^2} = \frac{1}{c_{\textrm{o}}} + \frac{1}{k^2}

  • 渐近 k^2 缩减:当 c_{\textrm{o}} \gg k^2 时,1/c_{\textrm{o}} 可忽略,3\times 3 可分离层开销降至稠密 3\times 3 的 \approx 1/9(便宜 8\text{--}9\times);7\times 7 可分离层(ConvNeXt)降至 \approx 1/49。
  • 在 c_{\textrm{i}} = c_{\textrm{o}} = 128, k = 3 处验证:(1/128 + 1/9)^{-1} = 147{,}456 / 17{,}536 \approx \mathbf{8.41\times} 权重节省:
(147456, 17536, 8.408759124087592)

MobileNetV1 与深度可分离块

MobileNet 架构

MobileNetV1 将输入主干之后的每层标准卷积替换为 Depthwise 3×3 -> BN -> ReLU -> Pointwise 1×1 -> BN -> ReLU 块:

  • 步幅深度下采样:在深度 3\times 3 卷积上设 stride=2 直接将分辨率减半,省去独立汇聚层。
  • 96\times 96 Fashion-MNIST 上的 Mini-MobileNet:步幅 2 的 32 通道 3\times 3 输入主干接 7 个升至 512 通道的可分离块,仅用 542{,}474 个参数(若这 7 块为稠密 3\times 3 则需 4.66\text{M} 权重——缩减 8.8\times)。

用代码实现深度可分离块

Mini-MobileNet 块

一层深度 3\times 3 卷积(每通道一个滤波器),接一层 1\times 1 逐点通道混合器:

def dws_block(in_channels, out_channels, stride=1):
    """Depthwise 3x3 and pointwise 1x1 convolutions, each with BN and ReLU."""
    return nn.Sequential(
        nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride,
                  padding=1, groups=in_channels, bias=False),
        nn.BatchNorm2d(in_channels), nn.ReLU(),
        nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
        nn.BatchNorm2d(out_channels), nn.ReLU())

def he_init(module):
    """Normal weights with variance 2/n_in and zero biases."""
    if isinstance(module, (nn.Conv2d, nn.Linear)):
        nn.init.kaiming_normal_(module.weight)
        if module.bias is not None:
            nn.init.zeros_(module.bias)

组装 Mini-MobileNet 并统计参数

Mini-MobileNet 骨干

def num_params(model):
    """The number of trainable parameters."""
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

model = MiniMobileNet()
assert model(torch.zeros(1, 1, 96, 96)).shape == (1, 10)
num_params(model)
542474

MobileNetV2:倒置瓶颈与线性投影

倒置瓶颈

当 3\times 3 滤波器为深度而非稠密卷积时,它本身已很廉价——且因每通道仅学一个滤波器,需要更宽的通道空间来保证表达力:

  • 经典 ResNet 瓶颈(左):将 256 \xrightarrow{1\times 1} 64 \to \text{dense } 3\times 3 \to 64 \xrightarrow{1\times 1} 256 压缩,让昂贵的稠密 3\times 3 在窄宽度上运行。
  • 倒置瓶颈(右,MobileNetV2):保持残差主干细窄(24 通道),用 1\times 1 扩展 6\times(24 \to 144),在 144 通道运行深度 3\times 3,再投影回 144 \to 24。
  • 为何末层 1\times 1 投影省略 ReLU:对低维 24 通道瓶颈施加 ReLU 会破坏负坐标;保持窄投影线性可保全信息,窄快捷路径则最小化块间 SRAM 流量。

受控基准:同参数量对比同 FLOPs

三方对比

在 96\times 96 Fashion-MNIST 上对比 MiniMobileNet(542\text{K} 参数、50.3\text{M} MAC)与两个稠密 VGG 风格基线:同参数量的 VGGSmall(584\text{K} 参数,宽至 128)和同乘加运算量的 VGG-style, narrow(49.1\text{M} MAC,宽度 \div 2.8,76\text{K} 参数):

({'Mini-MobileNet': 50259968,
  'VGG-style': 384861440,
  'VGG-style, narrow': 49103308},
 7.657415142007253)
Mini-MobileNet: 542,474 parameters, 50.3M multiply-adds, accuracy 0.917, 1.8 ms/batch
VGG-style: 583,594 parameters, 384.9M multiply-adds, accuracy 0.938, 4.9 ms/batch
VGG-style, narrow: 75,854 parameters, 49.1M multiply-adds, accuracy 0.933, 1.3 ms/batch

为何少 7.7× FLOPs 在 GPU 上仅快 2–3.5×

系统分析:算术强度

  • 同参数量(VGGSmall,385M MAC):MAC 是 MiniMobileNet(50.3\textrm{M})的 7.7\times,在 GPU 上却仅慢 2\text{--}3.5\times(准确率 93.8\% 对比 91.5\%)。
  • 同 FLOPs(VGG-style, narrow,49.1M MAC):准确率胜过 MiniMobileNet(93\%)且跑得更快(耗时 0.5\text{--}0.8\times)。
  • Roofline 瓶颈:深度 3 \times 3 每次访存仅做 9 次 MAC,而稠密 3 \times 3 为 9c_\textrm{o} 次。

复合缩放与延迟感知架构搜索

EfficientNet 与 EfficientNetV2

\text{MACs} \propto d \cdot w^2 \cdot r^2

  • 复合缩放(Tan 与 Le,2019):每步 \phi 将 (d, w, r) 按 (1.2^\phi, 1.1^\phi, 1.15^\phi) 缩放,总计算量乘以 \approx 1.92^\phi。
  • 延迟感知 NAS(EfficientNetV2):在早期高分辨率阶段用融合稠密 3 \times 3 卷积取代深度卷积,以获取更高 GPU 算术强度。

挤压与激励(SE):全局通道注意力

挤压与激励门控

class SE(nn.Module):
    def __init__(self, num_channels, ratio=4):
        super().__init__()
        self.fc = nn.Sequential(
            nn.LazyLinear(num_channels // ratio), nn.ReLU(),
            nn.LazyLinear(num_channels), nn.Sigmoid())

    def forward(self, X):
        s = self.fc(X.mean(dim=(2, 3)))
        return X * s[:, :, None, None]

SE(32)(d2l.randn(2, 32, 16, 16)).shape
torch.Size([2, 32, 16, 16])
  • 挤压 \to 激励 \to 重缩放:将 (C, H, W) \to (C, 1, 1) 汇聚,再过 C \to C/r \to C 门控 MLP(\sigma),额外 MAC 仅 <0.03\%。

RepVGG:多分支训练,单路径推理

结构重参数化

多分支残差拓扑训练时易于优化,而普通单路径 3\times 3 堆叠推理时内存与计算效率最高。RepVGG(Ding 等,2021)通过代数融合打通两者:

  • 训练期块:在 ReLU 前累加三条并行批量规范化分支: \mathbf{Y} = \textrm{ReLU}\bigl(\textrm{BN}_3(\textrm{Conv}_{3\times 3}(\mathbf{X})) + \textrm{BN}_1(\textrm{Conv}_{1\times 1}(\mathbf{X})) + \textrm{BN}_0(\mathbf{X})\bigr)
  • 部署期融合:推理时 \textrm{ReLU}(\cdot) 内部的三条分支均为线性算子,可代数折叠为单层带偏置的 3\times 3 卷积,省去两条分支与两个活跃激活缓冲区。

分支融合的三步线性代数

代数 BN 折叠与卷积核相加

把训练好的 RepVGGBlock 坍缩为单层 3\times 3 卷积 (\hat{\mathbf{W}}, \hat{\mathbf{b}}),对每个输出通道 o 只需三步精确变换:

  • 1. 将推理期 BN 折叠进各分支:用冻结滑动统计 (\mu_o, \sigma_o^2) 与参数 (\gamma_o, \beta_o): \hat{\mathbf{W}}_o = \frac{\gamma_o}{\sqrt{\sigma_o^2 + \epsilon}}\,\mathbf{W}_o, \qquad \hat{b}_o = \beta_o + \frac{\gamma_o(b_o - \mu_o)}{\sqrt{\sigma_o^2 + \epsilon}}
  • 2. 将 1\times 1 与恒等路径嵌入 3\times 3 核:1\times 1 核四周各补 1 像素零;通道 o 的恒等映射写成中心抽头 (i=o, 1, 1) 为 1、其余为 0 的 3\times 3 核。
  • 3. 按线性性求和:\hat{\mathbf{W}}_{\text{fused}} = \hat{\mathbf{W}}^{(3)} + \hat{\mathbf{W}}^{(1)} + \hat{\mathbf{W}}^{(0)},\hat{\mathbf{b}}_{\text{fused}} = \hat{\mathbf{b}}^{(3)} + \hat{\mathbf{b}}^{(1)} + \hat{\mathbf{b}}^{(0)}。

实现分支融合(fuse_bn 与 fuse_block)

RepVGG 融合代码

先将每条分支的 BN 折叠为 3\times 3 卷积核,再将三者相加成单个卷积:

def fuse_bn(W, bn):
    """Fold inference-mode batch normalization into a bias-free conv."""
    scale = bn.weight / torch.sqrt(bn.running_var + bn.eps)
    return W * scale.reshape(-1, 1, 1, 1), bn.bias - bn.running_mean * scale

@torch.no_grad()
def fuse_block(blk):
    c = blk.conv3.weight.shape[0]
    W3, b3 = fuse_bn(blk.conv3.weight, blk.bn3)
    W1, b1 = fuse_bn(F.pad(blk.conv1.weight, (1, 1, 1, 1)), blk.bn1)
    I = torch.zeros_like(W3)  # On the device of the block
    I[torch.arange(c), torch.arange(c), 1, 1] = 1.0
    W0, b0 = fuse_bn(I, blk.bn0)
    fused = nn.Conv2d(c, c, kernel_size=3, padding=1, device=W3.device)
    fused.weight.copy_(W3 + W1 + W0)
    fused.bias.copy_(b3 + b1 + b0)
    return fused

精确 FP32 等价性与 INT8 量化陷阱

代码验证与部署陷阱

实现 fuse_bn 与 fuse_block,在 float32 下验证精确等价,并揭示训练后量化的关键风险:

  • 精确到 FP32 舍入(\sim 10^{-6}):更新滑动统计并随机化 (\gamma, \beta) 后,融合 3\times 3 层与三分支块吻合至 10^{-6} 以内。
  • 陷阱 — FP32 等价 \neq INT8 等价(Chu 等,2024):\hat{\mathbf{W}}_{\text{fused}} 中心抽头累加了三条尺度悬殊的独立规范化分支(\gamma_o / \sqrt{\sigma_o^2 + \epsilon}),导致融合权重出现重尾离群值。朴素 8 位均匀量化(256 级)使融合 RepVGG-B0 在 ImageNet 上从 75.1\% 暴跌至 40.2\%(可用 QAT 或分支尺度正则化修复)。
5.7220458984375e-06

概念自测:可分离节省、SE 开销与 BN 折叠

概念自测

完成以下三道量化效率计算:

  1. 可分离 7\times 7 节省:ConvNeXt(§7.7)的一个块在宽度 c_{\textrm{i}} = c_{\textrm{o}} = 96 下使用 7\times 7 深度卷积后接 1\times 1 卷积。该深度可分离组合比 c = 96 的稠密 7\times 7 卷积便宜多少倍?
  2. 挤压与激励开销:在分辨率 14\times 14、通道 c = 256 的阶段上,比较 SE 门控(r = 4)与单层稠密 3\times 3 卷积(256 \to 256)的乘加运算量。
  3. 手工 BN 折叠:某无偏置卷积通道(b_o = 0)卷积核为 \mathbf{W}_o,后接滑动均值 \mu_o = 0.5、滑动方差 \sigma_o^2 + \epsilon = 0.25、拉伸 \gamma_o = 1、偏移 \beta_o = 0 的 BN。折叠后的核 \hat{\mathbf{W}}_o 与偏置 \hat{b}_o 是多少?

答案:

  1. 缩减比:1/c_{\textrm{o}} + 1/k^2 = 1/96 + 1/49 \approx 0.0308,因此便宜 32.4\times(随 c_{\textrm{o}} 增大趋近 49\times)。
  2. SE 门控:2 c^2 / r = 2(256^2)/4 = 32{,}768 次 MAC(作用于 1\times 1 汇聚向量)。稠密 3\times 3 卷积:14^2 \cdot 9 \cdot 256^2 \approx 115.6\text{M} 次 MAC。SE 门控仅增 0.028\% 算术开销。
  3. 缩放因子 \gamma_o / \sqrt{\sigma_o^2 + \epsilon} = 1 / \sqrt{0.25} = 2。因此 \hat{\mathbf{W}}_o = 2\mathbf{W}_o,\hat{b}_o = 0 + 2(0 - 0.5) = -1。

小结:高效卷积网络的核心要点

小结

技术 数学 / 结构形式 效率收益与实践注意
深度可分离卷积 深度 k\times k(g=c_{\textrm{i}})+ 逐点 1\times 1(c_{\textrm{i}}\to c_{\textrm{o}}) 权重与 MAC 降至 1/c_{\textrm{o}} + 1/k^2(3\times 3 \approx 1/9),但深度步算术强度低(每次访存 9 次 MAC)
倒置瓶颈(MBConv) 窄残差(c)\to 1\times 1(tc)\to \text{DW } 3\times 3(tc)\to 线性 1\times 1(c) 保持块间张量在 SRAM 中细窄;省略末层 ReLU 防止窄瓶颈秩坍缩
复合缩放 按 (d, w, r) \leftarrow (\alpha^\phi d, \beta^\phi w, \gamma^\phi r) 缩放,满足 \alpha\beta^2\gamma^2 \approx 2 同步平衡感受野、特征容量与图像细节(EfficientNet)
挤压与激励(SE) \mathbf{X} \odot \sigma(\mathbf{W}_2\,\textrm{ReLU}(\mathbf{W}_1\,\textrm{GAP}(\mathbf{X}))) 仅用 2c^2/r 权重与 <0.1\% FLOPs 实现全局通道注意力
RepVGG 重参数化 将 \textrm{BN} 折叠进 3\times 3, 1\times 1, \mathbf{I} 三分支并求和为单个 3\times 3 卷积 兼具多分支可训练性与单路径 FP32 推理速度;INT8 量化需控制分支尺度