Ultralytics:解读C1模块

Ultralytics:解读C1模块

前言

相关介绍

Ultralytics 简介

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

前提条件

  • 熟悉Python、Pytorch

实验环境

bash 复制代码
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

C1(CSP Bottleneck with 1 convolution)

C1 是一种轻量级的 CSP(Cross Stage Partial)瓶颈模块 ,它仅使用 1 个 1×1 卷积多个 3×3 卷积 构建残差结构。在 YOLOv5 等模型中,它常被用作基础构建块,以平衡计算量与特征表达能力。


代码实现

python 复制代码
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))

class C1(nn.Module):
    """CSP Bottleneck with 1 convolution."""

    def __init__(self, c1: int, c2: int, n: int = 1):
        """Initialize the CSP Bottleneck with 1 convolution.

        Args:
            c1 (int): Input channels.
            c2 (int): Output channels.
            n (int): Number of convolutions.
        """
        super().__init__()
        self.cv1 = Conv(c1, c2, 1, 1)
        self.m = nn.Sequential(*(Conv(c2, c2, 3) for _ in range(n)))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Apply convolution and residual connection to input tensor."""
        y = self.cv1(x)
        return self.m(y) + y

功能

  • 通道变换 :通过 1×1 卷积将输入通道从 c1 映射到 c2,同时实现跨通道信息融合。
  • 多层特征提取 :对变换后的特征图依次应用 n 个 3×3 卷积(保持通道数不变),捕获空间特征。
  • 残差连接 :将 1×1 卷积的输出与经过 n 个 3×3 卷积的输出相加,缓解梯度消失,促进深层训练。
  • CSP 风格:虽然未显式拆分特征图,但其结构类似于 CSPNet 中的部分残差块,仅使用单个卷积进行通道调整。

初始化参数

参数 类型 说明
c1 int 输入特征图的通道数
c2 int 输出特征图的通道数(也是中间特征的通道数)
n int 3×3 卷积的层数(默认为 1),控制模块深度

前向方法

  • forward(x):输入 x(形状 [B, c1, H, W]),输出 [B, c2, H, W]

计算流程

  1. y = self.cv1(x):1×1 卷积,通道数变为 c2
  2. z = self.m(y)n 个 3×3 卷积依次作用在 y 上,输出仍为 [B, c2, H, W]
  3. 返回 z + y(残差相加)。

使用示例

python 复制代码
if __name__ == '__main__':
    # 1. 创建随机输入特征图(模拟 batch=1, 通道=16, 高宽=64)
    x = torch.randn(1, 16, 64, 64)

    # 2. 创建 C1 模块:输入通道 16,输出通道 32,n=2(两个 3x3 卷积)
    c1_block = C1(c1=16, c2=32, n=2)

    # 3. 前向传播
    with torch.no_grad():
        out = c1_block(x)
    print("输入形状:", x.shape)   # [1, 16, 64, 64]
    print("输出形状:", out.shape) # [1, 32, 64, 64]

    # 4. 使用真实图像演示(需将图像转为特征图,这里直接展示输入输出通道0)
    img_path = "cat_640x640.png"
    img_bgr = cv2.imread(img_path)
    if img_bgr is not None:
        # 缩放到 64x64,转为灰度图并升维为单通道特征
        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]
        # 为了匹配 c1=16,复制通道(模拟特征图)
        x_img = img_tensor.repeat(1, 16, 1, 1)  # [1,16,64,64]
        
        # 创建 C1 模块(输入16,输出32,n=1)
        c1_img = C1(c1=16, c2=32, n=1)
        with torch.no_grad():
            out_img = c1_img(x_img)  # [1,32,64,64]
        
        # 可视化:输入通道0、输出通道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("C1 Output Ch0")
        plt.axis("off")
        plt.savefig("c1_demo.png", dpi=150)
        print("可视化已保存为 c1_demo.png")

输出示例

复制代码
输入形状: torch.Size([1, 16, 64, 64])
输出形状: torch.Size([1, 32, 64, 64])
可视化已保存为 c1_demo.png

流程示意图


代码解读

  • __init__
    • self.cv1:1×1 卷积,用于调整通道数并整合跨通道信息。
    • self.m:由 nConv(c2, c2, 3) 组成的序列,每个卷积保持通道数不变,步长为 1,自动填充(autopad(3))保证空间尺寸不变。
  • forward
    • y = self.cv1(x) 得到中间特征。
    • self.m(y) 经过 n 个 3×3 卷积提取更深层特征。
    • 最后将 yself.m(y) 逐元素相加,形成残差连接。

注意事项

  1. 通道数变化 :1×1 卷积将输入通道从 c1 变为 c2,后续 3×3 卷积保持 c2 不变,因此输出通道为 c2
  2. n 的作用n 控制 3×3 卷积的堆叠数量,可增加模型深度,但也会带来更多计算量。
  3. 空间尺寸不变:所有卷积步长均为 1,填充为自动 same,因此输入输出空间尺寸完全相同。
  4. 残差连接 :由于 yself.m(y) 形状相同,可直接相加,无需额外投影。
  5. 与标准 Bottleneck 的区别 :标准瓶颈通常包含两个卷积(1×1 降维、3×3 卷积、1×1 升维),而 C1 只有 1 个 1×1 和多个 3×3,结构更简洁。

优缺点

优点
  1. 参数量较少 :相比标准瓶颈,C1 减少了 1×1 卷积的数量,尤其当 n 较小时更轻量。
  2. 残差结构:缓解梯度消失,便于训练更深网络。
  3. 灵活调节深度 :通过 n 可方便地控制网络深度。
  4. 即插即用:可嵌入 YOLO、ResNet 等架构中。
缺点
  1. 表达能力有限:仅使用单一 1×1 卷积进行通道变换,可能不如双瓶颈结构(降维再升维)表达力强。
  2. 计算量随 n 线性增长n 较大时,3×3 卷积堆叠会增加计算开销。
  3. 无显式 CSP 分割:未像标准 CSP 那样将特征图分为两部分分别处理,可能影响梯度多样性。

在 YOLOv5 等网络中,C1 常作为 C3 模块的基础组件(C3 包含两个 C1 分支)。实际使用时,可根据任务需求调整 n 值,并在通道数较大的层适当增加 n 以提升特征提取能力。

参考文献

1 https://docs.ultralytics.com/

2 https://github.com/ultralytics/ultralytics.git