Ultralytics:解读RepVGGDW模块

在这里插入图片描述

前言

相关介绍

Ultralytics 简介

Ultralytics 基于多年的计算机视觉和人工智能基础研究,创建了最先进的 (SOTA) YOLO 模型。我们的模型不断更新性能和灵活性,快速、准确且易于使用。他们擅长对象检测、跟踪、实例分割、语义分割、图像分类和姿势估计任务。

前提条件

  • 熟悉Python、Pytorch

实验环境

Package                  Version
------------------------ ------------
Python                   3.11.8
absl-py                  2.4.0
accelerate               1.13.0
annotated-doc            0.0.4
anyio                    4.13.0
calflops                 0.3.2
certifi                  2026.4.22
charset-normalizer       3.4.7
click                    8.3.3
colorama                 0.4.6
contourpy                1.3.3
cycler                   0.12.1
filelock                 3.29.0
flatbuffers              25.12.19
fonttools                4.62.1
fsspec                   2026.4.0
grpcio                   1.80.0
h11                      0.16.0
hf-xet                   1.5.0
httpcore                 1.0.9
httpx                    0.28.1
huggingface_hub          1.14.0
idna                     3.15
Jinja2                   3.1.6
kiwisolver               1.5.0
Markdown                 3.10.2
markdown-it-py           4.2.0
MarkupSafe               3.0.3
matplotlib               3.10.9
mdurl                    0.1.2
ml_dtypes                0.5.0
mpmath                   1.3.0
networkx                 3.6.1
numpy                    1.26.4
nvidia-cublas-cu12       12.8.3.14
nvidia-cuda-cupti-cu12   12.8.57
nvidia-cuda-nvrtc-cu12   12.8.61
nvidia-cuda-runtime-cu12 12.8.57
nvidia-cudnn-cu12        9.7.1.26
nvidia-cufft-cu12        11.3.3.41
nvidia-cufile-cu12       1.13.0.11
nvidia-curand-cu12       10.3.9.55
nvidia-cusolver-cu12     11.7.2.55
nvidia-cusparse-cu12     12.5.7.53
nvidia-cusparselt-cu12   0.6.3
nvidia-nccl-cu12         2.26.2
nvidia-nvjitlink-cu12    12.8.61
nvidia-nvtx-cu12         12.8.55
onnx                     1.19.0
onnxruntime-gpu          1.26.0
onnxslim                 0.1.94
opencv-python            4.6.0.66
packaging                26.2
pillow                   12.2.0
pip                      24.0
polars                   1.40.1
polars-runtime-32        1.40.1
protobuf                 7.34.1
psutil                   7.2.2
pycocotools              2.0.11
Pygments                 2.20.0
pyparsing                3.3.2
python-dateutil          2.9.0.post0
PyYAML                   6.0.3
regex                    2026.5.9
requests                 2.34.1
rich                     15.0.0
safetensors              0.7.0
scipy                    1.16.0
setuptools               65.5.0
shellingham              1.5.4
six                      1.17.0
sympy                    1.14.0
tabulate                 0.10.0
tensorboard              2.20.0
tensorboard-data-server  0.7.2
tokenizers               0.22.2
torch                    2.7.1+cu128
torchaudio               2.7.1+cu128
torchvision              0.22.1+cu128
tqdm                     4.67.3
transformers             5.8.1
triton                   3.3.1
typer                    0.25.1
typing_extensions        4.15.0
ultralytics              8.4.58
ultralytics-thop         2.0.19
urllib3                  2.7.0
Werkzeug                 3.1.8

RepVGGDW(RepVGG风格深度卷积块)

RepVGGDW 是一种 RepVGG 风格 的深度卷积块,它包含两个并行的深度卷积分支(3×3 和 7×7),在训练时通过相加融合特征,在推理时利用结构重参数化将两个分支融合为一个等效的 7×7 卷积,从而既享受训练时多分支带来的性能增益,又保持推理时的高效率。该模块常见于 YOLOv6 等轻量级网络的骨干中。


代码实现

