关于人工智能:YOLOv5全面解析教程①网络结构逐行代码解读

8次阅读

共计 16764 个字符,预计需要花费 42 分钟才能阅读完成。

撰文 | Fengwen, BBuf

本教程波及的代码在:
https://github.com/Oneflow-In…

教程也同样实用于 Ultralytics/YOLOv5,因为 One-YOLOv5 仅仅是换了一个运行时后端而已,计算逻辑和代码相比 Ultralytics/YOLOv5 没有做任何扭转,欢送 star。详细信息请看:一个更快的 YOLOv5 问世,附送全面中文解析教程

1

引言

YOLOv5 针对不同大小(n, s, m, l, x)的网络整体架构都是一样的,只不过会在每个子模块中采纳不同的深度和宽度,别离应答 yaml 文件中的 depth_multiple 和 width_multiple 参数。

还须要留神一点,官网除了 n, s, m, l, x 版本外还有 n6, s6, m6, l6, x6,区别在于后者是针对更大分辨率的图片比方 1280×1280, 当然构造上也有些差别,前者只会下采样到 32 倍且采纳 3 个预测特色层 , 而后者会下采样 64 倍,采纳 4 个预测特色层。

本章将以 YOLOv5s 为例,
从配置文件 models/yolov5s.yaml
(https://github.com/Oneflow-In…)到 models/yolo.py (https://github.com/Oneflow-In…)
源码进行解读。

2

yolov5s.yaml 文件内容

nc: 80  # number of classes 数据集中的类别数
depth_multiple: 0.33  # model depth multiple  模型层数因子(用来调整网络的深度)
width_multiple: 0.50  # layer channel multiple 模型通道数因子(用来调整网络的宽度)
# 如何了解这个 depth_multiple 和 width_multiple 呢? 它决定的是整个模型中的深度(层数)和宽度(通道数), 具体怎么调整的联合前面的 backbone 代码解释。anchors: # 示意作用于以后特色图的 Anchor 大小为 xxx
# 9 个 anchor,其中 P 示意特色图的层级,P3/ 8 该层特色图缩放为 1 /8, 是第 3 层特色
  - [10,13, 16,30, 33,23]  # P3/8,示意[10,13],[16,30], [33,23]3 个 anchor
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32


# YOLOv5s v6.0 backbone
backbone:
  # [from, number, module, args]
  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2
   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4
   [-1, 3, C3, [128]],
   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8
   [-1, 6, C3, [256]],
   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16
   [-1, 9, C3, [512]],
   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32
   [-1, 3, C3, [1024]],
   [-1, 1, SPPF, [1024, 5]],  # 9
  ]

# YOLOv5s v6.0 head
head:
  [[-1, 1, Conv, [512, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 6], 1, Concat, [1]],  # cat backbone P4
   [-1, 3, C3, [512, False]],  # 13

   [-1, 1, Conv, [256, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 4], 1, Concat, [1]],  # cat backbone P3
   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)

   [-1, 1, Conv, [256, 3, 2]],
   [[-1, 14], 1, Concat, [1]],  # cat head P4
   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)

   [-1, 1, Conv, [512, 3, 2]],
   [[-1, 10], 1, Concat, [1]],  # cat head P5
   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)

   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)
  ]

3

anchors 解读

YOLOv5 初始化了 9 个 anchors,别离在三个特色图(feature map)中应用,每个 feature map 的每个 grid cell 都有三个 anchor 进行预测。调配规定:

  • 尺度越大的 feature map 越靠前,绝对原图的下采样率越小,感触野越小,所以绝对能够预测一些尺度比拟小的物体(小指标),调配到的 anchors 越小。
  • 尺度越小的 feature map 越靠后,绝对原图的下采样率越大,感触野越大,所以能够预测一些尺度比拟大的物体(大指标),所以调配到的 anchors 越大。
  • 即在小特色图(feature map)上检测大指标,中等大小的特色图上检测中等指标,在大特色图上检测小指标。

4

backbone & head 解读

[from, number, module, args] 参数

四个参数的意义别离是:

  1. 第一个参数 from:从哪一层取得输出,- 1 示意从上一层取得,[-1, 6]示意从下层和第 6 层两层取得。
  2. 第二个参数 number:示意有几个雷同的模块,如果为 9 则示意有 9 个雷同的模块。
  3. 第三个参数 module:模块的名称,这些模块写在 common.py 中。
  4. 第四个参数 args:类的初始化参数,用于解析作为 moudle 的传入参数。

