【Bug解决】YOLOv5 5.0 加载 6.0+版本的模型推理的兼容性问题

问题描述

使用YOLOv5 5.0版本加载6.0版本以上的模型时,会产生报错,本质原因是6.0及以上版本的网络结构发生了变化,如取消Focus结构,新增SPPF结构等。

下面进行解决。

问题一

AttributeError: Can't get attribute 'SPPF' on <module 'models.common'

这个报错只需要在5.0版本的工程中models/common文件中添加:

python 复制代码
class SPPF(nn.Module):
    # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))
        super().__init__()
        c_ = c1 // 2  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * 4, c2, 1, 1)
        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)

    def forward(self, x):
        x = self.cv1(x)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')  # suppress torch 1.9.0 max_pool2d() warning
            y1 = self.m(x)
            y2 = self.m(y1)
            return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))

问题二

RuntimeError: The size of tensor a (40) must match the size of tensor b (84) at non-singleton dimension 3

这个报错需要在models/yolo将Detect类进行替换。

python 复制代码
class Detect(nn.Module):
    stride = None  # strides computed during build
    onnx_dynamic = False  # ONNX export parameter

    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # detection layer
        super().__init__()
        self.nc = nc  # number of classes
        self.no = nc + 5  # number of outputs per anchor
        self.nl = len(anchors)  # number of detection layers
        self.na = len(anchors[0]) // 2  # number of anchors
        self.grid = [torch.zeros(1)] * self.nl  # init grid
        self.anchor_grid = [torch.zeros(1)] * self.nl  # init anchor grid
        self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2))  # shape(nl,na,2)
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv
        self.inplace = inplace  # use in-place ops (e.g. slice assignment)

    def forward(self, x):
        z = []  # inference output
        for i in range(self.nl):
            x[i] = self.m[i](x[i])  # conv
            bs, _, ny, nx = x[i].shape  # x(bs,255,20,20) to x(bs,3,20,20,85)
            x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()

            if not self.training:  # inference
                if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:
                    self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)

                y = x[i].sigmoid()
                if self.inplace:
                    y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # xy
                    y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh
                else:  # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
                    xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # xy
                    wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh
                    y = torch.cat((xy, wh, y[..., 4:]), -1)
                z.append(y.view(bs, -1, self.no))

        return x if self.training else (torch.cat(z, 1), x)

    def _make_grid(self, nx=20, ny=20, i=0):
        d = self.anchors[i].device
        yv, xv = torch.meshgrid([torch.arange(ny).to(d), torch.arange(nx).to(d)])
        grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float()
        anchor_grid = (self.anchors[i].clone() * self.stride[i]) \
            .view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float()
        return grid, anchor_grid

可以注意到,替换之后的Detect类在原报错位置增加了一个判断分支,这使得该类能够同时兼容5.0和6.0的推理模型。

相关推荐
Virgil1391 小时前
用PaddleDetection套件训练自己的数据集,PP-YOLO-SOD训练全流程
yolo
phantom_11119 小时前
Cursor 分析 bug 记录
bug·cursor
Coovally AI模型快速验证21 小时前
YOLO、DarkNet和深度学习如何让自动驾驶看得清?
深度学习·算法·yolo·cnn·自动驾驶·transformer·无人机
程序猿小D2 天前
【完整源码+数据集+部署教程】孔洞检测系统源码和数据集:改进yolo11-RetBlock
yolo·计算机视觉·毕业设计·数据集·yolo11·孔洞检测
Direction_Wind2 天前
Flinksql bug: Heartbeat of TaskManager with id container_XXX timed out.
大数据·flink·bug
钓了猫的鱼儿3 天前
无人机航拍数据集|第14期 无人机水体污染目标检测YOLO数据集3000张yolov11/yolov8/yolov5可训练
yolo·目标检测·猫脸码客·yolo数据集·无人机航拍数据集·无人机水体污染目标检测
飞翔的佩奇4 天前
【完整源码+数据集+部署教程】武器目标检测系统源码和数据集:改进yolo11-AggregatedAtt
人工智能·python·yolo·目标检测·计算机视觉·数据集·yolo11
AIBigModel5 天前
智能情趣设备、爆 bug:可被远程操控。。。
网络·安全·bug
Direction_Wind5 天前
flinksql bug: Received resultset tuples, but no field str
bug
欣赏你流浪^5 天前
物联网智能感知进阶:基于YOLO的琏雾系统视频分析
物联网·yolo·音视频