import cv2
import math
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch import nn

def autopad(k, p=None, d=1):  # kernel, padding, dilation
    """Pad to 'same' shape outputs."""
    if d > 1:
        k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k]  # actual kernel-size
    if p is None:
        p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-pad
    return p

class Conv(nn.Module):
    """Standard convolution module with batch normalization and activation.

    Attributes:
        conv (nn.Conv2d): Convolutional layer.
        bn (nn.BatchNorm2d): Batch normalization layer.
        act (nn.Module): Activation function layer.
        default_act (nn.Module): Default activation function (SiLU).
    """

    default_act = nn.SiLU()  # default activation

    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
        """Initialize Conv layer with given parameters.

        Args:
            c1 (int): Number of input channels.
            c2 (int): Number of output channels.
            k (int): Kernel size.
            s (int): Stride.
            p (int, optional): Padding.
            g (int): Groups.
            d (int): Dilation.
            act (bool | nn.Module): Activation function.
        """
        super().__init__()
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
        self.bn = nn.BatchNorm2d(c2)
        self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()

    def forward(self, x):
        """Apply convolution, batch normalization and activation to input tensor.

        Args:
            x (torch.Tensor): Input tensor.

        Returns:
            (torch.Tensor): Output tensor.
        """
        return self.act(self.bn(self.conv(x)))

    def forward_fuse(self, x):
        """Apply convolution and activation without batch normalization.

        Args:
            x (torch.Tensor): Input tensor.

        Returns:
            (torch.Tensor): Output tensor.
        """
        return self.act(self.conv(x))

def fuse_conv_and_bn(conv, bn):
    """Fuse Conv2d and BatchNorm2d layers for inference optimization.

    Args:
        conv (nn.Conv2d): Convolutional layer to fuse.
        bn (nn.BatchNorm2d): Batch normalization layer to fuse.

    Returns:
        (nn.Conv2d): The fused convolutional layer with gradients disabled.

    Examples:
        >>> conv = nn.Conv2d(3, 16, 3)
        >>> bn = nn.BatchNorm2d(16)
        >>> fused_conv = fuse_conv_and_bn(conv, bn)
    """
    # Compute fused weights
    w_conv = conv.weight.view(conv.out_channels, -1)
    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
    conv.weight.data = torch.mm(w_bn, w_conv).view(conv.weight.shape)

    # Compute fused bias
    b_conv = (
        torch.zeros(conv.out_channels, device=conv.weight.device, dtype=conv.weight.dtype)
        if conv.bias is None
        else conv.bias
    )
    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
    fused_bias = torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn

    if conv.bias is None:
        conv.register_parameter("bias", nn.Parameter(fused_bias))
    else:
        conv.bias.data = fused_bias

    return conv.requires_grad_(False)