上面以第一个模块 Conv 为例介绍下 common.py 中的模块

Conv 模块定义如下:

class Conv(nn.Module):
    # Standard convolution
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
        """
        @Pargm c1: 输出通道数
        @Pargm c2: 输入通道数
        @Pargm k : 卷积核大小(kernel_size)
        @Pargm s : 卷积步长 (stride)
        @Pargm p : 特色图填充宽度 (padding)
        @Pargm g : 管制分组,必须整除输出的通道数(保障输出的通道能被正确分组)
        """
        super().__init__()
        # https://oneflow.readthedocs.io/en/master/generated/oneflow.nn.Conv2d.html?highlight=Conv
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
        self.bn = nn.BatchNorm2d(c2)
        self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())

    def forward(self, x):
        return self.act(self.bn(self.conv(x)))

    def forward_fuse(self, x):
        return self.act(self.conv(x))

比方下面把 width_multiple 设置为了 0.5,那么第一个 [64, 6, 2, 2] 就会被解析为 [3,64*0.5=32,6,2,2],其中第一个 3 为输出 channel(因为输出),32 为输入 channel。

对于调整网络大小的详解阐明

在 yolo.py (https://github.com/Oneflow-In…)的 256 行 有对 yaml 文件的 nc,depth_multiple 等参数读取,具体代码如下:


anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']

“width_multiple” 参数的作用后面介绍 args 参数中曾经介绍过了,那么 ”depth_multiple” 又是什么作用呢?

在 yolo.py (https://github.com/Oneflow-In…) 的 257 行有对参数的具体定义:

 n = n_ = max(round(n * gd), 1) if n > 1 else n  # depth gain 暂且将这段代码当作公式(1)

其中 gd 就是 depth_multiple 的值,n 的值就是 backbone 中列表的第二个参数:

依据公式 (1) 很容易看出 gd 影响 n 的大小,从而影响网络的构造大小。

前面各层之间的模块数量、卷积核大小和数量等也都产生了变动,YOLOv5l 与 YOLOv5s 相比拟起来训练参数的大小成倍数增长,

其模型的深度和宽度也会大很多,这就使得 YOLOv5l 的精度值要比 YOLOv5s 好很多,因而在最终推理时的检测精度高,然而模型的推理速度更慢。

所以 YOLOv5 提供了不同的抉择,如果想要谋求推理速度可选用较小一些的模型如 YOLOv5s、YOLOv5m,如果想要谋求精度更高对推理速度要求不高的能够抉择其余两个稍大的模型。

如上面这张图:

yolov5 模型复杂度比拟图

5

Conv 模块解读

网络结构预览

上面是依据 yolov5s.yaml
(https://github.com/Oneflow-In…) 绘制的网络整体构造简化版。

yolov5s 网络整体结构图

1. 具体的网络结构图:
https://oneflow-static.oss-cn…
通过 export.py 导出的 onnx 格局,并通过 https://netron.app/ 网站导出的图片(模型导出将在本教程的后续文章独自介绍)。

2. 模块组件左边参数 示意特色图的的形态,比方 在 第 一 层 (Conv) 输出 图片形态为 [3, 640, 640] , 对于这些参数,能够固定一张图片输出到网络并通过 yolov5s.yaml
(https://github.com/Oneflow-In…) 的模型参数计算失去,并且能够在工程 models/yolo.py(https://github.com/Oneflow-In…) 通过代码进行 print 查看,具体数据能够参考附件表 2.1。

6

yolo.py 模块解读

文件地址(https://github.com/Oneflow-In…)

文件次要蕴含三大部分: Detect 类、Model 类和 parse_model 函数

能够通过 python models/yolo.py –cfg yolov5s.yaml 运行该脚本进行察看

7

parse_model 函数解读

def parse_model(d, ch):  # model_dict, input_channels(3)
    """ 用在上面 Model 模块中
    解析模型文件(字典模式),并搭建网络结构
    这个函数其实次要做的就是: 更新以后层的 args(参数), 计算 c2(以后层的输入 channel)=>
                          应用以后层的参数搭建以后层 =>
                          生成 layers + save
    @Params d: model_dict 模型文件 字典模式 {dict:7}  [yolov5s.yaml](https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolov5s.yaml)中的 6 个元素 + ch
    #Params ch: 记录模型每一层的输入 channel 初始 ch=[3] 前面会删除
    @return nn.Sequential(*layers): 网络的每一层的层构造
    @return sorted(save): 把所有层构造中 from 不是 - 1 的值记下 并排序 [4, 6, 10, 14, 17, 20, 23]
    """LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}")
    # 读取 d 字典中的 anchors 和 parameters(nc、depth_multiple、width_multiple)
    anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
    # na: number of anchors 每一个 predict head 上的 anchor 数 = 3
    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors
    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5) 每一个 predict head 层的输入 channel 
    # 开始搭建网络
    # layers: 保留每一层的层构造
    # save: 记录下所有层构造中 from 中不是 - 1 的层构造序号
    # c2: 保留以后层的输入 channel
    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out
    # enumerate() 函数用于将一个可遍历的数据对象 (如列表、元组或字符串) 组合为一个索引序列,同时列出数据和数据下标,个别用在 for 循环当中。for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args
        m = eval(m) if isinstance(m, str) else m  # eval strings
        for j, a in enumerate(args):
            # args 是一个列表,这一步把列表中的内容取出来
            with contextlib.suppress(NameError):
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings
        
        # 将深度与深度因子相乘,计算层深度。深度最小为 1. 
        n = n_ = max(round(n * gd), 1) if n > 1 else n  # depth gain
        
        # 如果以后的模块 m 在本我的项目定义的模块类型中,就能够解决这个模块
        if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
                 BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x):
            # c1: 输出通道数 c2:输入通道数
            c1, c2 = ch[f], args[0] 
            # 该层不是最初一层,则将通道数乘以宽度因子 也就是说,宽度因子作用于除了最初一层之外的所有层
            if c2 != no:  # if not output
                # make_divisible 的作用,使得原始的通道数乘以宽度因子之后取整到 8 的倍数,这样解决个别是让模型的并行性和推理性能更好。c2 = make_divisible(c2 * gw, 8)

            # 将后面的运算后果保留在 args 中,它也就是这个模块最终的输出参数。args = [c1, c2, *args[1:]] 
            # 依据每层网络参数的不同,别离解决参数 具体各个类的参数是什么请参考它们的__init__办法这里不再具体解释了
            if m in [BottleneckCSP, C3, C3TR, C3Ghost, C3x]:
                # 这里的意思就是反复 n 次,比方 conv 这个模块反复 n 次,这个 n 是下面算进去的 depth 
                args.insert(2, n)  # number of repeats
                n = 1
        elif m is nn.BatchNorm2d:
            args = [ch[f]]
        elif m is Concat:
            c2 = sum(ch[x] for x in f)
        elif m is Detect:
            args.append([ch[x] for x in f])
            if isinstance(args[1], int):  # number of anchors
                args[1] = [list(range(args[1] * 2))] * len(f)
        elif m is Contract:
            c2 = ch[f] * args[0] ** 2
        elif m is Expand:
            c2 = ch[f] // args[0] ** 2
        else:
            c2 = ch[f]
        # 构建整个网络模块 这里就是依据模块的反复次数 n 以及模块自身和它的参数来构建这个模块和参数对应的 Module
        m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module
        # 获取模块 (module type) 具体名例如 models.common.Conv , models.common.C3 , models.common.SPPF 等。t = str(m)[8:-2].replace('__main__.', '')  #  replace 函数作用是字符串"__main__"替换为'',在以后我的项目没有用到这个替换。np = sum(x.numel() for x in m_.parameters())  # number params
        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # attach index, 'from' index, type, number params
        LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f}  {t:<40}{str(args):<30}')  # print
        """
        如果 x 不是 -1,则将其保留在 save 列表中,示意该层须要保留特色图。这里 x % i 与 x 等价例如在最初一层 : 
        f = [17,20,23] , i = 24 
        y = [x % i for x in ([f] if isinstance(f, int) else f) if x != -1 ]
        print(y) # [17, 20, 23] 
        # 写成 x % i 可能因为:i - 1 = -1 % i (比方 f = [-1],则 [x % i for x in f] 代表 [11] )
        """
        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist
        layers.append(m_)
        if i == 0: # 如果是首次迭代,则新创建一个 ch(因为形参 ch 在创立第一个网络模块时须要用到,所以创立网络模块之后再初始化 ch)ch = []
        ch.append(c2)
    # 将所有的层封装为 nn.Sequential , 对保留的特色图排序
    return nn.Sequential(*layers), sorted(save) 

8

Model 类解读

class Model(nn.Module):
    # YOLOv5 model
    def __init__(self, cfg='[yolov5s.yaml](https://github.com/Oneflow-Inc/one-yolov5/blob/main/models/yolov5s.yaml)', ch=3, nc=None, anchors=None):  # model, input channels, number of classes
        super().__init__()
        # 如果 cfg 曾经是字典,则间接赋值,否则先加载 cfg 门路的文件为字典并赋值给 self.yaml。if isinstance(cfg, dict): 
            self.yaml = cfg  # model dict
        else:  # is *.yaml  加载 yaml 模块
            import yaml  # for flow hub 
            self.yaml_file = Path(cfg).name
            with open(cfg, encoding='ascii', errors='ignore') as f:
                self.yaml = yaml.safe_load(f)  # model dict  从 yaml 文件中加载出字典

        # Define model
        # ch: 输出通道数。如果 self.yaml 有键‘ch’,则将该键对应的值赋给外部变量 ch。如果没有‘ch’,则将形参 ch 赋给外部变量 ch
        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels
        # 如果 yaml 中的 nc 和办法形参中的 nc 不统一,则笼罩 yaml 中的 nc。if nc and nc != self.yaml['nc']:
            LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
            self.yaml['nc'] = nc  # override yaml value
        if anchors: # anchors  先验框的配置
            LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
            self.yaml['anchors'] = round(anchors)  # override yaml value
        # 失去模型,以及对应的保留的特色图列表。self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])  # model, savelist
        self.names = [str(i) for i in range(self.yaml['nc'])]  # default names 初始化类名列表,默认为[0,1,2...]
        
        # self.inplace=True  默认 True  节俭内存
        self.inplace = self.yaml.get('inplace', True)

        # Build strides, anchors  确定步长、步长对应的锚框
        m = self.model[-1]  # Detect()
        if isinstance(m, Detect): # 测验模型的最初一层是 Detect 模块
            s = 256  # 2x min stride
            m.inplace = self.inplace
            # 计算三个 feature map 下采样的倍率  [8, 16, 32]
            m.stride = flow.tensor([s / x.shape[-2] for x in self.forward(flow.zeros(1, ch, s, s))])  # forward
            # 查看 anchor 程序与 stride 程序是否统一 anchor 的程序应该是从小到大,这里排一下序
            check_anchor_order(m)  # must be in pixel-space (not grid-space)
            # 对应的 anchor 进行缩放操作,起因:失去 anchor 在理论的特色图中的地位,因为加载的原始 anchor 大小是绝对于原图的像素,然而通过卷积池化之后,特色图的长宽变小了。m.anchors /= m.stride.view(-1, 1, 1)
            self.stride = m.stride
            self._initialize_biases() # only run once  初始化偏置 

        # Init weights, biases
        # 调用 oneflow_utils.py 下 initialize_weights 初始化模型权重
        initialize_weights(self)
        self.info() # 打印模型信息
        LOGGER.info('')
    # 治理前向流传函数
    def forward(self, x, augment=False, profile=False, visualize=False):
        if augment:# 是否在测试时也应用数据加强  Test Time Augmentation(TTA)
            return self._forward_augment(x)  # augmented inference, None
        return self._forward_once(x, profile, visualize)  # single-scale inference, train
    # 带数据加强的前向流传
    def _forward_augment(self, x):
        img_size = x.shape[-2:]  # height, width
        s = [1, 0.83, 0.67]  # scales
        f = [None, 3, None]  # flips (2-ud, 3-lr)
        y = []  # outputs
        for si, fi in zip(s, f):
            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
            yi = self._forward_once(xi)[0]  # forward
            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save
            yi = self._descale_pred(yi, fi, si, img_size)
            y.append(yi)
        y = self._clip_augmented(y)  # clip augmented tails
        return flow.cat(y, 1), None  # augmented inference, train
    # 前向流传具体实现
    def _forward_once(self, x, profile=False, visualize=False):
        """
        @params x: 输出图像
        @params profile: True 能够做一些性能评估
        @params feature_vis: True 能够做一些特色可视化
        """
        # y: 寄存着 self.save=True 的每一层的输入,因为前面的特色交融操作要用到这些特色图
        y, dt = [], []  # outputs
        # 前向推理每一层构造   m.i=index   m.f=from   m.type= 类名   m.np=number of params
        for m in self.model:
            # if not from previous layer   m.f= 以后层的输出来自哪一层的输入  s 的 m.f 都是 -1
            if m.f != -1:  # if not from previous layer
                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers
            if profile:
                self._profile_one_layer(m, x, dt)
            x = m(x)  # run
            y.append(x if m.i in self.save else None)  # save output
            if visualize:
                feature_visualization(x, m.type, m.i, save_dir=visualize)
        return x
    # 将推理后果复原到原图图片尺寸(逆操作)
    def _descale_pred(self, p, flips, scale, img_size):
        # de-scale predictions following augmented inference (inverse operation)
        """ 用在下面的__init__函数上
        将推理后果复原到原图图片尺寸  Test Time Augmentation(TTA)中用到
         de-scale predictions following augmented inference (inverse operation)
        @params p: 推理后果
        @params flips:
        @params scale:
        @params img_size:
        """
        if self.inplace:
            p[..., :4] /= scale  # de-scale
            if flips == 2:
                p[..., 1] = img_size[0] - p[..., 1]  # de-flip ud
            elif flips == 3:
                p[..., 0] = img_size[1] - p[..., 0]  # de-flip lr
        else:
            x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale  # de-scale
            if flips == 2:
                y = img_size[0] - y  # de-flip ud
            elif flips == 3:
                x = img_size[1] - x  # de-flip lr
            p = flow.cat((x, y, wh, p[..., 4:]), -1)
        return p
    # 这个是 TTA 的时候对原图片进行裁剪,也是一种数据加强形式,用在 TTA 测试的时候。def _clip_augmented(self, y):
        # Clip YOLOv5 augmented inference tails
        nl = self.model[-1].nl  # number of detection layers (P3-P5)
        g = sum(4 ** x for x in range(nl))  # grid points
        e = 1  # exclude layer count
        i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e))  # indices
        y[0] = y[0][:, :-i]  # large
        i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices
        y[-1] = y[-1][:, i:]  # small
        return y
    # 打印日志信息  前向推理工夫
    def _profile_one_layer(self, m, x, dt):
        c = isinstance(m, Detect)  # is final layer, copy input as inplace fix
        o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs
        t = time_sync()
        for _ in range(10):
            m(x.copy() if c else x)
        dt.append((time_sync() - t) * 100)
        if m == self.model[0]:
            LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  module")
        LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')
        if c:
            LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total")
    # initialize biases into Detect(), cf is class frequency
    def _initialize_biases(self, cf=None): 
        # https://arxiv.org/abs/1708.02002 section 3.3
        # cf = flow.bincount(flow.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
        m = self.model[-1]  # Detect() module
        for mi, s in zip(m.m, m.stride):  # from
            b = mi.bias.view(m.na, -1).detach()  # conv.bias(255) to (3,85)
            b[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
            b[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else flow.log(cf / cf.sum())  # cls
            mi.bias = flow.nn.Parameter(b.view(-1), requires_grad=True)
    #  打印模型中最初 Detect 层的偏置 biases 信息(也能够任选哪些层 biases 信息)
    def _print_biases(self):
        """打印模型中最初 Detect 模块外面的卷积层的偏置 biases 信息(也能够任选哪些层 biases 信息)"""
        m = self.model[-1]  # Detect() module
        for mi in m.m:  # from
            b = mi.bias.detach().view(m.na, -1).T  # conv.bias(255) to (3,85)
            LOGGER.info(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))

    def _print_weights(self):
        """打印模型中 Bottleneck 层的权重参数 weights 信息(也能够任选哪些层 weights 信息)"""
        for m in self.model.modules():
            if type(m) is Bottleneck:
                LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2))  # shortcut weights
    
    # fuse()是用来进行 conv 和 bn 层合并,为了提速模型推理速度。def fuse(self):  # fuse model Conv2d() + BatchNorm2d() layers
        """ 用在 detect.py、val.py
        fuse model Conv2d() + BatchNorm2d() layers
        调用 oneflow_utils.py 中的 fuse_conv_and_bn 函数和 common.py 中 Conv 模块的 fuseforward 函数
        """LOGGER.info('Fusing layers... ')
        for m in self.model.modules():
            # 如果以后层是卷积层 Conv 且有 bn 构造, 那么就调用 fuse_conv_and_bn 函数讲 conv 和 bn 进行交融, 减速推理
            if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
                m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv
                delattr(m, 'bn')  # remove batchnorm  移除 bn remove batchnorm
                m.forward = m.forward_fuse  # update forward 更新前向流传 update forward (反向流传不必管, 因为这种推理只用在推理阶段)
        self.info()  # 打印 conv+bn 交融后的模型信息
        return self
    # 打印模型构造信息 在以后类__init__函数结尾处有调用
    def info(self, verbose=False, img_size=640):  # print model information
        model_info(self, verbose, img_size)

    def _apply(self, fn):
        # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
        self = super()._apply(fn)
        m = self.model[-1]  # Detect()
        if isinstance(m, Detect):
            m.stride = fn(m.stride)
            m.grid = list(map(fn, m.grid))
            if isinstance(m.anchor_grid, list):
                m.anchor_grid = list(map(fn, m.anchor_grid))
        return self

