Ultralytics:解读Proto模块

Ultralytics:解读Proto模块

前言

相关介绍

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

Proto(YOLO 分割掩码原型生成模块)

Proto 是 Ultralytics YOLO 系列(如 YOLOv8‑seg)中用于 实例分割 的核心组件,负责从特征图中生成一组 原型掩码(prototype masks) 。这些原型掩码是通用的、与类别无关的"基掩码",后续会与每个检测框的掩码系数(mask coefficients)进行线性组合,得到最终的分割掩码。该模块通过 卷积层 + 转置卷积上采样 的方式,将输入特征图转换为固定数量的原型掩码图,其空间分辨率通常为输入特征图的 2 倍。


代码实现

python 复制代码
import cv2
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt

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 Proto(nn.Module):
    """Ultralytics YOLO models mask Proto module for segmentation models."""

    def __init__(self, c1: int, c_: int = 256, c2: int = 32):
        """Initialize the Ultralytics YOLO models mask Proto module with specified number of protos and masks.

        Args:
            c1 (int): Input channels.
            c_ (int): Intermediate channels.
            c2 (int): Output channels (number of protos).
        """
        super().__init__()
        self.cv1 = Conv(c1, c_, k=3)
        self.upsample = nn.ConvTranspose2d(c_, c_, 2, 2, 0, bias=True)  # nn.Upsample(scale_factor=2, mode='nearest')
        self.cv2 = Conv(c_, c_, k=3)
        self.cv3 = Conv(c_, c2)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Perform a forward pass through layers using an upsampled input image."""
        return self.cv3(self.cv2(self.upsample(self.cv1(x))))

功能

  • 特征降维与提炼 :通过 cv1 3×3 卷积将输入通道 c1 压缩到中间通道 c_,提取紧凑特征。
  • 空间上采样 :使用 2×2 转置卷积(ConvTranspose2d)将特征图的空间尺寸放大 2 倍(高和宽各翻倍),增加细节分辨率。
  • 特征精炼与输出 :再经过 cv2cv3 两个 3×3 卷积,最终输出通道数为 c2 的特征图,其中每个通道即为一个原型掩码。
  • 输出尺寸 :最终输出的空间尺寸为输入尺寸的 2 倍,通道数为原型数量 c2

初始化参数

参数 类型 说明
c1 int 输入特征图的通道数(通常来自骨干网络)
c_ int 中间通道数(默认 256),用于降低计算量
c2 int 输出通道数(默认 32),即生成的原型掩码数量
  • cv1cv2cv3 均为 Conv 模块(包含卷积 + BatchNorm + SiLU 激活),卷积核大小为 3,步长为 1,填充自动 same。
  • upsample 为 2×2 转置卷积(nn.ConvTranspose2d),输入/输出通道均为 c_,步长 2,无填充,带偏置。

前向方法

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

计算流程

  1. x = self.cv1(x)[B, c_, H, W]
  2. x = self.upsample(x)[B, c_, 2H, 2W]
  3. x = self.cv2(x)[B, c_, 2H, 2W]
  4. x = self.cv3(x)[B, c2, 2H, 2W]

使用示例

python 复制代码
if __name__ == '__main__':
    # 1. 模拟输入特征图(通常来自骨干网络或 Neck)
    B, c1, H, W = 2, 128, 32, 32
    x = torch.randn(B, c1, H, W)

    # 2. 创建 Proto 模块(输入通道128,中间256,输出32个原型)
    proto = Proto(c1=128, c_=256, c2=32)

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

    # 4. 使用真实图像演示(仅演示流程,实际需提取特征图)
    img_path = "cat_640x640.png"
    img_bgr = cv2.imread(img_path)
    if img_bgr is not None:
        # 缩放到 64x64 并转为张量
        img_rgb = cv2.cvtColor(cv2.resize(img_bgr, (64, 64)), cv2.COLOR_BGR2RGB)
        img_tensor = torch.from_numpy(img_rgb).float().permute(2, 0, 1).unsqueeze(0) / 255.0  # [1,3,64,64]
        # 模拟一个简单的特征图(通过卷积提取)
        dummy_conv = nn.Conv2d(3, 128, 3, 1, 1)
        with torch.no_grad():
            feat = dummy_conv(img_tensor)  # [1,128,64,64]
        # 使用 Proto
        proto_img = Proto(c1=128, c_=64, c2=4)  # 生成4个原型
        with torch.no_grad():
            protos = proto_img(feat)  # [1, 4, 128, 128]

        # 可视化第一个原型掩码
        proto0 = protos[0, 0].cpu().numpy()  # [128, 128]
        proto0 = (proto0 - proto0.min()) / (proto0.max() - proto0.min() + 1e-8)

        plt.figure(figsize=(10, 5))
        plt.subplot(1, 2, 1)
        plt.imshow(img_rgb)
        plt.title("Original")
        plt.axis("off")
        plt.subplot(1, 2, 2)
        plt.imshow(proto0, cmap='gray')
        plt.title("Prototype 0")
        plt.axis("off")
        plt.savefig("proto_demo.png", dpi=150)
        print("可视化已保存为 proto_demo.png")

输出示例

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

流程示意图

#mermaid-svg-uYoPN3ov6EgsZhsK{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-uYoPN3ov6EgsZhsK .error-icon{fill:#552222;}#mermaid-svg-uYoPN3ov6EgsZhsK .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-uYoPN3ov6EgsZhsK .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-uYoPN3ov6EgsZhsK .marker{fill:#333333;stroke:#333333;}#mermaid-svg-uYoPN3ov6EgsZhsK .marker.cross{stroke:#333333;}#mermaid-svg-uYoPN3ov6EgsZhsK svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-uYoPN3ov6EgsZhsK p{margin:0;}#mermaid-svg-uYoPN3ov6EgsZhsK .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-uYoPN3ov6EgsZhsK .cluster-label text{fill:#333;}#mermaid-svg-uYoPN3ov6EgsZhsK .cluster-label span{color:#333;}#mermaid-svg-uYoPN3ov6EgsZhsK .cluster-label span p{background-color:transparent;}#mermaid-svg-uYoPN3ov6EgsZhsK .label text,#mermaid-svg-uYoPN3ov6EgsZhsK span{fill:#333;color:#333;}#mermaid-svg-uYoPN3ov6EgsZhsK .node rect,#mermaid-svg-uYoPN3ov6EgsZhsK .node circle,#mermaid-svg-uYoPN3ov6EgsZhsK .node ellipse,#mermaid-svg-uYoPN3ov6EgsZhsK .node polygon,#mermaid-svg-uYoPN3ov6EgsZhsK .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-uYoPN3ov6EgsZhsK .rough-node .label text,#mermaid-svg-uYoPN3ov6EgsZhsK .node .label text,#mermaid-svg-uYoPN3ov6EgsZhsK .image-shape .label,#mermaid-svg-uYoPN3ov6EgsZhsK .icon-shape .label{text-anchor:middle;}#mermaid-svg-uYoPN3ov6EgsZhsK .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-uYoPN3ov6EgsZhsK .rough-node .label,#mermaid-svg-uYoPN3ov6EgsZhsK .node .label,#mermaid-svg-uYoPN3ov6EgsZhsK .image-shape .label,#mermaid-svg-uYoPN3ov6EgsZhsK .icon-shape .label{text-align:center;}#mermaid-svg-uYoPN3ov6EgsZhsK .node.clickable{cursor:pointer;}#mermaid-svg-uYoPN3ov6EgsZhsK .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-uYoPN3ov6EgsZhsK .arrowheadPath{fill:#333333;}#mermaid-svg-uYoPN3ov6EgsZhsK .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-uYoPN3ov6EgsZhsK .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-uYoPN3ov6EgsZhsK .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-uYoPN3ov6EgsZhsK .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-uYoPN3ov6EgsZhsK .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-uYoPN3ov6EgsZhsK .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-uYoPN3ov6EgsZhsK .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-uYoPN3ov6EgsZhsK .cluster text{fill:#333;}#mermaid-svg-uYoPN3ov6EgsZhsK .cluster span{color:#333;}#mermaid-svg-uYoPN3ov6EgsZhsK div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-uYoPN3ov6EgsZhsK .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-uYoPN3ov6EgsZhsK rect.text{fill:none;stroke-width:0;}#mermaid-svg-uYoPN3ov6EgsZhsK .icon-shape,#mermaid-svg-uYoPN3ov6EgsZhsK .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-uYoPN3ov6EgsZhsK .icon-shape p,#mermaid-svg-uYoPN3ov6EgsZhsK .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-uYoPN3ov6EgsZhsK .icon-shape .label rect,#mermaid-svg-uYoPN3ov6EgsZhsK .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-uYoPN3ov6EgsZhsK .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-uYoPN3ov6EgsZhsK .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-uYoPN3ov6EgsZhsK :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 输入 x (B, c1, H, W)
cv1: Conv 3x3, c1 → c_
特征 (B, c_, H, W)
upsample: ConvTranspose2d, 2×2, stride=2
上采样 (B, c_, 2H, 2W)
cv2: Conv 3x3, c_ → c_
特征 (B, c_, 2H, 2W)
cv3: Conv 3x3, c_ → c2
输出原型 (B, c2, 2H, 2W)


代码解读

  • __init__
    • self.cv1:3×3 卷积,将输入通道 c1 压缩到 c_,减少后续计算量。
    • self.upsample:转置卷积(反卷积),将空间尺寸放大 2 倍,同时保持通道数 c_。与双线性插值上采样相比,转置卷积是可学习的,能提供更精细的上采样效果。
    • self.cv2self.cv3:两个 3×3 卷积,进一步精炼特征,最终将通道数压缩到原型数量 c2
  • forward:顺序执行上述层,输出原型掩码。

注意事项

  1. 输入与输出尺寸关系:输出空间尺寸为输入尺寸的 2 倍,因此输入特征图的分辨率需适中(过高会增加计算量,过低则丢失细节)。
  2. 原型数量 c2:通常设置为 32 左右,过多会增加计算量,过少则影响分割精度。
  3. 转置卷积的"棋盘效应" :使用 ConvTranspose2d 可能产生棋盘格伪影,但 YOLO 设计中后续会与掩码系数结合,且使用了 BatchNorm 和激活,可缓解该问题。
  4. 激活函数Conv 模块默认使用 SiLU(Swish),与 YOLOv8 整体风格一致。
  5. 训练与推理:该模块在训练和推理阶段行为相同,无特殊模式。

优缺点

优点
  1. 高效:仅由 3 个卷积层和 1 个上采样层组成,参数少,计算快。
  2. 可学习上采样:使用转置卷积而非固定插值,使上采样过程可调,有助于生成更精细的原型。
  3. 输出分辨率高:将特征图分辨率提升至 2 倍,有利于小目标分割。
缺点
  1. 转置卷积可能引入伪影:在不适当的初始化或训练下,可能产生棋盘格效应。
  2. 输出尺寸固定为 2 倍:无法灵活调整上采样倍数(如需 4 倍需修改代码)。
  3. 原型之间缺乏显式约束:生成的原型掩码可能重复或冗余,需依赖训练数据学习多样性。

在 YOLOv8‑seg 中,Proto 模块位于检测头之前,与掩码系数预测分支并行,共同生成最终的分割掩码。它通过少量参数实现了从特征图到原型掩码的转换,是实例分割任务的关键组成部分。使用时可根据输入特征图尺寸调整 c_c2,以平衡计算量和精度。

参考文献

1 https://docs.ultralytics.com/

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

相关推荐
AI小白Lin1 小时前
Agent Harness 越堆越烂?600 次实验推翻"自进化",个人场景下更适合"自驯化"
人工智能·架构
ViperL11 小时前
[智能算法]NASSFG-显著特征指导的医学目标检测NAS
人工智能·目标检测·计算机视觉
ShallWeL1 小时前
Orin 上 USB / CSI 相机采集踩坑
人工智能·嵌入式硬件·智能硬件·agi
武子康1 小时前
Pi vs Claude Code vs Codex 正确读法:6 组同模型匹配 + 2.08×/1.46×/1.20×/1.54×/1.22×/1.44× 成
人工智能·ai编程·claude
renhongxia11 小时前
AI安全保卫战:我们如何防止“失控”的智能体?
人工智能·深度学习·安全·机器学习·架构·机器人
江边风声1 小时前
PCB自动化收放板机 在薄板制程中的特殊取放策略——0.05mm芯板怎么稳抓不掉
人工智能·科技·自动化·制造·pcb工艺
zhiSiBuYu05171 小时前
Python3 循环语句新手实战指南
python
ShirleyWang0121 小时前
Day02 K3s NGF(Nginx Gateway Fabric)单 Worker 环境网关更新与故障处置 SOP
linux·服务器·python·k8s·k3s
ZDQNFU1 小时前
ORM之SQLAlchemy教程
后端·python