class RepVGGDW(torch.nn.Module):
    """RepVGGDW is a class that represents a depth-wise convolutional block in RepVGG architecture."""

    def __init__(self, ed: int) -> None:
        """Initialize RepVGGDW module.

        Args:
            ed (int): Input and output channels.
        """
        super().__init__()
        self.conv = Conv(ed, ed, 7, 1, 3, g=ed, act=False)
        self.conv1 = Conv(ed, ed, 3, 1, 1, g=ed, act=False)
        self.dim = ed
        self.act = nn.SiLU()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Perform a forward pass of the RepVGGDW block.

        Args:
            x (torch.Tensor): Input tensor.

        Returns:
            (torch.Tensor): Output tensor after applying the depth-wise convolution.
        """
        return self.act(self.conv(x) + self.conv1(x))

    def forward_fuse(self, x: torch.Tensor) -> torch.Tensor:
        """Perform a forward pass of the fused RepVGGDW block.

        Args:
            x (torch.Tensor): Input tensor.

        Returns:
            (torch.Tensor): Output tensor after applying the depth-wise convolution.
        """
        return self.act(self.conv(x))

    @torch.no_grad()
    def fuse(self):
        """Fuse the convolutional layers in the RepVGGDW block.

        This method fuses the convolutional layers and updates the weights and biases accordingly.
        """
        if not hasattr(self, "conv1"):
            return  # already fused
        conv = fuse_conv_and_bn(self.conv.conv, self.conv.bn)
        conv1 = fuse_conv_and_bn(self.conv1.conv, self.conv1.bn)

        conv_w = conv.weight
        conv_b = conv.bias
        conv1_w = conv1.weight
        conv1_b = conv1.bias

        conv1_w = torch.nn.functional.pad(conv1_w, [2, 2, 2, 2])

        final_conv_w = conv_w + conv1_w
        final_conv_b = conv_b + conv1_b

        conv.weight.data.copy_(final_conv_w)
        conv.bias.data.copy_(final_conv_b)

        self.conv = conv
        del self.conv1

功能

  • 多分支训练:并行使用 7×7 和 3×3 深度卷积,两者输出相加后经 SiLU 激活,提升特征表达能力。
  • 重参数化融合:在推理前可通过 fuse() 方法将两个卷积分支融合为一个等效的 7×7 深度卷积(3×3 卷积通过四周填充零变为 7×7),从而减少计算量,提升推理速度。
  • 深度卷积:两个分支均采用分组卷积,分组数等于通道数,实现深度卷积,参数量和计算量显著降低。

初始化参数

参数类型说明
edint输入和输出通道数(模块不改变通道数)
  • self.conv:7×7 深度卷积,步长 1,填充 3,无激活(act=False,仅含 BN)。
  • self.conv1:3×3 深度卷积,步长 1,填充 1,无激活。
  • self.act:SiLU(Swish)激活函数。

前向方法

方法流程用途
forward(x)act(conv(x) + conv1(x))训练模式,双分支
forward_fuse(x)act(conv(x))推理模式,融合后的单分支(需先调用 fuse()

融合机制(fuse 方法)

  1. 融合 BN:调用 fuse_conv_and_bn 分别将 self.convself.conv1 中的卷积层与对应的 BN 层融合为带偏置的卷积层。
  2. 填充 3×3 卷积核:将 3×3 卷积核四周填充 2 个零,扩展为 7×7 卷积核。
  3. 相加:将 7×7 核与填充后的 3×3 核逐元素相加,偏置也相加。
  4. 替换:用融合后的卷积层替换 self.conv,删除 self.conv1

数学原理:两个卷积相加等价于其卷积核相加,因此推理时可合并为一个卷积。


使用示例

在这里插入图片描述

if __name__ == '__main__':
    # 1. 创建随机输入
    x = torch.randn(1, 32, 64, 64)

    # 2. 创建 RepVGGDW 模块
    repvggdw = RepVGGDW(ed=32)

    repvggdw.eval()  # 关键:切换到评估模式,使 BN 使用全局统计量

    # 3. 前向传播(训练模式,双分支)
    with torch.no_grad():
        out_train = repvggdw(x)
    print("训练模式输出形状:", out_train.shape)  # [1,32,64,64]

    # 4. 融合分支
    repvggdw.fuse()
    print("融合完成")

    # 5. 推理模式前向(单分支)
    with torch.no_grad():
        out_fuse = repvggdw.forward_fuse(x)
    print("推理模式输出形状:", out_fuse.shape)  # [1,32,64,64]

    # 6. 验证融合前后一致性
    diff = torch.abs(out_train - out_fuse).max().item()
    print(f"融合前后最大差异: {diff:.6f}")  # 通常 < 1e-5

    # 7. 使用真实图像演示
    img_path = "cat_640x640.png"
    img_bgr = cv2.imread(img_path)
    if img_bgr is not None:
        img_gray = cv2.cvtColor(cv2.resize(img_bgr, (64, 64)), cv2.COLOR_BGR2GRAY)
        img_tensor = torch.from_numpy(img_gray).float().unsqueeze(0).unsqueeze(0)  # [1,1,64,64]
        # 扩展通道数至 32
        x_img = img_tensor.repeat(1, 32, 1, 1)

        # 创建 RepVGGDW(未融合)
        rep_img = RepVGGDW(ed=32)
        with torch.no_grad():
            out_img = rep_img(x_img)  # 训练模式

        # 可视化输入和输出通道0
        inp_ch0 = x_img[0, 0].cpu().numpy()
        out_ch0 = out_img[0, 0].cpu().numpy()

        def norm(arr):
            return (arr - arr.min()) / (arr.max() - arr.min() + 1e-8)

        plt.figure(figsize=(12, 5), constrained_layout=True)
        plt.subplot(1, 3, 1)
        plt.imshow(img_gray, cmap='gray')
        plt.title("Original Gray")
        plt.axis("off")
        plt.subplot(1, 3, 2)
        plt.imshow(norm(inp_ch0), cmap='gray')
        plt.title("Input Ch0")
        plt.axis("off")
        plt.subplot(1, 3, 3)
        plt.imshow(norm(out_ch0), cmap='gray')
        plt.title("RepVGGDW Output Ch0")
        plt.axis("off")
        plt.savefig("repvggdw_demo.png", dpi=150)
        print("可视化已保存为 repvggdw_demo.png")

在这里插入图片描述
输出示例

训练模式输出形状: torch.Size([1, 32, 64, 64])
融合完成
推理模式输出形状: torch.Size([1, 32, 64, 64])
融合前后最大差异: 0.000003
可视化已保存为 repvggdw_demo.png

流程示意图

推理模式(融合后)

输入 x

等效 7x7 depthwise Conv + Bias

SiLU

输出

训练模式

输入 x (B, C, H, W)

Conv 7x7 depthwise + BN

Conv 3x3 depthwise + BN

相加

SiLU

输出


代码解读

  • __init__

    • 定义两个 Conv 模块,均使用 g=ed(分组数等于通道数),实现深度卷积。
    • 7×7 卷积核大小 7,填充 3;3×3 卷积核大小 3,填充 1。
    • 两者 act=False,不包含激活函数,激活在外部统一添加(nn.SiLU())。
  • forward

    • 计算两个分支输出的和,再通过 SiLU。
  • forward_fuse

    • 直接对 self.conv 输出应用 SiLU,因为 self.conv 在融合后已包含两个分支的等效权重。
  • fuse

    • 调用 fuse_conv_and_bn 分别融合两个分支(卷积+BN),得到带偏置的卷积层。
    • 将 3×3 卷积核填充为 7×7(四周各补 2 个零)。
    • 相加权重和偏置,更新 self.conv,删除 self.conv1

注意事项

  1. 融合前需调用 fuse():推理前务必执行融合,否则 forward_fuse 会因 conv1 缺失而报错(若未删除则仍可调用,但不会获得加速)。
  2. 输入输出通道不变:模块不改变通道数和空间尺寸(步长均为 1)。
  3. 与标准 RepVGG 的区别:此处仅使用深度卷积(分组=通道),而非普通卷积,是轻量级版本。
  4. 数值误差:融合前后差异通常在 1e-5 左右,属于正常浮点误差。
  5. SiLU 激活:在融合前后均位于卷积之后,融合时无需特殊处理。

优缺点

优点
  1. 推理加速:融合后仅单个卷积,减少计算量,提升速度。
  2. 训练精度:多分支结构提供更多梯度路径,提升模型表达能力。
  3. 轻量级:深度卷积大幅减少参数量,适合移动端部署。
  4. 即插即用:可替换其他深度卷积块,易于集成。
缺点
  1. 训练内存开销:双分支增加显存占用。
  2. 融合复杂性:需在推理前手动调用 fuse(),增加了部署步骤。
  3. 固定卷积核大小:分支核大小固定为 7 和 3,无法灵活调整。

在 YOLOv6 等网络中,RepVGGDW 常作为骨干网络的基础块,用于构建高效特征提取层。使用时建议训练后统一融合,以最大化推理性能。

参考文献

[1] https://docs.ultralytics.com/
[2] https://github.com/ultralytics/ultralytics.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FriendshipT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值