天天看點

【YOLOV5-5.x 源碼解讀】yolo.py前言0、導入需要的包和基本配置1、parse_model2、Detect3、Model總結

目錄

  • 前言
  • 0、導入需要的包和基本配置
  • 1、parse_model
  • 2、Detect
  • 3、Model
  • 總結

前言

源碼: YOLOv5源碼.

導航: 【YOLOV5-5.x 源碼講解】整體項目檔案導航.

注釋版全部項目檔案已上傳至GitHub: yolov5-5.x-annotations.

\qquad 這個子產品是yolov5的模型搭模組化塊,非常的重要,不過代碼量并不大,不是很難,隻是yolov5的作者把封裝的太好了,模型擴充了很多的額外的功能,導緻看起來很難,其實真正有用的代碼不多的。重點是抓住三個函數是在哪裡調用的,誰調用誰的,了解這個應該就不會很難。

0、導入需要的包和基本配置

import argparse            # 解析指令行參數子產品
import logging             # 日志子產品
import sys                 # sys系統子產品 包含了與Python解釋器和它的環境有關的函數
from copy import deepcopy  # 資料拷貝子產品 深拷貝
from pathlib import Path   # Path将str轉換為Path對象 使字元串路徑易于操作的子產品

FILE = Path(__file__).absolute()  # FILE = WindowsPath 'F:\yolo_v5\yolov5-U\modles\yolo.py'
# 将'F:/yolo_v5/yolov5-U'加入系統的環境變量  該腳本結束後失效
sys.path.append(FILE.parents[1].as_posix())  # add yolov5/ to path

from models.common import *
from models.experimental import *
from utils.autoanchor import check_anchor_order
from utils.general import make_divisible, check_file, set_logging
from utils.plots import feature_visualization
from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, \
                              scale_img, initialize_weights, select_device, copy_attr

# 導入thop包 用于計算FLOPs
try:
    import thop  # for FLOPs computation
except ImportError:
    thop = None
# 初始化日志
logger = logging.getLogger(__name__)
           

1、parse_model