9

Detect 类解读

class Detect(nn.Module):
    """Detect 模块是用来构建 Detect 层的,将输出 feature map 通过一个卷积操作和公式计算到咱们想要的 shape, 为前面的计算损失或者 NMS 后处理作筹备"""
    stride = None  # strides computed during build
    onnx_dynamic = False  # ONNX export parameter
    export = False  # export mode

    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # detection layer
        super().__init__()
        #  nc: 分类数量
        self.nc = nc  # number of classes  
        #  no: 每个 anchor 的输入数
        self.no = nc + 5  # number of outputs per anchor
        # nl: 预测层数,此次为 3
        self.nl = len(anchors)  # number of detection layers
        #  na:anchors 的数量,此次为 3
        self.na = len(anchors[0]) // 2  # number of anchors
        #  grid: 格子坐标系,左上角为(1,1), 右下角为(input.w/stride,input.h/stride)
        self.grid = [flow.zeros(1)] * self.nl  # init grid
        self.anchor_grid = [flow.zeros(1)] * self.nl  # init anchor grid
        # 写入缓存中,并命名为 anchors
        self.register_buffer('anchors', flow.tensor(anchors).float().view(self.nl, -1, 2))  # shape(nl,na,2)
        # 将输入通过卷积到 self.no * self.na 的通道,达到全连贯的作用
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv
        self.inplace = inplace  # use inplace 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.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
                    # 向前流传时须要将绝对坐标转换到 grid 相对坐标系中
                    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 + 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, wh, conf = y.split((2, 2, self.nc + 1), 4)  # y.tensor_split((2, 4, 5), 4)  
                    xy = (xy * 2 + self.grid[i]) * self.stride[i]  # xy
                    wh = (wh * 2) ** 2 * self.anchor_grid[i]  # wh
                    y = flow.cat((xy, wh, conf), 4)
                z.append(y.view(bs, -1, self.no))

        return x if self.training else (flow.cat(z, 1),) if self.export else (flow.cat(z, 1), x)
    
    # 绝对坐标转换到 grid 相对坐标系
    def _make_grid(self, nx=20, ny=20, i=0):
        d = self.anchors[i].device
        t = self.anchors[i].dtype
        shape = 1, self.na, ny, nx, 2  # grid shape
        y, x = flow.arange(ny, device=d, dtype=t), flow.arange(nx, device=d, dtype=t)
       
        yv, xv = flow.meshgrid(y, x, indexing="ij")
        grid = flow.stack((xv, yv), 2).expand(shape) - 0.5  # add grid offset, i.e. y = 2.0 * x - 0.5
        anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
        return grid, anchor_grid

10

附件

表 2.1 yolov5s.yaml 解析表
(https://github.com/Oneflow-In…)

11

参考文章

  • https://zhuanlan.zhihu.com/p/…
  • https://zhuanlan.zhihu.com/p/…
  • https://www.it610.com/article…

欢送 Star、试用 OneFlow 最新版本:https://github.com/Oneflow-In…

正文完
 0