\qquad parse_model子產品用來解析模型檔案(從Model中傳來的字典形式),并搭建網絡結構。

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中的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('\n%3s%18s%3s%10s  %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
    # 讀取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
    # no: number of outputs 每一個predict head層的輸出channel = anchors * (classes + 5) = 75(VOC)
    no = na * (nc + 5)

    # 開始搭建網絡
    # layers: 儲存每一層的層結構
    # save: 記錄下所有層結構中from中不是-1的層結構序号
    # c2: 儲存目前層的輸出channel
    layers, save, c2 = [], [], ch[-1]
    # from(目前層輸入來自哪些層), number(目前層次數 初定), module(目前層類别), args(目前層類參數 初定)
    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # 周遊backbone和head的每一層
        # eval(string) 得到目前層的真實類名 例如: m= Focus -> <class 'models.common.Focus'>
        m = eval(m) if isinstance(m, str) else m

        # 沒什麼用
        for j, a in enumerate(args):
            try:
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings
            except:
                pass
        # ------------------- 更新目前層的args(參數),計算c2(目前層的輸出channel) -------------------
        # depth gain 控制深度  如v5s: n*0.33   n: 目前子產品的次數(間接控制深度)
        n = max(round(n * gd), 1) if n > 1 else n
        if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d,
                 Focus, CrossConv, BottleneckCSP, C3, C3TR, CBAM]:
            # c1: 目前層的輸入的channel數  c2: 目前層的輸出的channel數(初定)  ch: 記錄着所有層的輸出channel
            c1, c2 = ch[f], args[0]
            # if not output  no=75  隻有最後一層c2=no  最後一層不用控制寬度,輸出channel必須是no
            if c2 != no:
                # width gain 控制寬度  如v5s: c2*0.5  c2: 目前層的最終輸出的channel數(間接控制寬度)
                c2 = make_divisible(c2 * gw, 8)

            # 在初始arg的基礎上更新 加入目前層的輸入channel并更新目前層
            # [in_channel, out_channel, *args[1:]]
            args = [c1, c2, *args[1:]]
            # 如果目前層是BottleneckCSP/C3/C3TR, 則需要在args中加入bottleneck的個數
            # [in_channel, out_channel, Bottleneck的個數n, bool(True表示有shortcut 預設,反之無)]
            if m in [BottleneckCSP, C3, C3TR]:
                args.insert(2, n)  # 在第二個位置插入bottleneck個數n
                n = 1  # 恢複預設值1
        elif m is nn.BatchNorm2d:
            # BN層隻需要傳回上一層的輸出channel
            args = [ch[f]]
        elif m is Concat:
            # Concat層則将f中所有的輸出累加得到這層的輸出channel
            c2 = sum([ch[x] for x in f])
        elif m is Detect:  # Detect(YOLO Layer)層
            # 在args中加入三個Detect層的輸出channel
            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
        elif m is SELayer:  # 加入SE子產品
            channel, re = args[0], args[1]
            channel = make_divisible(channel * gw, 8) if channel != no else channel
            args = [channel, re]
        else:
            # Upsample
            c2 = ch[f]  # args不變
        # -----------------------------------------------------------------------------------

        # m_: 得到目前層module  如果n>1就建立多個m(目前層結構), 如果n=1就建立一個m
        m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args)

        # 列印目前層結構的一些基本資訊
        t = str(m)[8:-2].replace('__main__.', '')  # t = module type   'modules.common.Focus'
        np = sum([x.numel() for x in m_.parameters()])  # number params  計算這一層的參數量
        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # index, 'from' index, number, type, number params
        logger.info('%3s%18s%3s%10.0f  %-40s%-30s' % (i, f, n, np, t, args))  # print

        # append to savelist  把所有層結構中from不是-1的值記下  [6, 4, 14, 10, 17, 20, 23]
        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)

        # 将目前層結構module加入layers中
        layers.append(m_)

        if i == 0:
            ch = []  # 去除輸入channel [3]

        # 把目前層的輸出channel數加入ch
        ch.append(c2)

    return nn.Sequential(*layers), sorted(save)
           

在Model子產品的__init__函數中調用:

【YOLOV5-5.x 源碼解讀】yolo.py前言0、導入需要的包和基本配置1、parse_model2、Detect3、Model總結

2、Detect

\qquad Detect子產品是用來建構Detect層的,将輸入feature map 通過一個卷積操作和公式計算到我們想要的shape,為後面的計算損失或者NMS作準備。

Detect子產品代碼:

class Detect(nn.Module):
    """Detect子產品是用來建構Detect層的,将輸入feature map 通過一個卷積操作和公式計算到我們想要的shape, 為後面的計算損失或者NMS作準備"""
    stride = None  # strides computed during build
    onnx_dynamic = False  # ONNX export parameter

    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):
        """
        detection layer 相當于yolov3中的YOLOLayer層
        :params nc: number of classes
        :params anchors: 傳入3個feature map上的所有anchor的大小(P3、P4、P5)
        :params ch: [128, 256, 512] 3個輸出feature map的channel
        """
        super(Detect, self).__init__()
        self.nc = nc  # number of classes VOC: 20
        self.no = nc + 5  # number of outputs per anchor  VOC: 5+20=25  xywhc+20classes
        self.nl = len(anchors)  # number of detection layers   Detect的個數 3
        self.na = len(anchors[0]) // 2  # number of anchors  每個feature map的anchor個數 3
        self.grid = [torch.zeros(1)] * self.nl  # init grid  {list: 3}  tensor([0.]) X 3
        # a=[3, 3, 2]  anchors以[w, h]對的形式存儲  3個feature map 每個feature map上有三個anchor(w,h)
        a = torch.tensor(anchors).float().view(self.nl, -1, 2)
        # register_buffer
        # 模型中需要儲存的參數一般有兩種:一種是反向傳播需要被optimizer更新的,稱為parameter; 另一種不要被更新稱為buffer
        # buffer的參數更新是在forward中,而optim.step隻能更新nn.parameter類型的參數
        # shape(nl,na,2)
        self.register_buffer('anchors', a)
        # shape(nl,1,na,1,1,2)
        self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2))
        # output conv 對每個輸出的feature map都要調用一次conv1x1
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)
        # use in-place ops (e.g. slice assignment) 一般都是True 預設不使用AWS Inferentia加速
        self.inplace = inplace

    def forward(self, x):
        """
        :return train: 一個tensor list 存放三個元素   [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                       分别是 [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
                inference: 0 [1, 19200+4800+1200, 25] = [bs, anchor_num*grid_w*grid_h, xywh+c+20classes]
                           1 一個tensor list 存放三個元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                             [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
        """
        # x = x.copy()  # for profiling
        z = []  # inference output
        for i in range(self.nl):  # 對三個feature map分别進行處理
            x[i] = self.m[i](x[i])  # conv  xi[bs, 128/256/512, 80, 80] to [bs, 75, 80, 80]
            bs, _, ny, nx = x[i].shape
            # [bs, 75, 80, 80] to [1, 3, 25, 80, 80] to [1, 3, 80, 80, 25]
            x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()

            # inference
            if not self.training:
                # 構造網格
                # 因為推理傳回的不是歸一化後的網格偏移量 需要再加上網格的位置 得到最終的推理坐标 再送入nms
                # 是以這裡建構網格就是為了紀律每個grid的網格坐标 方面後面使用
                if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:
                    self.grid[i] = self._make_grid(nx, ny).to(x[i].device)

                y = x[i].sigmoid()
                if self.inplace:
                    # 預設執行 不使用AWS Inferentia
                    # 這裡的公式和yolov3、v4中使用的不一樣 是yolov5作者自己用的 效果更好
                    y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # xy
                    # y[..., 2:4] = torch.exp(y[..., 2:4]) * self.anchor_wh     # wh yolo method
                    y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh power method
                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].view(1, self.na, 1, 1, 2) # wh
                    y = torch.cat((xy, wh, y[..., 4:]), -1)
                # z是一個tensor list 三個元素 分别是[1, 19200, 25] [1, 4800, 25] [1, 1200, 25]
                z.append(y.view(bs, -1, self.no))

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

    @staticmethod
    def _make_grid(nx=20, ny=20):
        """
        構造網格
        """
        yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
        return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
           

__init__函數在parse_model函數中調用:

【YOLOV5-5.x 源碼解讀】yolo.py前言0、導入需要的包和基本配置1、parse_model2、Detect3、Model總結
【YOLOV5-5.x 源碼解讀】yolo.py前言0、導入需要的包和基本配置1、parse_model2、Detect3、Model總結

forward函數在Model類的forward_once中調用:

【YOLOV5-5.x 源碼解讀】yolo.py前言0、導入需要的包和基本配置1、parse_model2、Detect3、Model總結

3、Model

\qquad 這個子產品是整個模型的搭模組化塊。且yolov5的作者将這個子產品的功能寫的很全,不光包含模型的搭建,還擴充了很多功能如:特征可視化,列印模型資訊、TTA推理增強、融合Conv+Bn加速推理、模型搭載nms功能、autoshape函數:模型包含前處理、推理、後處理的子產品(預處理 + 推理 + nms)。感興趣的可以仔細看看,不感興趣的可以直接看__init__和__forward__兩個函數即可。

Model子產品代碼:

class Model(nn.Module):
    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None):
        """
        :params cfg:模型配置檔案
        :params ch: input img channels 一般是3 RGB檔案
        :params nc: number of classes 資料集的類别個數
        :anchors: 一般是None
        """
        super(Model, self).__init__()
        if isinstance(cfg, dict):
            self.yaml = cfg  # model dict
        else:
            # is *.yaml  一般執行這裡
            import yaml  # for torch hub
            self.yaml_file = Path(cfg).name  # cfg file name = yolov5s.yaml
            # 如果配置檔案中有中文,打開時要加encoding參數
            with open(cfg, encoding='utf-8') as f:
                # model dict  取到配置檔案中每條的資訊(沒有注釋内容)
                self.yaml = yaml.safe_load(f)

        # input channels  ch=3
        ch = self.yaml['ch'] = self.yaml.get('ch', ch)
        # 設定類别數 一般不執行, 因為nc=self.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
        # 重寫anchor,一般不執行, 因為傳進來的anchors一般都是None
        if anchors:
            logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
            self.yaml['anchors'] = round(anchors)  # override yaml value

        # 建立網絡模型
        # self.model: 初始化的整個網絡模型(包括Detect層結構)
        # self.save: 所有層結構中from不等于-1的序号,并排好序  [4, 6, 10, 14, 17, 20, 23]
        self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])

        # default class names ['0', '1', '2',..., '19']
        self.names = [str(i) for i in range(self.yaml['nc'])]

        # self.inplace=True  預設True  不使用加速推理
        # AWS Inferentia Inplace compatiability
        # https://github.com/ultralytics/yolov5/pull/2953
        self.inplace = self.yaml.get('inplace', True)
        # logger.info([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])

        # 擷取Detect子產品的stride(相對輸入圖像的下采樣率)和anchors在目前Detect輸出的feature map的尺度
        m = self.model[-1]  # Detect()
        if isinstance(m, Detect):
            s = 256  # 2x min stride
            m.inplace = self.inplace
            # 計算三個feature map下采樣的倍率  [8, 16, 32]
            m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))])  # forward
            # 求出相對目前feature map的anchor大小 如[10, 13]/8 -> [1.25, 1.625]
            m.anchors /= m.stride.view(-1, 1, 1)
            # 檢查anchor順序與stride順序是否一緻
            check_anchor_order(m)
            self.stride = m.stride
            self._initialize_biases()  # only run once 初始化偏置
            # logger.info('Strides: %s' % m.stride.tolist())

        # Init weights, biases
        initialize_weights(self)  # 調用torch_utils.py下initialize_weights初始化模型權重
        self.info()  # 列印模型資訊
        logger.info('')

    def forward(self, x, augment=False, profile=False):
        # augmented inference, None  上下flip/左右flip
        # 是否在測試時也使用資料增強  Test Time Augmentation(TTA)
        if augment:
            return self.forward_augment(x)
        else:
            # 預設執行 正常前向推理
            # single-scale inference, train
            return self.forward_once(x, profile)

    def forward_augment(self, x):
        """
        TTA Test Time Augmentation
        """
        img_size = x.shape[-2:]  # height, width
        s = [1, 0.83, 0.67]  # scales ratio
        f = [None, 3, None]  # flips (2-ud上下flip, 3-lr左右flip)
        y = []  # outputs
        for si, fi in zip(s, f):
            # scale_img縮放圖檔尺寸
            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
            # _descale_pred将推理結果恢複到相對原圖圖檔尺寸
            yi = self._descale_pred(yi, fi, si, img_size)
            y.append(yi)
        return torch.cat(y, 1), None  # augmented inference, train

    def forward_once(self, x, profile=False, feature_vis=False):
        """
        :params x: 輸入圖像
        :params profile: True 可以做一些性能評估
        :params feature_vis: True 可以做一些特征可視化
        :return train: 一個tensor list 存放三個元素   [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                       分别是 [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
                inference: 0 [1, 19200+4800+1200, 25] = [bs, anchor_num*grid_w*grid_h, xywh+c+20classes]
                           1 一個tensor list 存放三個元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                             [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
        """
        # y: 存放着self.save=True的每一層的輸出,因為後面的層結構concat等操作要用到
        # dt: 在profile中做性能評估時使用
        y, dt = [], []
        for m in self.model:
            # 前向推理每一層結構   m.i=index   m.f=from   m.type=類名   m.np=number of params
            # if not from previous layer   m.f=目前層的輸入來自哪一層的輸出  s的m.f都是-1
            if m.f != -1:
                # 這裡需要做4個concat操作和1個Detect操作
                # concat操作如m.f=[-1, 6] x就有兩個元素,一個是上一層的輸出,另一個是index=6的層的輸出 再送到x=m(x)做concat操作
                # Detect操作m.f=[17, 20, 23] x有三個元素,分别存放第17層第20層第23層的輸出 再送到x=m(x)做Detect的forward
                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

            # 列印日志資訊  FLOPs time等
            if profile:
                o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs
                t = time_synchronized()
                for _ in range(10):
                    _ = m(x)
                dt.append((time_synchronized() - 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}')

            x = m(x)  # run正向推理  執行每一層的forward函數(除Concat和Detect操作)

            # 存放着self.save的每一層的輸出,因為後面需要用來作concat等操作要用到  不在self.save層的輸出就為None
            y.append(x if m.i in self.save else None)

            # 特征可視化 可以自己改動想要哪層的特征進行可視化
            if feature_vis and m.type == 'models.common.SPP':
                feature_visualization(x, m.type, m.i)

        # 列印日志資訊  前向推理時間
        if profile:
            logger.info('%.1fms total' % sum(dt))
        return x

    def _initialize_biases(self, cf=None):
        """用在上面的__init__函數上
        initialize biases into Detect(), cf is class frequency
        https://arxiv.org/abs/1708.02002 section 3.3
        """
        # cf = torch.bincount(torch.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)  # conv.bias(255) to (3,85)
            b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
            b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum())  # cls
            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)

    def info(self, verbose=False, img_size=640):  # print model information
        """用在上面的__init__函數上
        調用torch_utils.py下model_info函數列印模型資訊
        """
        model_info(self, verbose, img_size)

    def _descale_pred(self, p, flips, scale, img_size):
        """用在上面的__init__函數上
        将推理結果恢複到原圖圖檔尺寸  Test Time Augmentation(TTA)中用到
        de-scale predictions following augmented inference (inverse operation)
        :params p: 推理結果
        :params flips:
        :params scale:
        :params img_size:
        """
        # 不同的方式前向推理使用公式不同 具體可看Detect函數
        if self.inplace:  # 預設執行 不使用AWS Inferentia
            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 = torch.cat((x, y, wh, p[..., 4:]), -1)
        return p

    def _print_biases(self):
        """
        列印模型中最後Detect層的偏置bias資訊(也可以任選哪些層bias資訊)
        """
        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

    def fuse(self):
        """用在detect.py、val.py
        fuse model Conv2d() + BatchNorm2d() layers
        調用torch_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 type(m) is Conv and hasattr(m, 'bn'):
                m.conv = fuse_conv_and_bn(m.conv, m.bn)  # 融合 update conv
                delattr(m, 'bn')  # 移除bn remove batchnorm
                m.forward = m.fuseforward  # 更新前向傳播 update forward (反向傳播不用管, 因為這種推理隻用在推理階段)
        self.info()  # 列印conv+bn融合後的模型資訊
        return self

    def nms(self, mode=True):
        """
        add or remove NMS module
        可以自選是否擴充model 增加模型nms功能  直接調用common.py中的NMS子產品
         一般是用不到的 前向推理結束直接掉用non_max_suppression函數即可
        """
        present = type(self.model[-1]) is NMS  # last layer is NMS
        if mode and not present:
            logger.info('Adding NMS... ')
            m = NMS()  # module
            m.f = -1  # from
            m.i = self.model[-1].i + 1  # index
            self.model.add_module(name='%s' % m.i, module=m)  # add nms module to model
            self.eval()  # nms 開啟模型驗證模式
        elif not mode and present:
            logger.info('Removing NMS... ')
            self.model = self.model[:-1]  # remove nms from model
        return self

    def autoshape(self):
        """
        add AutoShape module  直接調用common.py中的AutoShape子產品  也是一個擴充模型功能的子產品
        """
        logger.info('Adding AutoShape... ')
        # wrap model 擴充模型功能 此時模型包含前處理、推理、後處理的子產品(預處理 + 推理 + nms)
        m = AutoShape(self)
        copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=())  # copy attributes
        return m
           

總結

\qquad 這個檔案我的解釋并不多,主要要解釋的都寫在注釋裡了,我覺得我寫的還是挺明白的,如果有不了解的讨論區裡讨論吧!

– 2021.08.23 2021.08.23

繼續閱讀