Spaces:
Running
Running
Upload 22 files
Browse files- models/__init__.py +1 -0
- models/__pycache__/__init__.cpython-38.pyc +0 -0
- models/__pycache__/common.cpython-38.pyc +0 -0
- models/__pycache__/experimental.cpython-38.pyc +0 -0
- models/__pycache__/yolo.cpython-38.pyc +0 -0
- models/common.py +1200 -0
- models/detect/gelan-c.yaml +80 -0
- models/detect/gelan-e.yaml +121 -0
- models/detect/gelan.yaml +80 -0
- models/detect/yolov7-af.yaml +137 -0
- models/detect/yolov9-c.yaml +124 -0
- models/detect/yolov9-e.yaml +144 -0
- models/detect/yolov9.yaml +117 -0
- models/experimental.py +107 -0
- models/hub/anchors.yaml +59 -0
- models/hub/yolov3-spp.yaml +51 -0
- models/hub/yolov3-tiny.yaml +41 -0
- models/hub/yolov3.yaml +51 -0
- models/panoptic/yolov7-af-pan.yaml +137 -0
- models/segment/yolov7-af-seg.yaml +136 -0
- models/tf.py +596 -0
- models/yolo.py +763 -0
models/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# init
|
models/__pycache__/__init__.cpython-38.pyc
ADDED
Binary file (165 Bytes). View file
|
|
models/__pycache__/common.cpython-38.pyc
ADDED
Binary file (51.5 kB). View file
|
|
models/__pycache__/experimental.cpython-38.pyc
ADDED
Binary file (4.73 kB). View file
|
|
models/__pycache__/yolo.cpython-38.pyc
ADDED
Binary file (33 kB). View file
|
|
models/common.py
ADDED
@@ -0,0 +1,1200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import ast
|
2 |
+
import contextlib
|
3 |
+
import json
|
4 |
+
import math
|
5 |
+
import platform
|
6 |
+
import warnings
|
7 |
+
import zipfile
|
8 |
+
from collections import OrderedDict, namedtuple
|
9 |
+
from copy import copy
|
10 |
+
from pathlib import Path
|
11 |
+
from urllib.parse import urlparse
|
12 |
+
|
13 |
+
from typing import Optional
|
14 |
+
|
15 |
+
import cv2
|
16 |
+
import numpy as np
|
17 |
+
import pandas as pd
|
18 |
+
import requests
|
19 |
+
import torch
|
20 |
+
import torch.nn as nn
|
21 |
+
from IPython.display import display
|
22 |
+
from PIL import Image
|
23 |
+
from torch.cuda import amp
|
24 |
+
|
25 |
+
from utils import TryExcept
|
26 |
+
from utils.dataloaders import exif_transpose, letterbox
|
27 |
+
from utils.general import (LOGGER, ROOT, Profile, check_requirements, check_suffix, check_version, colorstr,
|
28 |
+
increment_path, is_notebook, make_divisible, non_max_suppression, scale_boxes,
|
29 |
+
xywh2xyxy, xyxy2xywh, yaml_load)
|
30 |
+
from utils.plots import Annotator, colors, save_one_box
|
31 |
+
from utils.torch_utils import copy_attr, smart_inference_mode
|
32 |
+
|
33 |
+
|
34 |
+
def autopad(k, p=None, d=1): # kernel, padding, dilation
|
35 |
+
# Pad to 'same' shape outputs
|
36 |
+
if d > 1:
|
37 |
+
k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
|
38 |
+
if p is None:
|
39 |
+
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
40 |
+
return p
|
41 |
+
|
42 |
+
|
43 |
+
class Conv(nn.Module):
|
44 |
+
# Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)
|
45 |
+
default_act = nn.SiLU() # default activation
|
46 |
+
|
47 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
|
48 |
+
super().__init__()
|
49 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
|
50 |
+
self.bn = nn.BatchNorm2d(c2)
|
51 |
+
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
52 |
+
|
53 |
+
def forward(self, x):
|
54 |
+
return self.act(self.bn(self.conv(x)))
|
55 |
+
|
56 |
+
def forward_fuse(self, x):
|
57 |
+
return self.act(self.conv(x))
|
58 |
+
|
59 |
+
|
60 |
+
class AConv(nn.Module):
|
61 |
+
def __init__(self, c1, c2): # ch_in, ch_out, shortcut, kernels, groups, expand
|
62 |
+
super().__init__()
|
63 |
+
self.cv1 = Conv(c1, c2, 3, 2, 1)
|
64 |
+
|
65 |
+
def forward(self, x):
|
66 |
+
x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True)
|
67 |
+
return self.cv1(x)
|
68 |
+
|
69 |
+
|
70 |
+
class ADown(nn.Module):
|
71 |
+
def __init__(self, c1, c2): # ch_in, ch_out, shortcut, kernels, groups, expand
|
72 |
+
super().__init__()
|
73 |
+
self.c = c2 // 2
|
74 |
+
self.cv1 = Conv(c1 // 2, self.c, 3, 2, 1)
|
75 |
+
self.cv2 = Conv(c1 // 2, self.c, 1, 1, 0)
|
76 |
+
|
77 |
+
def forward(self, x):
|
78 |
+
x = torch.nn.functional.avg_pool2d(x, 2, 1, 0, False, True)
|
79 |
+
x1,x2 = x.chunk(2, 1)
|
80 |
+
x1 = self.cv1(x1)
|
81 |
+
x2 = torch.nn.functional.max_pool2d(x2, 3, 2, 1)
|
82 |
+
x2 = self.cv2(x2)
|
83 |
+
return torch.cat((x1, x2), 1)
|
84 |
+
|
85 |
+
|
86 |
+
class RepConvN(nn.Module):
|
87 |
+
"""RepConv is a basic rep-style block, including training and deploy status
|
88 |
+
This code is based on https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py
|
89 |
+
"""
|
90 |
+
default_act = nn.SiLU() # default activation
|
91 |
+
|
92 |
+
def __init__(self, c1, c2, k=3, s=1, p=1, g=1, d=1, act=True, bn=False, deploy=False):
|
93 |
+
super().__init__()
|
94 |
+
assert k == 3 and p == 1
|
95 |
+
self.g = g
|
96 |
+
self.c1 = c1
|
97 |
+
self.c2 = c2
|
98 |
+
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
99 |
+
|
100 |
+
self.bn = None
|
101 |
+
self.conv1 = Conv(c1, c2, k, s, p=p, g=g, act=False)
|
102 |
+
self.conv2 = Conv(c1, c2, 1, s, p=(p - k // 2), g=g, act=False)
|
103 |
+
|
104 |
+
def forward_fuse(self, x):
|
105 |
+
"""Forward process"""
|
106 |
+
return self.act(self.conv(x))
|
107 |
+
|
108 |
+
def forward(self, x):
|
109 |
+
"""Forward process"""
|
110 |
+
id_out = 0 if self.bn is None else self.bn(x)
|
111 |
+
return self.act(self.conv1(x) + self.conv2(x) + id_out)
|
112 |
+
|
113 |
+
def get_equivalent_kernel_bias(self):
|
114 |
+
kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)
|
115 |
+
kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)
|
116 |
+
kernelid, biasid = self._fuse_bn_tensor(self.bn)
|
117 |
+
return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
|
118 |
+
|
119 |
+
def _avg_to_3x3_tensor(self, avgp):
|
120 |
+
channels = self.c1
|
121 |
+
groups = self.g
|
122 |
+
kernel_size = avgp.kernel_size
|
123 |
+
input_dim = channels // groups
|
124 |
+
k = torch.zeros((channels, input_dim, kernel_size, kernel_size))
|
125 |
+
k[np.arange(channels), np.tile(np.arange(input_dim), groups), :, :] = 1.0 / kernel_size ** 2
|
126 |
+
return k
|
127 |
+
|
128 |
+
def _pad_1x1_to_3x3_tensor(self, kernel1x1):
|
129 |
+
if kernel1x1 is None:
|
130 |
+
return 0
|
131 |
+
else:
|
132 |
+
return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
|
133 |
+
|
134 |
+
def _fuse_bn_tensor(self, branch):
|
135 |
+
if branch is None:
|
136 |
+
return 0, 0
|
137 |
+
if isinstance(branch, Conv):
|
138 |
+
kernel = branch.conv.weight
|
139 |
+
running_mean = branch.bn.running_mean
|
140 |
+
running_var = branch.bn.running_var
|
141 |
+
gamma = branch.bn.weight
|
142 |
+
beta = branch.bn.bias
|
143 |
+
eps = branch.bn.eps
|
144 |
+
elif isinstance(branch, nn.BatchNorm2d):
|
145 |
+
if not hasattr(self, 'id_tensor'):
|
146 |
+
input_dim = self.c1 // self.g
|
147 |
+
kernel_value = np.zeros((self.c1, input_dim, 3, 3), dtype=np.float32)
|
148 |
+
for i in range(self.c1):
|
149 |
+
kernel_value[i, i % input_dim, 1, 1] = 1
|
150 |
+
self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
|
151 |
+
kernel = self.id_tensor
|
152 |
+
running_mean = branch.running_mean
|
153 |
+
running_var = branch.running_var
|
154 |
+
gamma = branch.weight
|
155 |
+
beta = branch.bias
|
156 |
+
eps = branch.eps
|
157 |
+
std = (running_var + eps).sqrt()
|
158 |
+
t = (gamma / std).reshape(-1, 1, 1, 1)
|
159 |
+
return kernel * t, beta - running_mean * gamma / std
|
160 |
+
|
161 |
+
def fuse_convs(self):
|
162 |
+
if hasattr(self, 'conv'):
|
163 |
+
return
|
164 |
+
kernel, bias = self.get_equivalent_kernel_bias()
|
165 |
+
self.conv = nn.Conv2d(in_channels=self.conv1.conv.in_channels,
|
166 |
+
out_channels=self.conv1.conv.out_channels,
|
167 |
+
kernel_size=self.conv1.conv.kernel_size,
|
168 |
+
stride=self.conv1.conv.stride,
|
169 |
+
padding=self.conv1.conv.padding,
|
170 |
+
dilation=self.conv1.conv.dilation,
|
171 |
+
groups=self.conv1.conv.groups,
|
172 |
+
bias=True).requires_grad_(False)
|
173 |
+
self.conv.weight.data = kernel
|
174 |
+
self.conv.bias.data = bias
|
175 |
+
for para in self.parameters():
|
176 |
+
para.detach_()
|
177 |
+
self.__delattr__('conv1')
|
178 |
+
self.__delattr__('conv2')
|
179 |
+
if hasattr(self, 'nm'):
|
180 |
+
self.__delattr__('nm')
|
181 |
+
if hasattr(self, 'bn'):
|
182 |
+
self.__delattr__('bn')
|
183 |
+
if hasattr(self, 'id_tensor'):
|
184 |
+
self.__delattr__('id_tensor')
|
185 |
+
|
186 |
+
|
187 |
+
class SP(nn.Module):
|
188 |
+
def __init__(self, k=3, s=1):
|
189 |
+
super(SP, self).__init__()
|
190 |
+
self.m = nn.MaxPool2d(kernel_size=k, stride=s, padding=k // 2)
|
191 |
+
|
192 |
+
def forward(self, x):
|
193 |
+
return self.m(x)
|
194 |
+
|
195 |
+
|
196 |
+
class MP(nn.Module):
|
197 |
+
# Max pooling
|
198 |
+
def __init__(self, k=2):
|
199 |
+
super(MP, self).__init__()
|
200 |
+
self.m = nn.MaxPool2d(kernel_size=k, stride=k)
|
201 |
+
|
202 |
+
def forward(self, x):
|
203 |
+
return self.m(x)
|
204 |
+
|
205 |
+
|
206 |
+
class ConvTranspose(nn.Module):
|
207 |
+
# Convolution transpose 2d layer
|
208 |
+
default_act = nn.SiLU() # default activation
|
209 |
+
|
210 |
+
def __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True):
|
211 |
+
super().__init__()
|
212 |
+
self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn)
|
213 |
+
self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity()
|
214 |
+
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
|
215 |
+
|
216 |
+
def forward(self, x):
|
217 |
+
return self.act(self.bn(self.conv_transpose(x)))
|
218 |
+
|
219 |
+
|
220 |
+
class DWConv(Conv):
|
221 |
+
# Depth-wise convolution
|
222 |
+
def __init__(self, c1, c2, k=1, s=1, d=1, act=True): # ch_in, ch_out, kernel, stride, dilation, activation
|
223 |
+
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)
|
224 |
+
|
225 |
+
|
226 |
+
class DWConvTranspose2d(nn.ConvTranspose2d):
|
227 |
+
# Depth-wise transpose convolution
|
228 |
+
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out
|
229 |
+
super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))
|
230 |
+
|
231 |
+
|
232 |
+
class DFL(nn.Module):
|
233 |
+
# DFL module
|
234 |
+
def __init__(self, c1=17):
|
235 |
+
super().__init__()
|
236 |
+
self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False)
|
237 |
+
self.conv.weight.data[:] = nn.Parameter(torch.arange(c1, dtype=torch.float).view(1, c1, 1, 1)) # / 120.0
|
238 |
+
self.c1 = c1
|
239 |
+
# self.bn = nn.BatchNorm2d(4)
|
240 |
+
|
241 |
+
def forward(self, x):
|
242 |
+
b, c, a = x.shape # batch, channels, anchors
|
243 |
+
return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a)
|
244 |
+
# return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a)
|
245 |
+
|
246 |
+
|
247 |
+
class BottleneckBase(nn.Module):
|
248 |
+
# Standard bottleneck
|
249 |
+
def __init__(self, c1, c2, shortcut=True, g=1, k=(1, 3), e=0.5): # ch_in, ch_out, shortcut, kernels, groups, expand
|
250 |
+
super().__init__()
|
251 |
+
c_ = int(c2 * e) # hidden channels
|
252 |
+
self.cv1 = Conv(c1, c_, k[0], 1)
|
253 |
+
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
|
254 |
+
self.add = shortcut and c1 == c2
|
255 |
+
|
256 |
+
def forward(self, x):
|
257 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
258 |
+
|
259 |
+
|
260 |
+
class RBottleneckBase(nn.Module):
|
261 |
+
# Standard bottleneck
|
262 |
+
def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 1), e=0.5): # ch_in, ch_out, shortcut, kernels, groups, expand
|
263 |
+
super().__init__()
|
264 |
+
c_ = int(c2 * e) # hidden channels
|
265 |
+
self.cv1 = Conv(c1, c_, k[0], 1)
|
266 |
+
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
|
267 |
+
self.add = shortcut and c1 == c2
|
268 |
+
|
269 |
+
def forward(self, x):
|
270 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
271 |
+
|
272 |
+
|
273 |
+
class RepNRBottleneckBase(nn.Module):
|
274 |
+
# Standard bottleneck
|
275 |
+
def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 1), e=0.5): # ch_in, ch_out, shortcut, kernels, groups, expand
|
276 |
+
super().__init__()
|
277 |
+
c_ = int(c2 * e) # hidden channels
|
278 |
+
self.cv1 = RepConvN(c1, c_, k[0], 1)
|
279 |
+
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
|
280 |
+
self.add = shortcut and c1 == c2
|
281 |
+
|
282 |
+
def forward(self, x):
|
283 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
284 |
+
|
285 |
+
|
286 |
+
class Bottleneck(nn.Module):
|
287 |
+
# Standard bottleneck
|
288 |
+
def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5): # ch_in, ch_out, shortcut, kernels, groups, expand
|
289 |
+
super().__init__()
|
290 |
+
c_ = int(c2 * e) # hidden channels
|
291 |
+
self.cv1 = Conv(c1, c_, k[0], 1)
|
292 |
+
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
|
293 |
+
self.add = shortcut and c1 == c2
|
294 |
+
|
295 |
+
def forward(self, x):
|
296 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
297 |
+
|
298 |
+
|
299 |
+
class RepNBottleneck(nn.Module):
|
300 |
+
# Standard bottleneck
|
301 |
+
def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5): # ch_in, ch_out, shortcut, kernels, groups, expand
|
302 |
+
super().__init__()
|
303 |
+
c_ = int(c2 * e) # hidden channels
|
304 |
+
self.cv1 = RepConvN(c1, c_, k[0], 1)
|
305 |
+
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
|
306 |
+
self.add = shortcut and c1 == c2
|
307 |
+
|
308 |
+
def forward(self, x):
|
309 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
310 |
+
|
311 |
+
|
312 |
+
class Res(nn.Module):
|
313 |
+
# ResNet bottleneck
|
314 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
|
315 |
+
super(Res, self).__init__()
|
316 |
+
c_ = int(c2 * e) # hidden channels
|
317 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
318 |
+
self.cv2 = Conv(c_, c_, 3, 1, g=g)
|
319 |
+
self.cv3 = Conv(c_, c2, 1, 1)
|
320 |
+
self.add = shortcut and c1 == c2
|
321 |
+
|
322 |
+
def forward(self, x):
|
323 |
+
return x + self.cv3(self.cv2(self.cv1(x))) if self.add else self.cv3(self.cv2(self.cv1(x)))
|
324 |
+
|
325 |
+
|
326 |
+
class RepNRes(nn.Module):
|
327 |
+
# ResNet bottleneck
|
328 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
|
329 |
+
super(RepNRes, self).__init__()
|
330 |
+
c_ = int(c2 * e) # hidden channels
|
331 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
332 |
+
self.cv2 = RepConvN(c_, c_, 3, 1, g=g)
|
333 |
+
self.cv3 = Conv(c_, c2, 1, 1)
|
334 |
+
self.add = shortcut and c1 == c2
|
335 |
+
|
336 |
+
def forward(self, x):
|
337 |
+
return x + self.cv3(self.cv2(self.cv1(x))) if self.add else self.cv3(self.cv2(self.cv1(x)))
|
338 |
+
|
339 |
+
|
340 |
+
class BottleneckCSP(nn.Module):
|
341 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
342 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
343 |
+
super().__init__()
|
344 |
+
c_ = int(c2 * e) # hidden channels
|
345 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
346 |
+
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
347 |
+
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
348 |
+
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
349 |
+
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
350 |
+
self.act = nn.SiLU()
|
351 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
352 |
+
|
353 |
+
def forward(self, x):
|
354 |
+
y1 = self.cv3(self.m(self.cv1(x)))
|
355 |
+
y2 = self.cv2(x)
|
356 |
+
return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))
|
357 |
+
|
358 |
+
|
359 |
+
class CSP(nn.Module):
|
360 |
+
# CSP Bottleneck with 3 convolutions
|
361 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
362 |
+
super().__init__()
|
363 |
+
c_ = int(c2 * e) # hidden channels
|
364 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
365 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
366 |
+
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
|
367 |
+
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
368 |
+
|
369 |
+
def forward(self, x):
|
370 |
+
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
|
371 |
+
|
372 |
+
|
373 |
+
class RepNCSP(nn.Module):
|
374 |
+
# CSP Bottleneck with 3 convolutions
|
375 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
376 |
+
super().__init__()
|
377 |
+
c_ = int(c2 * e) # hidden channels
|
378 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
379 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
380 |
+
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
|
381 |
+
self.m = nn.Sequential(*(RepNBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
382 |
+
|
383 |
+
def forward(self, x):
|
384 |
+
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
|
385 |
+
|
386 |
+
|
387 |
+
class CSPBase(nn.Module):
|
388 |
+
# CSP Bottleneck with 3 convolutions
|
389 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
390 |
+
super().__init__()
|
391 |
+
c_ = int(c2 * e) # hidden channels
|
392 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
393 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
394 |
+
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
|
395 |
+
self.m = nn.Sequential(*(BottleneckBase(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
|
396 |
+
|
397 |
+
def forward(self, x):
|
398 |
+
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
|
399 |
+
|
400 |
+
|
401 |
+
class SPP(nn.Module):
|
402 |
+
# Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
|
403 |
+
def __init__(self, c1, c2, k=(5, 9, 13)):
|
404 |
+
super().__init__()
|
405 |
+
c_ = c1 // 2 # hidden channels
|
406 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
407 |
+
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
|
408 |
+
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
409 |
+
|
410 |
+
def forward(self, x):
|
411 |
+
x = self.cv1(x)
|
412 |
+
with warnings.catch_warnings():
|
413 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
414 |
+
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
415 |
+
|
416 |
+
|
417 |
+
class ASPP(torch.nn.Module):
|
418 |
+
|
419 |
+
def __init__(self, in_channels, out_channels):
|
420 |
+
super().__init__()
|
421 |
+
kernel_sizes = [1, 3, 3, 1]
|
422 |
+
dilations = [1, 3, 6, 1]
|
423 |
+
paddings = [0, 3, 6, 0]
|
424 |
+
self.aspp = torch.nn.ModuleList()
|
425 |
+
for aspp_idx in range(len(kernel_sizes)):
|
426 |
+
conv = torch.nn.Conv2d(
|
427 |
+
in_channels,
|
428 |
+
out_channels,
|
429 |
+
kernel_size=kernel_sizes[aspp_idx],
|
430 |
+
stride=1,
|
431 |
+
dilation=dilations[aspp_idx],
|
432 |
+
padding=paddings[aspp_idx],
|
433 |
+
bias=True)
|
434 |
+
self.aspp.append(conv)
|
435 |
+
self.gap = torch.nn.AdaptiveAvgPool2d(1)
|
436 |
+
self.aspp_num = len(kernel_sizes)
|
437 |
+
for m in self.modules():
|
438 |
+
if isinstance(m, torch.nn.Conv2d):
|
439 |
+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
440 |
+
m.weight.data.normal_(0, math.sqrt(2. / n))
|
441 |
+
m.bias.data.fill_(0)
|
442 |
+
|
443 |
+
def forward(self, x):
|
444 |
+
avg_x = self.gap(x)
|
445 |
+
out = []
|
446 |
+
for aspp_idx in range(self.aspp_num):
|
447 |
+
inp = avg_x if (aspp_idx == self.aspp_num - 1) else x
|
448 |
+
out.append(F.relu_(self.aspp[aspp_idx](inp)))
|
449 |
+
out[-1] = out[-1].expand_as(out[-2])
|
450 |
+
out = torch.cat(out, dim=1)
|
451 |
+
return out
|
452 |
+
|
453 |
+
|
454 |
+
class SPPCSPC(nn.Module):
|
455 |
+
# CSP SPP https://github.com/WongKinYiu/CrossStagePartialNetworks
|
456 |
+
def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)):
|
457 |
+
super(SPPCSPC, self).__init__()
|
458 |
+
c_ = int(2 * c2 * e) # hidden channels
|
459 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
460 |
+
self.cv2 = Conv(c1, c_, 1, 1)
|
461 |
+
self.cv3 = Conv(c_, c_, 3, 1)
|
462 |
+
self.cv4 = Conv(c_, c_, 1, 1)
|
463 |
+
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
464 |
+
self.cv5 = Conv(4 * c_, c_, 1, 1)
|
465 |
+
self.cv6 = Conv(c_, c_, 3, 1)
|
466 |
+
self.cv7 = Conv(2 * c_, c2, 1, 1)
|
467 |
+
|
468 |
+
def forward(self, x):
|
469 |
+
x1 = self.cv4(self.cv3(self.cv1(x)))
|
470 |
+
y1 = self.cv6(self.cv5(torch.cat([x1] + [m(x1) for m in self.m], 1)))
|
471 |
+
y2 = self.cv2(x)
|
472 |
+
return self.cv7(torch.cat((y1, y2), dim=1))
|
473 |
+
|
474 |
+
|
475 |
+
class SPPF(nn.Module):
|
476 |
+
# Spatial Pyramid Pooling - Fast (SPPF) layer by Glenn Jocher
|
477 |
+
def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
|
478 |
+
super().__init__()
|
479 |
+
c_ = c1 // 2 # hidden channels
|
480 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
481 |
+
self.cv2 = Conv(c_ * 4, c2, 1, 1)
|
482 |
+
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
|
483 |
+
# self.m = SoftPool2d(kernel_size=k, stride=1, padding=k // 2)
|
484 |
+
|
485 |
+
def forward(self, x):
|
486 |
+
x = self.cv1(x)
|
487 |
+
with warnings.catch_warnings():
|
488 |
+
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
|
489 |
+
y1 = self.m(x)
|
490 |
+
y2 = self.m(y1)
|
491 |
+
return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
|
492 |
+
|
493 |
+
|
494 |
+
import torch.nn.functional as F
|
495 |
+
from torch.nn.modules.utils import _pair
|
496 |
+
|
497 |
+
|
498 |
+
class ReOrg(nn.Module):
|
499 |
+
# yolo
|
500 |
+
def __init__(self):
|
501 |
+
super(ReOrg, self).__init__()
|
502 |
+
|
503 |
+
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
|
504 |
+
return torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)
|
505 |
+
|
506 |
+
|
507 |
+
class Contract(nn.Module):
|
508 |
+
# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
|
509 |
+
def __init__(self, gain=2):
|
510 |
+
super().__init__()
|
511 |
+
self.gain = gain
|
512 |
+
|
513 |
+
def forward(self, x):
|
514 |
+
b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
|
515 |
+
s = self.gain
|
516 |
+
x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
|
517 |
+
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
|
518 |
+
return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
|
519 |
+
|
520 |
+
|
521 |
+
class Expand(nn.Module):
|
522 |
+
# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
|
523 |
+
def __init__(self, gain=2):
|
524 |
+
super().__init__()
|
525 |
+
self.gain = gain
|
526 |
+
|
527 |
+
def forward(self, x):
|
528 |
+
b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
|
529 |
+
s = self.gain
|
530 |
+
x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
|
531 |
+
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
|
532 |
+
return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
|
533 |
+
|
534 |
+
|
535 |
+
class Concat(nn.Module):
|
536 |
+
# Concatenate a list of tensors along dimension
|
537 |
+
def __init__(self, dimension=1):
|
538 |
+
super().__init__()
|
539 |
+
self.d = dimension
|
540 |
+
|
541 |
+
def forward(self, x):
|
542 |
+
return torch.cat(x, self.d)
|
543 |
+
|
544 |
+
|
545 |
+
class Shortcut(nn.Module):
|
546 |
+
def __init__(self, dimension=0):
|
547 |
+
super(Shortcut, self).__init__()
|
548 |
+
self.d = dimension
|
549 |
+
|
550 |
+
def forward(self, x):
|
551 |
+
return x[0]+x[1]
|
552 |
+
|
553 |
+
|
554 |
+
class Silence(nn.Module):
|
555 |
+
def __init__(self):
|
556 |
+
super(Silence, self).__init__()
|
557 |
+
def forward(self, x):
|
558 |
+
return x
|
559 |
+
|
560 |
+
|
561 |
+
##### GELAN #####
|
562 |
+
|
563 |
+
class SPPELAN(nn.Module):
|
564 |
+
# spp-elan
|
565 |
+
def __init__(self, c1, c2, c3): # ch_in, ch_out, number, shortcut, groups, expansion
|
566 |
+
super().__init__()
|
567 |
+
self.c = c3
|
568 |
+
self.cv1 = Conv(c1, c3, 1, 1)
|
569 |
+
self.cv2 = SP(5)
|
570 |
+
self.cv3 = SP(5)
|
571 |
+
self.cv4 = SP(5)
|
572 |
+
self.cv5 = Conv(4*c3, c2, 1, 1)
|
573 |
+
|
574 |
+
def forward(self, x):
|
575 |
+
y = [self.cv1(x)]
|
576 |
+
y.extend(m(y[-1]) for m in [self.cv2, self.cv3, self.cv4])
|
577 |
+
return self.cv5(torch.cat(y, 1))
|
578 |
+
|
579 |
+
|
580 |
+
class RepNCSPELAN4(nn.Module):
|
581 |
+
# csp-elan
|
582 |
+
def __init__(self, c1, c2, c3, c4, c5=1): # ch_in, ch_out, number, shortcut, groups, expansion
|
583 |
+
super().__init__()
|
584 |
+
self.c = c3//2
|
585 |
+
self.cv1 = Conv(c1, c3, 1, 1)
|
586 |
+
self.cv2 = nn.Sequential(RepNCSP(c3//2, c4, c5), Conv(c4, c4, 3, 1))
|
587 |
+
self.cv3 = nn.Sequential(RepNCSP(c4, c4, c5), Conv(c4, c4, 3, 1))
|
588 |
+
self.cv4 = Conv(c3+(2*c4), c2, 1, 1)
|
589 |
+
|
590 |
+
def forward(self, x):
|
591 |
+
y = list(self.cv1(x).chunk(2, 1))
|
592 |
+
y.extend((m(y[-1])) for m in [self.cv2, self.cv3])
|
593 |
+
return self.cv4(torch.cat(y, 1))
|
594 |
+
|
595 |
+
def forward_split(self, x):
|
596 |
+
y = list(self.cv1(x).split((self.c, self.c), 1))
|
597 |
+
y.extend(m(y[-1]) for m in [self.cv2, self.cv3])
|
598 |
+
return self.cv4(torch.cat(y, 1))
|
599 |
+
|
600 |
+
#################
|
601 |
+
|
602 |
+
|
603 |
+
##### YOLOR #####
|
604 |
+
|
605 |
+
class ImplicitA(nn.Module):
|
606 |
+
def __init__(self, channel):
|
607 |
+
super(ImplicitA, self).__init__()
|
608 |
+
self.channel = channel
|
609 |
+
self.implicit = nn.Parameter(torch.zeros(1, channel, 1, 1))
|
610 |
+
nn.init.normal_(self.implicit, std=.02)
|
611 |
+
|
612 |
+
def forward(self, x):
|
613 |
+
return self.implicit + x
|
614 |
+
|
615 |
+
|
616 |
+
class ImplicitM(nn.Module):
|
617 |
+
def __init__(self, channel):
|
618 |
+
super(ImplicitM, self).__init__()
|
619 |
+
self.channel = channel
|
620 |
+
self.implicit = nn.Parameter(torch.ones(1, channel, 1, 1))
|
621 |
+
nn.init.normal_(self.implicit, mean=1., std=.02)
|
622 |
+
|
623 |
+
def forward(self, x):
|
624 |
+
return self.implicit * x
|
625 |
+
|
626 |
+
#################
|
627 |
+
|
628 |
+
|
629 |
+
##### CBNet #####
|
630 |
+
|
631 |
+
class CBLinear(nn.Module):
|
632 |
+
def __init__(self, c1, c2s, k=1, s=1, p=None, g=1): # ch_in, ch_outs, kernel, stride, padding, groups
|
633 |
+
super(CBLinear, self).__init__()
|
634 |
+
self.c2s = c2s
|
635 |
+
self.conv = nn.Conv2d(c1, sum(c2s), k, s, autopad(k, p), groups=g, bias=True)
|
636 |
+
|
637 |
+
def forward(self, x):
|
638 |
+
outs = self.conv(x).split(self.c2s, dim=1)
|
639 |
+
return outs
|
640 |
+
|
641 |
+
class CBFuse(nn.Module):
|
642 |
+
def __init__(self, idx):
|
643 |
+
super(CBFuse, self).__init__()
|
644 |
+
self.idx = idx
|
645 |
+
|
646 |
+
def forward(self, xs):
|
647 |
+
target_size = xs[-1].shape[2:]
|
648 |
+
res = [F.interpolate(x[self.idx[i]], size=target_size, mode='nearest') for i, x in enumerate(xs[:-1])]
|
649 |
+
out = torch.sum(torch.stack(res + xs[-1:]), dim=0)
|
650 |
+
return out
|
651 |
+
|
652 |
+
#################
|
653 |
+
|
654 |
+
|
655 |
+
class DetectMultiBackend(nn.Module):
|
656 |
+
# YOLO MultiBackend class for python inference on various backends
|
657 |
+
def __init__(self, weights='yolo.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=True):
|
658 |
+
# Usage:
|
659 |
+
# PyTorch: weights = *.pt
|
660 |
+
# TorchScript: *.torchscript
|
661 |
+
# ONNX Runtime: *.onnx
|
662 |
+
# ONNX OpenCV DNN: *.onnx --dnn
|
663 |
+
# OpenVINO: *_openvino_model
|
664 |
+
# CoreML: *.mlmodel
|
665 |
+
# TensorRT: *.engine
|
666 |
+
# TensorFlow SavedModel: *_saved_model
|
667 |
+
# TensorFlow GraphDef: *.pb
|
668 |
+
# TensorFlow Lite: *.tflite
|
669 |
+
# TensorFlow Edge TPU: *_edgetpu.tflite
|
670 |
+
# PaddlePaddle: *_paddle_model
|
671 |
+
from models.experimental import attempt_download, attempt_load # scoped to avoid circular import
|
672 |
+
|
673 |
+
super().__init__()
|
674 |
+
w = str(weights[0] if isinstance(weights, list) else weights)
|
675 |
+
pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)
|
676 |
+
fp16 &= pt or jit or onnx or engine # FP16
|
677 |
+
nhwc = coreml or saved_model or pb or tflite or edgetpu # BHWC formats (vs torch BCWH)
|
678 |
+
stride = 32 # default stride
|
679 |
+
cuda = torch.cuda.is_available() and device.type != 'cpu' # use CUDA
|
680 |
+
if not (pt or triton):
|
681 |
+
w = attempt_download(w) # download if not local
|
682 |
+
|
683 |
+
if pt: # PyTorch
|
684 |
+
model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
|
685 |
+
stride = max(int(model.stride.max()), 32) # model stride
|
686 |
+
names = model.module.names if hasattr(model, 'module') else model.names # get class names
|
687 |
+
model.half() if fp16 else model.float()
|
688 |
+
self.model = model # explicitly assign for to(), cpu(), cuda(), half()
|
689 |
+
elif jit: # TorchScript
|
690 |
+
LOGGER.info(f'Loading {w} for TorchScript inference...')
|
691 |
+
extra_files = {'config.txt': ''} # model metadata
|
692 |
+
model = torch.jit.load(w, _extra_files=extra_files, map_location=device)
|
693 |
+
model.half() if fp16 else model.float()
|
694 |
+
if extra_files['config.txt']: # load metadata dict
|
695 |
+
d = json.loads(extra_files['config.txt'],
|
696 |
+
object_hook=lambda d: {int(k) if k.isdigit() else k: v
|
697 |
+
for k, v in d.items()})
|
698 |
+
stride, names = int(d['stride']), d['names']
|
699 |
+
elif dnn: # ONNX OpenCV DNN
|
700 |
+
LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')
|
701 |
+
check_requirements('opencv-python>=4.5.4')
|
702 |
+
net = cv2.dnn.readNetFromONNX(w)
|
703 |
+
elif onnx: # ONNX Runtime
|
704 |
+
LOGGER.info(f'Loading {w} for ONNX Runtime inference...')
|
705 |
+
check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))
|
706 |
+
import onnxruntime
|
707 |
+
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']
|
708 |
+
session = onnxruntime.InferenceSession(w, providers=providers)
|
709 |
+
output_names = [x.name for x in session.get_outputs()]
|
710 |
+
meta = session.get_modelmeta().custom_metadata_map # metadata
|
711 |
+
if 'stride' in meta:
|
712 |
+
stride, names = int(meta['stride']), eval(meta['names'])
|
713 |
+
elif xml: # OpenVINO
|
714 |
+
LOGGER.info(f'Loading {w} for OpenVINO inference...')
|
715 |
+
check_requirements('openvino') # requires openvino-dev: https://pypi.org/project/openvino-dev/
|
716 |
+
from openvino.runtime import Core, Layout, get_batch
|
717 |
+
ie = Core()
|
718 |
+
if not Path(w).is_file(): # if not *.xml
|
719 |
+
w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir
|
720 |
+
network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin'))
|
721 |
+
if network.get_parameters()[0].get_layout().empty:
|
722 |
+
network.get_parameters()[0].set_layout(Layout("NCHW"))
|
723 |
+
batch_dim = get_batch(network)
|
724 |
+
if batch_dim.is_static:
|
725 |
+
batch_size = batch_dim.get_length()
|
726 |
+
executable_network = ie.compile_model(network, device_name="CPU") # device_name="MYRIAD" for Intel NCS2
|
727 |
+
stride, names = self._load_metadata(Path(w).with_suffix('.yaml')) # load metadata
|
728 |
+
elif engine: # TensorRT
|
729 |
+
LOGGER.info(f'Loading {w} for TensorRT inference...')
|
730 |
+
import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download
|
731 |
+
check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0
|
732 |
+
if device.type == 'cpu':
|
733 |
+
device = torch.device('cuda:0')
|
734 |
+
Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))
|
735 |
+
logger = trt.Logger(trt.Logger.INFO)
|
736 |
+
with open(w, 'rb') as f, trt.Runtime(logger) as runtime:
|
737 |
+
model = runtime.deserialize_cuda_engine(f.read())
|
738 |
+
context = model.create_execution_context()
|
739 |
+
bindings = OrderedDict()
|
740 |
+
output_names = []
|
741 |
+
fp16 = False # default updated below
|
742 |
+
dynamic = False
|
743 |
+
for i in range(model.num_bindings):
|
744 |
+
name = model.get_binding_name(i)
|
745 |
+
dtype = trt.nptype(model.get_binding_dtype(i))
|
746 |
+
if model.binding_is_input(i):
|
747 |
+
if -1 in tuple(model.get_binding_shape(i)): # dynamic
|
748 |
+
dynamic = True
|
749 |
+
context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))
|
750 |
+
if dtype == np.float16:
|
751 |
+
fp16 = True
|
752 |
+
else: # output
|
753 |
+
output_names.append(name)
|
754 |
+
shape = tuple(context.get_binding_shape(i))
|
755 |
+
im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)
|
756 |
+
bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))
|
757 |
+
binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())
|
758 |
+
batch_size = bindings['images'].shape[0] # if dynamic, this is instead max batch size
|
759 |
+
elif coreml: # CoreML
|
760 |
+
LOGGER.info(f'Loading {w} for CoreML inference...')
|
761 |
+
import coremltools as ct
|
762 |
+
model = ct.models.MLModel(w)
|
763 |
+
elif saved_model: # TF SavedModel
|
764 |
+
LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')
|
765 |
+
import tensorflow as tf
|
766 |
+
keras = False # assume TF1 saved_model
|
767 |
+
model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)
|
768 |
+
elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
|
769 |
+
LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')
|
770 |
+
import tensorflow as tf
|
771 |
+
|
772 |
+
def wrap_frozen_graph(gd, inputs, outputs):
|
773 |
+
x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped
|
774 |
+
ge = x.graph.as_graph_element
|
775 |
+
return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))
|
776 |
+
|
777 |
+
def gd_outputs(gd):
|
778 |
+
name_list, input_list = [], []
|
779 |
+
for node in gd.node: # tensorflow.core.framework.node_def_pb2.NodeDef
|
780 |
+
name_list.append(node.name)
|
781 |
+
input_list.extend(node.input)
|
782 |
+
return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))
|
783 |
+
|
784 |
+
gd = tf.Graph().as_graph_def() # TF GraphDef
|
785 |
+
with open(w, 'rb') as f:
|
786 |
+
gd.ParseFromString(f.read())
|
787 |
+
frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs=gd_outputs(gd))
|
788 |
+
elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python
|
789 |
+
try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu
|
790 |
+
from tflite_runtime.interpreter import Interpreter, load_delegate
|
791 |
+
except ImportError:
|
792 |
+
import tensorflow as tf
|
793 |
+
Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate,
|
794 |
+
if edgetpu: # TF Edge TPU https://coral.ai/software/#edgetpu-runtime
|
795 |
+
LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')
|
796 |
+
delegate = {
|
797 |
+
'Linux': 'libedgetpu.so.1',
|
798 |
+
'Darwin': 'libedgetpu.1.dylib',
|
799 |
+
'Windows': 'edgetpu.dll'}[platform.system()]
|
800 |
+
interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])
|
801 |
+
else: # TFLite
|
802 |
+
LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')
|
803 |
+
interpreter = Interpreter(model_path=w) # load TFLite model
|
804 |
+
interpreter.allocate_tensors() # allocate
|
805 |
+
input_details = interpreter.get_input_details() # inputs
|
806 |
+
output_details = interpreter.get_output_details() # outputs
|
807 |
+
# load metadata
|
808 |
+
with contextlib.suppress(zipfile.BadZipFile):
|
809 |
+
with zipfile.ZipFile(w, "r") as model:
|
810 |
+
meta_file = model.namelist()[0]
|
811 |
+
meta = ast.literal_eval(model.read(meta_file).decode("utf-8"))
|
812 |
+
stride, names = int(meta['stride']), meta['names']
|
813 |
+
elif tfjs: # TF.js
|
814 |
+
raise NotImplementedError('ERROR: YOLO TF.js inference is not supported')
|
815 |
+
elif paddle: # PaddlePaddle
|
816 |
+
LOGGER.info(f'Loading {w} for PaddlePaddle inference...')
|
817 |
+
check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')
|
818 |
+
import paddle.inference as pdi
|
819 |
+
if not Path(w).is_file(): # if not *.pdmodel
|
820 |
+
w = next(Path(w).rglob('*.pdmodel')) # get *.pdmodel file from *_paddle_model dir
|
821 |
+
weights = Path(w).with_suffix('.pdiparams')
|
822 |
+
config = pdi.Config(str(w), str(weights))
|
823 |
+
if cuda:
|
824 |
+
config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)
|
825 |
+
predictor = pdi.create_predictor(config)
|
826 |
+
input_handle = predictor.get_input_handle(predictor.get_input_names()[0])
|
827 |
+
output_names = predictor.get_output_names()
|
828 |
+
elif triton: # NVIDIA Triton Inference Server
|
829 |
+
LOGGER.info(f'Using {w} as Triton Inference Server...')
|
830 |
+
check_requirements('tritonclient[all]')
|
831 |
+
from utils.triton import TritonRemoteModel
|
832 |
+
model = TritonRemoteModel(url=w)
|
833 |
+
nhwc = model.runtime.startswith("tensorflow")
|
834 |
+
else:
|
835 |
+
raise NotImplementedError(f'ERROR: {w} is not a supported format')
|
836 |
+
|
837 |
+
# class names
|
838 |
+
if 'names' not in locals():
|
839 |
+
names = yaml_load(data)['names'] if data else {i: f'class{i}' for i in range(999)}
|
840 |
+
if names[0] == 'n01440764' and len(names) == 1000: # ImageNet
|
841 |
+
names = yaml_load(ROOT / 'data/ImageNet.yaml')['names'] # human-readable names
|
842 |
+
|
843 |
+
self.__dict__.update(locals()) # assign all variables to self
|
844 |
+
|
845 |
+
def forward(self, im, augment=False, visualize=False):
|
846 |
+
# YOLO MultiBackend inference
|
847 |
+
b, ch, h, w = im.shape # batch, channel, height, width
|
848 |
+
if self.fp16 and im.dtype != torch.float16:
|
849 |
+
im = im.half() # to FP16
|
850 |
+
if self.nhwc:
|
851 |
+
im = im.permute(0, 2, 3, 1) # torch BCHW to numpy BHWC shape(1,320,192,3)
|
852 |
+
|
853 |
+
if self.pt: # PyTorch
|
854 |
+
y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)
|
855 |
+
elif self.jit: # TorchScript
|
856 |
+
y = self.model(im)
|
857 |
+
elif self.dnn: # ONNX OpenCV DNN
|
858 |
+
im = im.cpu().numpy() # torch to numpy
|
859 |
+
self.net.setInput(im)
|
860 |
+
y = self.net.forward()
|
861 |
+
elif self.onnx: # ONNX Runtime
|
862 |
+
im = im.cpu().numpy() # torch to numpy
|
863 |
+
y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})
|
864 |
+
elif self.xml: # OpenVINO
|
865 |
+
im = im.cpu().numpy() # FP32
|
866 |
+
y = list(self.executable_network([im]).values())
|
867 |
+
elif self.engine: # TensorRT
|
868 |
+
if self.dynamic and im.shape != self.bindings['images'].shape:
|
869 |
+
i = self.model.get_binding_index('images')
|
870 |
+
self.context.set_binding_shape(i, im.shape) # reshape if dynamic
|
871 |
+
self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)
|
872 |
+
for name in self.output_names:
|
873 |
+
i = self.model.get_binding_index(name)
|
874 |
+
self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))
|
875 |
+
s = self.bindings['images'].shape
|
876 |
+
assert im.shape == s, f"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}"
|
877 |
+
self.binding_addrs['images'] = int(im.data_ptr())
|
878 |
+
self.context.execute_v2(list(self.binding_addrs.values()))
|
879 |
+
y = [self.bindings[x].data for x in sorted(self.output_names)]
|
880 |
+
elif self.coreml: # CoreML
|
881 |
+
im = im.cpu().numpy()
|
882 |
+
im = Image.fromarray((im[0] * 255).astype('uint8'))
|
883 |
+
# im = im.resize((192, 320), Image.ANTIALIAS)
|
884 |
+
y = self.model.predict({'image': im}) # coordinates are xywh normalized
|
885 |
+
if 'confidence' in y:
|
886 |
+
box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels
|
887 |
+
conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)
|
888 |
+
y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)
|
889 |
+
else:
|
890 |
+
y = list(reversed(y.values())) # reversed for segmentation models (pred, proto)
|
891 |
+
elif self.paddle: # PaddlePaddle
|
892 |
+
im = im.cpu().numpy().astype(np.float32)
|
893 |
+
self.input_handle.copy_from_cpu(im)
|
894 |
+
self.predictor.run()
|
895 |
+
y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]
|
896 |
+
elif self.triton: # NVIDIA Triton Inference Server
|
897 |
+
y = self.model(im)
|
898 |
+
else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)
|
899 |
+
im = im.cpu().numpy()
|
900 |
+
if self.saved_model: # SavedModel
|
901 |
+
y = self.model(im, training=False) if self.keras else self.model(im)
|
902 |
+
elif self.pb: # GraphDef
|
903 |
+
y = self.frozen_func(x=self.tf.constant(im))
|
904 |
+
else: # Lite or Edge TPU
|
905 |
+
input = self.input_details[0]
|
906 |
+
int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model
|
907 |
+
if int8:
|
908 |
+
scale, zero_point = input['quantization']
|
909 |
+
im = (im / scale + zero_point).astype(np.uint8) # de-scale
|
910 |
+
self.interpreter.set_tensor(input['index'], im)
|
911 |
+
self.interpreter.invoke()
|
912 |
+
y = []
|
913 |
+
for output in self.output_details:
|
914 |
+
x = self.interpreter.get_tensor(output['index'])
|
915 |
+
if int8:
|
916 |
+
scale, zero_point = output['quantization']
|
917 |
+
x = (x.astype(np.float32) - zero_point) * scale # re-scale
|
918 |
+
y.append(x)
|
919 |
+
y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]
|
920 |
+
y[0][..., :4] *= [w, h, w, h] # xywh normalized to pixels
|
921 |
+
|
922 |
+
if isinstance(y, (list, tuple)):
|
923 |
+
return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]
|
924 |
+
else:
|
925 |
+
return self.from_numpy(y)
|
926 |
+
|
927 |
+
def from_numpy(self, x):
|
928 |
+
return torch.from_numpy(x).to(self.device) if isinstance(x, np.ndarray) else x
|
929 |
+
|
930 |
+
def warmup(self, imgsz=(1, 3, 640, 640)):
|
931 |
+
# Warmup model by running inference once
|
932 |
+
warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton
|
933 |
+
if any(warmup_types) and (self.device.type != 'cpu' or self.triton):
|
934 |
+
im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input
|
935 |
+
for _ in range(2 if self.jit else 1): #
|
936 |
+
self.forward(im) # warmup
|
937 |
+
|
938 |
+
@staticmethod
|
939 |
+
def _model_type(p='path/to/model.pt'):
|
940 |
+
# Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx
|
941 |
+
# types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]
|
942 |
+
from export import export_formats
|
943 |
+
from utils.downloads import is_url
|
944 |
+
sf = list(export_formats().Suffix) # export suffixes
|
945 |
+
if not is_url(p, check=False):
|
946 |
+
check_suffix(p, sf) # checks
|
947 |
+
url = urlparse(p) # if url may be Triton inference server
|
948 |
+
types = [s in Path(p).name for s in sf]
|
949 |
+
types[8] &= not types[9] # tflite &= not edgetpu
|
950 |
+
triton = not any(types) and all([any(s in url.scheme for s in ["http", "grpc"]), url.netloc])
|
951 |
+
return types + [triton]
|
952 |
+
|
953 |
+
@staticmethod
|
954 |
+
def _load_metadata(f=Path('path/to/meta.yaml')):
|
955 |
+
# Load metadata from meta.yaml if it exists
|
956 |
+
if f.exists():
|
957 |
+
d = yaml_load(f)
|
958 |
+
return d['stride'], d['names'] # assign stride, names
|
959 |
+
return None, None
|
960 |
+
|
961 |
+
|
962 |
+
class AutoShape(nn.Module):
|
963 |
+
# YOLO input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
|
964 |
+
conf = 0.25 # NMS confidence threshold
|
965 |
+
iou = 0.45 # NMS IoU threshold
|
966 |
+
agnostic = False # NMS class-agnostic
|
967 |
+
multi_label = False # NMS multiple labels per box
|
968 |
+
classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs
|
969 |
+
max_det = 1000 # maximum number of detections per image
|
970 |
+
amp = False # Automatic Mixed Precision (AMP) inference
|
971 |
+
|
972 |
+
def __init__(self, model, verbose=True):
|
973 |
+
super().__init__()
|
974 |
+
if verbose:
|
975 |
+
LOGGER.info('Adding AutoShape... ')
|
976 |
+
copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes
|
977 |
+
self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance
|
978 |
+
self.pt = not self.dmb or model.pt # PyTorch model
|
979 |
+
self.model = model.eval()
|
980 |
+
if self.pt:
|
981 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
982 |
+
m.inplace = False # Detect.inplace=False for safe multithread inference
|
983 |
+
m.export = True # do not output loss values
|
984 |
+
|
985 |
+
def _apply(self, fn):
|
986 |
+
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
|
987 |
+
self = super()._apply(fn)
|
988 |
+
from models.yolo import Detect, Segment
|
989 |
+
if self.pt:
|
990 |
+
m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect()
|
991 |
+
if isinstance(m, (Detect, Segment)):
|
992 |
+
for k in 'stride', 'anchor_grid', 'stride_grid', 'grid':
|
993 |
+
x = getattr(m, k)
|
994 |
+
setattr(m, k, list(map(fn, x))) if isinstance(x, (list, tuple)) else setattr(m, k, fn(x))
|
995 |
+
return self
|
996 |
+
|
997 |
+
@smart_inference_mode()
|
998 |
+
def forward(self, ims, size=640, augment=False, profile=False):
|
999 |
+
# Inference from various sources. For size(height=640, width=1280), RGB images example inputs are:
|
1000 |
+
# file: ims = 'data/images/zidane.jpg' # str or PosixPath
|
1001 |
+
# URI: = 'https://ultralytics.com/images/zidane.jpg'
|
1002 |
+
# OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
|
1003 |
+
# PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
|
1004 |
+
# numpy: = np.zeros((640,1280,3)) # HWC
|
1005 |
+
# torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
|
1006 |
+
# multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
|
1007 |
+
|
1008 |
+
dt = (Profile(), Profile(), Profile())
|
1009 |
+
with dt[0]:
|
1010 |
+
if isinstance(size, int): # expand
|
1011 |
+
size = (size, size)
|
1012 |
+
p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device) # param
|
1013 |
+
autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference
|
1014 |
+
if isinstance(ims, torch.Tensor): # torch
|
1015 |
+
with amp.autocast(autocast):
|
1016 |
+
return self.model(ims.to(p.device).type_as(p), augment=augment) # inference
|
1017 |
+
|
1018 |
+
# Pre-process
|
1019 |
+
n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims]) # number, list of images
|
1020 |
+
shape0, shape1, files = [], [], [] # image and inference shapes, filenames
|
1021 |
+
for i, im in enumerate(ims):
|
1022 |
+
f = f'image{i}' # filename
|
1023 |
+
if isinstance(im, (str, Path)): # filename or uri
|
1024 |
+
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
|
1025 |
+
im = np.asarray(exif_transpose(im))
|
1026 |
+
elif isinstance(im, Image.Image): # PIL Image
|
1027 |
+
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
|
1028 |
+
files.append(Path(f).with_suffix('.jpg').name)
|
1029 |
+
if im.shape[0] < 5: # image in CHW
|
1030 |
+
im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
|
1031 |
+
im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # enforce 3ch input
|
1032 |
+
s = im.shape[:2] # HWC
|
1033 |
+
shape0.append(s) # image shape
|
1034 |
+
g = max(size) / max(s) # gain
|
1035 |
+
shape1.append([int(y * g) for y in s])
|
1036 |
+
ims[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
|
1037 |
+
shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] # inf shape
|
1038 |
+
x = [letterbox(im, shape1, auto=False)[0] for im in ims] # pad
|
1039 |
+
x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW
|
1040 |
+
x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32
|
1041 |
+
|
1042 |
+
with amp.autocast(autocast):
|
1043 |
+
# Inference
|
1044 |
+
with dt[1]:
|
1045 |
+
y = self.model(x, augment=augment) # forward
|
1046 |
+
|
1047 |
+
# Post-process
|
1048 |
+
with dt[2]:
|
1049 |
+
y = non_max_suppression(y if self.dmb else y[0],
|
1050 |
+
self.conf,
|
1051 |
+
self.iou,
|
1052 |
+
self.classes,
|
1053 |
+
self.agnostic,
|
1054 |
+
self.multi_label,
|
1055 |
+
max_det=self.max_det) # NMS
|
1056 |
+
for i in range(n):
|
1057 |
+
scale_boxes(shape1, y[i][:, :4], shape0[i])
|
1058 |
+
|
1059 |
+
return Detections(ims, y, files, dt, self.names, x.shape)
|
1060 |
+
|
1061 |
+
|
1062 |
+
class Detections:
|
1063 |
+
# YOLO detections class for inference results
|
1064 |
+
def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):
|
1065 |
+
super().__init__()
|
1066 |
+
d = pred[0].device # device
|
1067 |
+
gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims] # normalizations
|
1068 |
+
self.ims = ims # list of images as numpy arrays
|
1069 |
+
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
|
1070 |
+
self.names = names # class names
|
1071 |
+
self.files = files # image filenames
|
1072 |
+
self.times = times # profiling times
|
1073 |
+
self.xyxy = pred # xyxy pixels
|
1074 |
+
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
|
1075 |
+
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
|
1076 |
+
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
|
1077 |
+
self.n = len(self.pred) # number of images (batch size)
|
1078 |
+
self.t = tuple(x.t / self.n * 1E3 for x in times) # timestamps (ms)
|
1079 |
+
self.s = tuple(shape) # inference BCHW shape
|
1080 |
+
|
1081 |
+
def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):
|
1082 |
+
s, crops = '', []
|
1083 |
+
for i, (im, pred) in enumerate(zip(self.ims, self.pred)):
|
1084 |
+
s += f'\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
|
1085 |
+
if pred.shape[0]:
|
1086 |
+
for c in pred[:, -1].unique():
|
1087 |
+
n = (pred[:, -1] == c).sum() # detections per class
|
1088 |
+
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
|
1089 |
+
s = s.rstrip(', ')
|
1090 |
+
if show or save or render or crop:
|
1091 |
+
annotator = Annotator(im, example=str(self.names))
|
1092 |
+
for *box, conf, cls in reversed(pred): # xyxy, confidence, class
|
1093 |
+
label = f'{self.names[int(cls)]} {conf:.2f}'
|
1094 |
+
if crop:
|
1095 |
+
file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
|
1096 |
+
crops.append({
|
1097 |
+
'box': box,
|
1098 |
+
'conf': conf,
|
1099 |
+
'cls': cls,
|
1100 |
+
'label': label,
|
1101 |
+
'im': save_one_box(box, im, file=file, save=save)})
|
1102 |
+
else: # all others
|
1103 |
+
annotator.box_label(box, label if labels else '', color=colors(cls))
|
1104 |
+
im = annotator.im
|
1105 |
+
else:
|
1106 |
+
s += '(no detections)'
|
1107 |
+
|
1108 |
+
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
|
1109 |
+
if show:
|
1110 |
+
display(im) if is_notebook() else im.show(self.files[i])
|
1111 |
+
if save:
|
1112 |
+
f = self.files[i]
|
1113 |
+
im.save(save_dir / f) # save
|
1114 |
+
if i == self.n - 1:
|
1115 |
+
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
|
1116 |
+
if render:
|
1117 |
+
self.ims[i] = np.asarray(im)
|
1118 |
+
if pprint:
|
1119 |
+
s = s.lstrip('\n')
|
1120 |
+
return f'{s}\nSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t
|
1121 |
+
if crop:
|
1122 |
+
if save:
|
1123 |
+
LOGGER.info(f'Saved results to {save_dir}\n')
|
1124 |
+
return crops
|
1125 |
+
|
1126 |
+
@TryExcept('Showing images is not supported in this environment')
|
1127 |
+
def show(self, labels=True):
|
1128 |
+
self._run(show=True, labels=labels) # show results
|
1129 |
+
|
1130 |
+
def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):
|
1131 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) # increment save_dir
|
1132 |
+
self._run(save=True, labels=labels, save_dir=save_dir) # save results
|
1133 |
+
|
1134 |
+
def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):
|
1135 |
+
save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None
|
1136 |
+
return self._run(crop=True, save=save, save_dir=save_dir) # crop results
|
1137 |
+
|
1138 |
+
def render(self, labels=True):
|
1139 |
+
self._run(render=True, labels=labels) # render results
|
1140 |
+
return self.ims
|
1141 |
+
|
1142 |
+
def pandas(self):
|
1143 |
+
# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
|
1144 |
+
new = copy(self) # return copy
|
1145 |
+
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
|
1146 |
+
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
|
1147 |
+
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
|
1148 |
+
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
|
1149 |
+
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
|
1150 |
+
return new
|
1151 |
+
|
1152 |
+
def tolist(self):
|
1153 |
+
# return a list of Detections objects, i.e. 'for result in results.tolist():'
|
1154 |
+
r = range(self.n) # iterable
|
1155 |
+
x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]
|
1156 |
+
# for d in x:
|
1157 |
+
# for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
|
1158 |
+
# setattr(d, k, getattr(d, k)[0]) # pop out of list
|
1159 |
+
return x
|
1160 |
+
|
1161 |
+
def print(self):
|
1162 |
+
LOGGER.info(self.__str__())
|
1163 |
+
|
1164 |
+
def __len__(self): # override len(results)
|
1165 |
+
return self.n
|
1166 |
+
|
1167 |
+
def __str__(self): # override print(results)
|
1168 |
+
return self._run(pprint=True) # print results
|
1169 |
+
|
1170 |
+
def __repr__(self):
|
1171 |
+
return f'YOLO {self.__class__} instance\n' + self.__str__()
|
1172 |
+
|
1173 |
+
|
1174 |
+
class Proto(nn.Module):
|
1175 |
+
# YOLO mask Proto module for segmentation models
|
1176 |
+
def __init__(self, c1, c_=256, c2=32): # ch_in, number of protos, number of masks
|
1177 |
+
super().__init__()
|
1178 |
+
self.cv1 = Conv(c1, c_, k=3)
|
1179 |
+
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
|
1180 |
+
self.cv2 = Conv(c_, c_, k=3)
|
1181 |
+
self.cv3 = Conv(c_, c2)
|
1182 |
+
|
1183 |
+
def forward(self, x):
|
1184 |
+
return self.cv3(self.cv2(self.upsample(self.cv1(x))))
|
1185 |
+
|
1186 |
+
|
1187 |
+
class Classify(nn.Module):
|
1188 |
+
# YOLO classification head, i.e. x(b,c1,20,20) to x(b,c2)
|
1189 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
|
1190 |
+
super().__init__()
|
1191 |
+
c_ = 1280 # efficientnet_b0 size
|
1192 |
+
self.conv = Conv(c1, c_, k, s, autopad(k, p), g)
|
1193 |
+
self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1)
|
1194 |
+
self.drop = nn.Dropout(p=0.0, inplace=True)
|
1195 |
+
self.linear = nn.Linear(c_, c2) # to x(b,c2)
|
1196 |
+
|
1197 |
+
def forward(self, x):
|
1198 |
+
if isinstance(x, list):
|
1199 |
+
x = torch.cat(x, 1)
|
1200 |
+
return self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))
|
models/detect/gelan-c.yaml
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv9
|
2 |
+
|
3 |
+
# parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
#activation: nn.LeakyReLU(0.1)
|
8 |
+
#activation: nn.ReLU()
|
9 |
+
|
10 |
+
# anchors
|
11 |
+
anchors: 3
|
12 |
+
|
13 |
+
# gelan backbone
|
14 |
+
backbone:
|
15 |
+
[
|
16 |
+
# conv down
|
17 |
+
[-1, 1, Conv, [64, 3, 2]], # 0-P1/2
|
18 |
+
|
19 |
+
# conv down
|
20 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
21 |
+
|
22 |
+
# elan-1 block
|
23 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 1]], # 2
|
24 |
+
|
25 |
+
# avg-conv down
|
26 |
+
[-1, 1, ADown, [256]], # 3-P3/8
|
27 |
+
|
28 |
+
# elan-2 block
|
29 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 1]], # 4
|
30 |
+
|
31 |
+
# avg-conv down
|
32 |
+
[-1, 1, ADown, [512]], # 5-P4/16
|
33 |
+
|
34 |
+
# elan-2 block
|
35 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 6
|
36 |
+
|
37 |
+
# avg-conv down
|
38 |
+
[-1, 1, ADown, [512]], # 7-P5/32
|
39 |
+
|
40 |
+
# elan-2 block
|
41 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 8
|
42 |
+
]
|
43 |
+
|
44 |
+
# gelan head
|
45 |
+
head:
|
46 |
+
[
|
47 |
+
# elan-spp block
|
48 |
+
[-1, 1, SPPELAN, [512, 256]], # 9
|
49 |
+
|
50 |
+
# up-concat merge
|
51 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
52 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
53 |
+
|
54 |
+
# elan-2 block
|
55 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 12
|
56 |
+
|
57 |
+
# up-concat merge
|
58 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
59 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
60 |
+
|
61 |
+
# elan-2 block
|
62 |
+
[-1, 1, RepNCSPELAN4, [256, 256, 128, 1]], # 15 (P3/8-small)
|
63 |
+
|
64 |
+
# avg-conv-down merge
|
65 |
+
[-1, 1, ADown, [256]],
|
66 |
+
[[-1, 12], 1, Concat, [1]], # cat head P4
|
67 |
+
|
68 |
+
# elan-2 block
|
69 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 18 (P4/16-medium)
|
70 |
+
|
71 |
+
# avg-conv-down merge
|
72 |
+
[-1, 1, ADown, [512]],
|
73 |
+
[[-1, 9], 1, Concat, [1]], # cat head P5
|
74 |
+
|
75 |
+
# elan-2 block
|
76 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 21 (P5/32-large)
|
77 |
+
|
78 |
+
# detect
|
79 |
+
[[15, 18, 21], 1, DDetect, [nc]], # DDetect(P3, P4, P5)
|
80 |
+
]
|
models/detect/gelan-e.yaml
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv9
|
2 |
+
|
3 |
+
# parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
#activation: nn.LeakyReLU(0.1)
|
8 |
+
#activation: nn.ReLU()
|
9 |
+
|
10 |
+
# anchors
|
11 |
+
anchors: 3
|
12 |
+
|
13 |
+
# gelan backbone
|
14 |
+
backbone:
|
15 |
+
[
|
16 |
+
[-1, 1, Silence, []],
|
17 |
+
|
18 |
+
# conv down
|
19 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
20 |
+
|
21 |
+
# conv down
|
22 |
+
[-1, 1, Conv, [128, 3, 2]], # 2-P2/4
|
23 |
+
|
24 |
+
# elan-1 block
|
25 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 2]], # 3
|
26 |
+
|
27 |
+
# avg-conv down
|
28 |
+
[-1, 1, ADown, [256]], # 4-P3/8
|
29 |
+
|
30 |
+
# elan-2 block
|
31 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 2]], # 5
|
32 |
+
|
33 |
+
# avg-conv down
|
34 |
+
[-1, 1, ADown, [512]], # 6-P4/16
|
35 |
+
|
36 |
+
# elan-2 block
|
37 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 7
|
38 |
+
|
39 |
+
# avg-conv down
|
40 |
+
[-1, 1, ADown, [1024]], # 8-P5/32
|
41 |
+
|
42 |
+
# elan-2 block
|
43 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 9
|
44 |
+
|
45 |
+
# routing
|
46 |
+
[1, 1, CBLinear, [[64]]], # 10
|
47 |
+
[3, 1, CBLinear, [[64, 128]]], # 11
|
48 |
+
[5, 1, CBLinear, [[64, 128, 256]]], # 12
|
49 |
+
[7, 1, CBLinear, [[64, 128, 256, 512]]], # 13
|
50 |
+
[9, 1, CBLinear, [[64, 128, 256, 512, 1024]]], # 14
|
51 |
+
|
52 |
+
# conv down fuse
|
53 |
+
[0, 1, Conv, [64, 3, 2]], # 15-P1/2
|
54 |
+
[[10, 11, 12, 13, 14, -1], 1, CBFuse, [[0, 0, 0, 0, 0]]], # 16
|
55 |
+
|
56 |
+
# conv down fuse
|
57 |
+
[-1, 1, Conv, [128, 3, 2]], # 17-P2/4
|
58 |
+
[[11, 12, 13, 14, -1], 1, CBFuse, [[1, 1, 1, 1]]], # 18
|
59 |
+
|
60 |
+
# elan-1 block
|
61 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 2]], # 19
|
62 |
+
|
63 |
+
# avg-conv down fuse
|
64 |
+
[-1, 1, ADown, [256]], # 20-P3/8
|
65 |
+
[[12, 13, 14, -1], 1, CBFuse, [[2, 2, 2]]], # 21
|
66 |
+
|
67 |
+
# elan-2 block
|
68 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 2]], # 22
|
69 |
+
|
70 |
+
# avg-conv down fuse
|
71 |
+
[-1, 1, ADown, [512]], # 23-P4/16
|
72 |
+
[[13, 14, -1], 1, CBFuse, [[3, 3]]], # 24
|
73 |
+
|
74 |
+
# elan-2 block
|
75 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 25
|
76 |
+
|
77 |
+
# avg-conv down fuse
|
78 |
+
[-1, 1, ADown, [1024]], # 26-P5/32
|
79 |
+
[[14, -1], 1, CBFuse, [[4]]], # 27
|
80 |
+
|
81 |
+
# elan-2 block
|
82 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 28
|
83 |
+
]
|
84 |
+
|
85 |
+
# gelan head
|
86 |
+
head:
|
87 |
+
[
|
88 |
+
# elan-spp block
|
89 |
+
[28, 1, SPPELAN, [512, 256]], # 29
|
90 |
+
|
91 |
+
# up-concat merge
|
92 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
93 |
+
[[-1, 25], 1, Concat, [1]], # cat backbone P4
|
94 |
+
|
95 |
+
# elan-2 block
|
96 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 2]], # 32
|
97 |
+
|
98 |
+
# up-concat merge
|
99 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
100 |
+
[[-1, 22], 1, Concat, [1]], # cat backbone P3
|
101 |
+
|
102 |
+
# elan-2 block
|
103 |
+
[-1, 1, RepNCSPELAN4, [256, 256, 128, 2]], # 35 (P3/8-small)
|
104 |
+
|
105 |
+
# avg-conv-down merge
|
106 |
+
[-1, 1, ADown, [256]],
|
107 |
+
[[-1, 32], 1, Concat, [1]], # cat head P4
|
108 |
+
|
109 |
+
# elan-2 block
|
110 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 2]], # 38 (P4/16-medium)
|
111 |
+
|
112 |
+
# avg-conv-down merge
|
113 |
+
[-1, 1, ADown, [512]],
|
114 |
+
[[-1, 29], 1, Concat, [1]], # cat head P5
|
115 |
+
|
116 |
+
# elan-2 block
|
117 |
+
[-1, 1, RepNCSPELAN4, [512, 1024, 512, 2]], # 41 (P5/32-large)
|
118 |
+
|
119 |
+
# detect
|
120 |
+
[[35, 38, 41], 1, DDetect, [nc]], # Detect(P3, P4, P5)
|
121 |
+
]
|
models/detect/gelan.yaml
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv9
|
2 |
+
|
3 |
+
# parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
#activation: nn.LeakyReLU(0.1)
|
8 |
+
#activation: nn.ReLU()
|
9 |
+
|
10 |
+
# anchors
|
11 |
+
anchors: 3
|
12 |
+
|
13 |
+
# gelan backbone
|
14 |
+
backbone:
|
15 |
+
[
|
16 |
+
# conv down
|
17 |
+
[-1, 1, Conv, [64, 3, 2]], # 0-P1/2
|
18 |
+
|
19 |
+
# conv down
|
20 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
21 |
+
|
22 |
+
# elan-1 block
|
23 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 1]], # 2
|
24 |
+
|
25 |
+
# avg-conv down
|
26 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
27 |
+
|
28 |
+
# elan-2 block
|
29 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 1]], # 4
|
30 |
+
|
31 |
+
# avg-conv down
|
32 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
33 |
+
|
34 |
+
# elan-2 block
|
35 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 6
|
36 |
+
|
37 |
+
# avg-conv down
|
38 |
+
[-1, 1, Conv, [512, 3, 2]], # 7-P5/32
|
39 |
+
|
40 |
+
# elan-2 block
|
41 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 8
|
42 |
+
]
|
43 |
+
|
44 |
+
# gelan head
|
45 |
+
head:
|
46 |
+
[
|
47 |
+
# elan-spp block
|
48 |
+
[-1, 1, SPPELAN, [512, 256]], # 9
|
49 |
+
|
50 |
+
# up-concat merge
|
51 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
52 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
53 |
+
|
54 |
+
# elan-2 block
|
55 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 12
|
56 |
+
|
57 |
+
# up-concat merge
|
58 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
59 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
60 |
+
|
61 |
+
# elan-2 block
|
62 |
+
[-1, 1, RepNCSPELAN4, [256, 256, 128, 1]], # 15 (P3/8-small)
|
63 |
+
|
64 |
+
# avg-conv-down merge
|
65 |
+
[-1, 1, Conv, [256, 3, 2]],
|
66 |
+
[[-1, 12], 1, Concat, [1]], # cat head P4
|
67 |
+
|
68 |
+
# elan-2 block
|
69 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 18 (P4/16-medium)
|
70 |
+
|
71 |
+
# avg-conv-down merge
|
72 |
+
[-1, 1, Conv, [512, 3, 2]],
|
73 |
+
[[-1, 9], 1, Concat, [1]], # cat head P5
|
74 |
+
|
75 |
+
# elan-2 block
|
76 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 21 (P5/32-large)
|
77 |
+
|
78 |
+
# detect
|
79 |
+
[[15, 18, 21], 1, DDetect, [nc]], # Detect(P3, P4, P5)
|
80 |
+
]
|
models/detect/yolov7-af.yaml
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv7
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1. # model depth multiple
|
6 |
+
width_multiple: 1. # layer channel multiple
|
7 |
+
anchors: 3
|
8 |
+
|
9 |
+
# YOLOv7 backbone
|
10 |
+
backbone:
|
11 |
+
# [from, number, module, args]
|
12 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
13 |
+
|
14 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
15 |
+
[-1, 1, Conv, [64, 3, 1]],
|
16 |
+
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
18 |
+
[-1, 1, Conv, [64, 1, 1]],
|
19 |
+
[-2, 1, Conv, [64, 1, 1]],
|
20 |
+
[-1, 1, Conv, [64, 3, 1]],
|
21 |
+
[-1, 1, Conv, [64, 3, 1]],
|
22 |
+
[-1, 1, Conv, [64, 3, 1]],
|
23 |
+
[-1, 1, Conv, [64, 3, 1]],
|
24 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
25 |
+
[-1, 1, Conv, [256, 1, 1]], # 11
|
26 |
+
|
27 |
+
[-1, 1, MP, []],
|
28 |
+
[-1, 1, Conv, [128, 1, 1]],
|
29 |
+
[-3, 1, Conv, [128, 1, 1]],
|
30 |
+
[-1, 1, Conv, [128, 3, 2]],
|
31 |
+
[[-1, -3], 1, Concat, [1]], # 16-P3/8
|
32 |
+
[-1, 1, Conv, [128, 1, 1]],
|
33 |
+
[-2, 1, Conv, [128, 1, 1]],
|
34 |
+
[-1, 1, Conv, [128, 3, 1]],
|
35 |
+
[-1, 1, Conv, [128, 3, 1]],
|
36 |
+
[-1, 1, Conv, [128, 3, 1]],
|
37 |
+
[-1, 1, Conv, [128, 3, 1]],
|
38 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
39 |
+
[-1, 1, Conv, [512, 1, 1]], # 24
|
40 |
+
|
41 |
+
[-1, 1, MP, []],
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-3, 1, Conv, [256, 1, 1]],
|
44 |
+
[-1, 1, Conv, [256, 3, 2]],
|
45 |
+
[[-1, -3], 1, Concat, [1]], # 29-P4/16
|
46 |
+
[-1, 1, Conv, [256, 1, 1]],
|
47 |
+
[-2, 1, Conv, [256, 1, 1]],
|
48 |
+
[-1, 1, Conv, [256, 3, 1]],
|
49 |
+
[-1, 1, Conv, [256, 3, 1]],
|
50 |
+
[-1, 1, Conv, [256, 3, 1]],
|
51 |
+
[-1, 1, Conv, [256, 3, 1]],
|
52 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
53 |
+
[-1, 1, Conv, [1024, 1, 1]], # 37
|
54 |
+
|
55 |
+
[-1, 1, MP, []],
|
56 |
+
[-1, 1, Conv, [512, 1, 1]],
|
57 |
+
[-3, 1, Conv, [512, 1, 1]],
|
58 |
+
[-1, 1, Conv, [512, 3, 2]],
|
59 |
+
[[-1, -3], 1, Concat, [1]], # 42-P5/32
|
60 |
+
[-1, 1, Conv, [256, 1, 1]],
|
61 |
+
[-2, 1, Conv, [256, 1, 1]],
|
62 |
+
[-1, 1, Conv, [256, 3, 1]],
|
63 |
+
[-1, 1, Conv, [256, 3, 1]],
|
64 |
+
[-1, 1, Conv, [256, 3, 1]],
|
65 |
+
[-1, 1, Conv, [256, 3, 1]],
|
66 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
67 |
+
[-1, 1, Conv, [1024, 1, 1]], # 50
|
68 |
+
]
|
69 |
+
|
70 |
+
# yolov7 head
|
71 |
+
head:
|
72 |
+
[[-1, 1, SPPCSPC, [512]], # 51
|
73 |
+
|
74 |
+
[-1, 1, Conv, [256, 1, 1]],
|
75 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
76 |
+
[37, 1, Conv, [256, 1, 1]], # route backbone P4
|
77 |
+
[[-1, -2], 1, Concat, [1]],
|
78 |
+
|
79 |
+
[-1, 1, Conv, [256, 1, 1]],
|
80 |
+
[-2, 1, Conv, [256, 1, 1]],
|
81 |
+
[-1, 1, Conv, [128, 3, 1]],
|
82 |
+
[-1, 1, Conv, [128, 3, 1]],
|
83 |
+
[-1, 1, Conv, [128, 3, 1]],
|
84 |
+
[-1, 1, Conv, [128, 3, 1]],
|
85 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
86 |
+
[-1, 1, Conv, [256, 1, 1]], # 63
|
87 |
+
|
88 |
+
[-1, 1, Conv, [128, 1, 1]],
|
89 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
90 |
+
[24, 1, Conv, [128, 1, 1]], # route backbone P3
|
91 |
+
[[-1, -2], 1, Concat, [1]],
|
92 |
+
|
93 |
+
[-1, 1, Conv, [128, 1, 1]],
|
94 |
+
[-2, 1, Conv, [128, 1, 1]],
|
95 |
+
[-1, 1, Conv, [64, 3, 1]],
|
96 |
+
[-1, 1, Conv, [64, 3, 1]],
|
97 |
+
[-1, 1, Conv, [64, 3, 1]],
|
98 |
+
[-1, 1, Conv, [64, 3, 1]],
|
99 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
100 |
+
[-1, 1, Conv, [128, 1, 1]], # 75
|
101 |
+
|
102 |
+
[-1, 1, MP, []],
|
103 |
+
[-1, 1, Conv, [128, 1, 1]],
|
104 |
+
[-3, 1, Conv, [128, 1, 1]],
|
105 |
+
[-1, 1, Conv, [128, 3, 2]],
|
106 |
+
[[-1, -3, 63], 1, Concat, [1]],
|
107 |
+
|
108 |
+
[-1, 1, Conv, [256, 1, 1]],
|
109 |
+
[-2, 1, Conv, [256, 1, 1]],
|
110 |
+
[-1, 1, Conv, [128, 3, 1]],
|
111 |
+
[-1, 1, Conv, [128, 3, 1]],
|
112 |
+
[-1, 1, Conv, [128, 3, 1]],
|
113 |
+
[-1, 1, Conv, [128, 3, 1]],
|
114 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
115 |
+
[-1, 1, Conv, [256, 1, 1]], # 88
|
116 |
+
|
117 |
+
[-1, 1, MP, []],
|
118 |
+
[-1, 1, Conv, [256, 1, 1]],
|
119 |
+
[-3, 1, Conv, [256, 1, 1]],
|
120 |
+
[-1, 1, Conv, [256, 3, 2]],
|
121 |
+
[[-1, -3, 51], 1, Concat, [1]],
|
122 |
+
|
123 |
+
[-1, 1, Conv, [512, 1, 1]],
|
124 |
+
[-2, 1, Conv, [512, 1, 1]],
|
125 |
+
[-1, 1, Conv, [256, 3, 1]],
|
126 |
+
[-1, 1, Conv, [256, 3, 1]],
|
127 |
+
[-1, 1, Conv, [256, 3, 1]],
|
128 |
+
[-1, 1, Conv, [256, 3, 1]],
|
129 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
130 |
+
[-1, 1, Conv, [512, 1, 1]], # 101
|
131 |
+
|
132 |
+
[75, 1, Conv, [256, 3, 1]],
|
133 |
+
[88, 1, Conv, [512, 3, 1]],
|
134 |
+
[101, 1, Conv, [1024, 3, 1]],
|
135 |
+
|
136 |
+
[[102, 103, 104], 1, Detect, [nc]], # Detect(P3, P4, P5)
|
137 |
+
]
|
models/detect/yolov9-c.yaml
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv9
|
2 |
+
|
3 |
+
# parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
#activation: nn.LeakyReLU(0.1)
|
8 |
+
#activation: nn.ReLU()
|
9 |
+
|
10 |
+
# anchors
|
11 |
+
anchors: 3
|
12 |
+
|
13 |
+
# YOLOv9 backbone
|
14 |
+
backbone:
|
15 |
+
[
|
16 |
+
[-1, 1, Silence, []],
|
17 |
+
|
18 |
+
# conv down
|
19 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
20 |
+
|
21 |
+
# conv down
|
22 |
+
[-1, 1, Conv, [128, 3, 2]], # 2-P2/4
|
23 |
+
|
24 |
+
# elan-1 block
|
25 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 1]], # 3
|
26 |
+
|
27 |
+
# avg-conv down
|
28 |
+
[-1, 1, ADown, [256]], # 4-P3/8
|
29 |
+
|
30 |
+
# elan-2 block
|
31 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 1]], # 5
|
32 |
+
|
33 |
+
# avg-conv down
|
34 |
+
[-1, 1, ADown, [512]], # 6-P4/16
|
35 |
+
|
36 |
+
# elan-2 block
|
37 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 7
|
38 |
+
|
39 |
+
# avg-conv down
|
40 |
+
[-1, 1, ADown, [512]], # 8-P5/32
|
41 |
+
|
42 |
+
# elan-2 block
|
43 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 9
|
44 |
+
]
|
45 |
+
|
46 |
+
# YOLOv9 head
|
47 |
+
head:
|
48 |
+
[
|
49 |
+
# elan-spp block
|
50 |
+
[-1, 1, SPPELAN, [512, 256]], # 10
|
51 |
+
|
52 |
+
# up-concat merge
|
53 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
54 |
+
[[-1, 7], 1, Concat, [1]], # cat backbone P4
|
55 |
+
|
56 |
+
# elan-2 block
|
57 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 13
|
58 |
+
|
59 |
+
# up-concat merge
|
60 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
61 |
+
[[-1, 5], 1, Concat, [1]], # cat backbone P3
|
62 |
+
|
63 |
+
# elan-2 block
|
64 |
+
[-1, 1, RepNCSPELAN4, [256, 256, 128, 1]], # 16 (P3/8-small)
|
65 |
+
|
66 |
+
# avg-conv-down merge
|
67 |
+
[-1, 1, ADown, [256]],
|
68 |
+
[[-1, 13], 1, Concat, [1]], # cat head P4
|
69 |
+
|
70 |
+
# elan-2 block
|
71 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 19 (P4/16-medium)
|
72 |
+
|
73 |
+
# avg-conv-down merge
|
74 |
+
[-1, 1, ADown, [512]],
|
75 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
76 |
+
|
77 |
+
# elan-2 block
|
78 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 22 (P5/32-large)
|
79 |
+
|
80 |
+
|
81 |
+
# multi-level reversible auxiliary branch
|
82 |
+
|
83 |
+
# routing
|
84 |
+
[5, 1, CBLinear, [[256]]], # 23
|
85 |
+
[7, 1, CBLinear, [[256, 512]]], # 24
|
86 |
+
[9, 1, CBLinear, [[256, 512, 512]]], # 25
|
87 |
+
|
88 |
+
# conv down
|
89 |
+
[0, 1, Conv, [64, 3, 2]], # 26-P1/2
|
90 |
+
|
91 |
+
# conv down
|
92 |
+
[-1, 1, Conv, [128, 3, 2]], # 27-P2/4
|
93 |
+
|
94 |
+
# elan-1 block
|
95 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 1]], # 28
|
96 |
+
|
97 |
+
# avg-conv down fuse
|
98 |
+
[-1, 1, ADown, [256]], # 29-P3/8
|
99 |
+
[[23, 24, 25, -1], 1, CBFuse, [[0, 0, 0]]], # 30
|
100 |
+
|
101 |
+
# elan-2 block
|
102 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 1]], # 31
|
103 |
+
|
104 |
+
# avg-conv down fuse
|
105 |
+
[-1, 1, ADown, [512]], # 32-P4/16
|
106 |
+
[[24, 25, -1], 1, CBFuse, [[1, 1]]], # 33
|
107 |
+
|
108 |
+
# elan-2 block
|
109 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 34
|
110 |
+
|
111 |
+
# avg-conv down fuse
|
112 |
+
[-1, 1, ADown, [512]], # 35-P5/32
|
113 |
+
[[25, -1], 1, CBFuse, [[2]]], # 36
|
114 |
+
|
115 |
+
# elan-2 block
|
116 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 37
|
117 |
+
|
118 |
+
|
119 |
+
|
120 |
+
# detection head
|
121 |
+
|
122 |
+
# detect
|
123 |
+
[[31, 34, 37, 16, 19, 22], 1, DualDDetect, [nc]], # DualDDetect(A3, A4, A5, P3, P4, P5)
|
124 |
+
]
|
models/detect/yolov9-e.yaml
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv9
|
2 |
+
|
3 |
+
# parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
#activation: nn.LeakyReLU(0.1)
|
8 |
+
#activation: nn.ReLU()
|
9 |
+
|
10 |
+
# anchors
|
11 |
+
anchors: 3
|
12 |
+
|
13 |
+
# YOLOv9 backbone
|
14 |
+
backbone:
|
15 |
+
[
|
16 |
+
[-1, 1, Silence, []],
|
17 |
+
|
18 |
+
# conv down
|
19 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
20 |
+
|
21 |
+
# conv down
|
22 |
+
[-1, 1, Conv, [128, 3, 2]], # 2-P2/4
|
23 |
+
|
24 |
+
# csp-elan block
|
25 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 2]], # 3
|
26 |
+
|
27 |
+
# avg-conv down
|
28 |
+
[-1, 1, ADown, [256]], # 4-P3/8
|
29 |
+
|
30 |
+
# csp-elan block
|
31 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 2]], # 5
|
32 |
+
|
33 |
+
# avg-conv down
|
34 |
+
[-1, 1, ADown, [512]], # 6-P4/16
|
35 |
+
|
36 |
+
# csp-elan block
|
37 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 7
|
38 |
+
|
39 |
+
# avg-conv down
|
40 |
+
[-1, 1, ADown, [1024]], # 8-P5/32
|
41 |
+
|
42 |
+
# csp-elan block
|
43 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 9
|
44 |
+
|
45 |
+
# routing
|
46 |
+
[1, 1, CBLinear, [[64]]], # 10
|
47 |
+
[3, 1, CBLinear, [[64, 128]]], # 11
|
48 |
+
[5, 1, CBLinear, [[64, 128, 256]]], # 12
|
49 |
+
[7, 1, CBLinear, [[64, 128, 256, 512]]], # 13
|
50 |
+
[9, 1, CBLinear, [[64, 128, 256, 512, 1024]]], # 14
|
51 |
+
|
52 |
+
# conv down
|
53 |
+
[0, 1, Conv, [64, 3, 2]], # 15-P1/2
|
54 |
+
[[10, 11, 12, 13, 14, -1], 1, CBFuse, [[0, 0, 0, 0, 0]]], # 16
|
55 |
+
|
56 |
+
# conv down
|
57 |
+
[-1, 1, Conv, [128, 3, 2]], # 17-P2/4
|
58 |
+
[[11, 12, 13, 14, -1], 1, CBFuse, [[1, 1, 1, 1]]], # 18
|
59 |
+
|
60 |
+
# csp-elan block
|
61 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 2]], # 19
|
62 |
+
|
63 |
+
# avg-conv down fuse
|
64 |
+
[-1, 1, ADown, [256]], # 20-P3/8
|
65 |
+
[[12, 13, 14, -1], 1, CBFuse, [[2, 2, 2]]], # 21
|
66 |
+
|
67 |
+
# csp-elan block
|
68 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 2]], # 22
|
69 |
+
|
70 |
+
# avg-conv down fuse
|
71 |
+
[-1, 1, ADown, [512]], # 23-P4/16
|
72 |
+
[[13, 14, -1], 1, CBFuse, [[3, 3]]], # 24
|
73 |
+
|
74 |
+
# csp-elan block
|
75 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 25
|
76 |
+
|
77 |
+
# avg-conv down fuse
|
78 |
+
[-1, 1, ADown, [1024]], # 26-P5/32
|
79 |
+
[[14, -1], 1, CBFuse, [[4]]], # 27
|
80 |
+
|
81 |
+
# csp-elan block
|
82 |
+
[-1, 1, RepNCSPELAN4, [1024, 512, 256, 2]], # 28
|
83 |
+
]
|
84 |
+
|
85 |
+
# YOLOv9 head
|
86 |
+
head:
|
87 |
+
[
|
88 |
+
# multi-level auxiliary branch
|
89 |
+
|
90 |
+
# elan-spp block
|
91 |
+
[9, 1, SPPELAN, [512, 256]], # 29
|
92 |
+
|
93 |
+
# up-concat merge
|
94 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
95 |
+
[[-1, 7], 1, Concat, [1]], # cat backbone P4
|
96 |
+
|
97 |
+
# csp-elan block
|
98 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 2]], # 32
|
99 |
+
|
100 |
+
# up-concat merge
|
101 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
102 |
+
[[-1, 5], 1, Concat, [1]], # cat backbone P3
|
103 |
+
|
104 |
+
# csp-elan block
|
105 |
+
[-1, 1, RepNCSPELAN4, [256, 256, 128, 2]], # 35
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
# main branch
|
110 |
+
|
111 |
+
# elan-spp block
|
112 |
+
[28, 1, SPPELAN, [512, 256]], # 36
|
113 |
+
|
114 |
+
# up-concat merge
|
115 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
116 |
+
[[-1, 25], 1, Concat, [1]], # cat backbone P4
|
117 |
+
|
118 |
+
# csp-elan block
|
119 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 2]], # 39
|
120 |
+
|
121 |
+
# up-concat merge
|
122 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
123 |
+
[[-1, 22], 1, Concat, [1]], # cat backbone P3
|
124 |
+
|
125 |
+
# csp-elan block
|
126 |
+
[-1, 1, RepNCSPELAN4, [256, 256, 128, 2]], # 42 (P3/8-small)
|
127 |
+
|
128 |
+
# avg-conv-down merge
|
129 |
+
[-1, 1, ADown, [256]],
|
130 |
+
[[-1, 39], 1, Concat, [1]], # cat head P4
|
131 |
+
|
132 |
+
# csp-elan block
|
133 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 2]], # 45 (P4/16-medium)
|
134 |
+
|
135 |
+
# avg-conv-down merge
|
136 |
+
[-1, 1, ADown, [512]],
|
137 |
+
[[-1, 36], 1, Concat, [1]], # cat head P5
|
138 |
+
|
139 |
+
# csp-elan block
|
140 |
+
[-1, 1, RepNCSPELAN4, [512, 1024, 512, 2]], # 48 (P5/32-large)
|
141 |
+
|
142 |
+
# detect
|
143 |
+
[[35, 32, 29, 42, 45, 48], 1, DualDDetect, [nc]], # DualDDetect(A3, A4, A5, P3, P4, P5)
|
144 |
+
]
|
models/detect/yolov9.yaml
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv9
|
2 |
+
|
3 |
+
# parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
#activation: nn.LeakyReLU(0.1)
|
8 |
+
#activation: nn.ReLU()
|
9 |
+
|
10 |
+
# anchors
|
11 |
+
anchors: 3
|
12 |
+
|
13 |
+
# YOLOv9 backbone
|
14 |
+
backbone:
|
15 |
+
[
|
16 |
+
[-1, 1, Silence, []],
|
17 |
+
|
18 |
+
# conv down
|
19 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
20 |
+
|
21 |
+
# conv down
|
22 |
+
[-1, 1, Conv, [128, 3, 2]], # 2-P2/4
|
23 |
+
|
24 |
+
# elan-1 block
|
25 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 1]], # 3
|
26 |
+
|
27 |
+
# conv down
|
28 |
+
[-1, 1, Conv, [256, 3, 2]], # 4-P3/8
|
29 |
+
|
30 |
+
# elan-2 block
|
31 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 1]], # 5
|
32 |
+
|
33 |
+
# conv down
|
34 |
+
[-1, 1, Conv, [512, 3, 2]], # 6-P4/16
|
35 |
+
|
36 |
+
# elan-2 block
|
37 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 7
|
38 |
+
|
39 |
+
# conv down
|
40 |
+
[-1, 1, Conv, [512, 3, 2]], # 8-P5/32
|
41 |
+
|
42 |
+
# elan-2 block
|
43 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 9
|
44 |
+
]
|
45 |
+
|
46 |
+
# YOLOv9 head
|
47 |
+
head:
|
48 |
+
[
|
49 |
+
# elan-spp block
|
50 |
+
[-1, 1, SPPELAN, [512, 256]], # 10
|
51 |
+
|
52 |
+
# up-concat merge
|
53 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
54 |
+
[[-1, 7], 1, Concat, [1]], # cat backbone P4
|
55 |
+
|
56 |
+
# elan-2 block
|
57 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 13
|
58 |
+
|
59 |
+
# up-concat merge
|
60 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
61 |
+
[[-1, 5], 1, Concat, [1]], # cat backbone P3
|
62 |
+
|
63 |
+
# elan-2 block
|
64 |
+
[-1, 1, RepNCSPELAN4, [256, 256, 128, 1]], # 16 (P3/8-small)
|
65 |
+
|
66 |
+
# conv-down merge
|
67 |
+
[-1, 1, Conv, [256, 3, 2]],
|
68 |
+
[[-1, 13], 1, Concat, [1]], # cat head P4
|
69 |
+
|
70 |
+
# elan-2 block
|
71 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 19 (P4/16-medium)
|
72 |
+
|
73 |
+
# conv-down merge
|
74 |
+
[-1, 1, Conv, [512, 3, 2]],
|
75 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
76 |
+
|
77 |
+
# elan-2 block
|
78 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 22 (P5/32-large)
|
79 |
+
|
80 |
+
# routing
|
81 |
+
[5, 1, CBLinear, [[256]]], # 23
|
82 |
+
[7, 1, CBLinear, [[256, 512]]], # 24
|
83 |
+
[9, 1, CBLinear, [[256, 512, 512]]], # 25
|
84 |
+
|
85 |
+
# conv down
|
86 |
+
[0, 1, Conv, [64, 3, 2]], # 26-P1/2
|
87 |
+
|
88 |
+
# conv down
|
89 |
+
[-1, 1, Conv, [128, 3, 2]], # 27-P2/4
|
90 |
+
|
91 |
+
# elan-1 block
|
92 |
+
[-1, 1, RepNCSPELAN4, [256, 128, 64, 1]], # 28
|
93 |
+
|
94 |
+
# conv down fuse
|
95 |
+
[-1, 1, Conv, [256, 3, 2]], # 29-P3/8
|
96 |
+
[[23, 24, 25, -1], 1, CBFuse, [[0, 0, 0]]], # 30
|
97 |
+
|
98 |
+
# elan-2 block
|
99 |
+
[-1, 1, RepNCSPELAN4, [512, 256, 128, 1]], # 31
|
100 |
+
|
101 |
+
# conv down fuse
|
102 |
+
[-1, 1, Conv, [512, 3, 2]], # 32-P4/16
|
103 |
+
[[24, 25, -1], 1, CBFuse, [[1, 1]]], # 33
|
104 |
+
|
105 |
+
# elan-2 block
|
106 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 34
|
107 |
+
|
108 |
+
# conv down fuse
|
109 |
+
[-1, 1, Conv, [512, 3, 2]], # 35-P5/32
|
110 |
+
[[25, -1], 1, CBFuse, [[2]]], # 36
|
111 |
+
|
112 |
+
# elan-2 block
|
113 |
+
[-1, 1, RepNCSPELAN4, [512, 512, 256, 1]], # 37
|
114 |
+
|
115 |
+
# detect
|
116 |
+
[[31, 34, 37, 16, 19, 22], 1, DualDDetect, [nc]], # DualDDetect(A3, A4, A5, P3, P4, P5)
|
117 |
+
]
|
models/experimental.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
|
7 |
+
from utils.downloads import attempt_download
|
8 |
+
|
9 |
+
|
10 |
+
class Sum(nn.Module):
|
11 |
+
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
12 |
+
def __init__(self, n, weight=False): # n: number of inputs
|
13 |
+
super().__init__()
|
14 |
+
self.weight = weight # apply weights boolean
|
15 |
+
self.iter = range(n - 1) # iter object
|
16 |
+
if weight:
|
17 |
+
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
18 |
+
|
19 |
+
def forward(self, x):
|
20 |
+
y = x[0] # no weight
|
21 |
+
if self.weight:
|
22 |
+
w = torch.sigmoid(self.w) * 2
|
23 |
+
for i in self.iter:
|
24 |
+
y = y + x[i + 1] * w[i]
|
25 |
+
else:
|
26 |
+
for i in self.iter:
|
27 |
+
y = y + x[i + 1]
|
28 |
+
return y
|
29 |
+
|
30 |
+
|
31 |
+
class MixConv2d(nn.Module):
|
32 |
+
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
33 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
34 |
+
super().__init__()
|
35 |
+
n = len(k) # number of convolutions
|
36 |
+
if equal_ch: # equal c_ per group
|
37 |
+
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
38 |
+
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
39 |
+
else: # equal weight.numel() per group
|
40 |
+
b = [c2] + [0] * n
|
41 |
+
a = np.eye(n + 1, n, k=-1)
|
42 |
+
a -= np.roll(a, 1, axis=1)
|
43 |
+
a *= np.array(k) ** 2
|
44 |
+
a[0] = 1
|
45 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
46 |
+
|
47 |
+
self.m = nn.ModuleList([
|
48 |
+
nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
49 |
+
self.bn = nn.BatchNorm2d(c2)
|
50 |
+
self.act = nn.SiLU()
|
51 |
+
|
52 |
+
def forward(self, x):
|
53 |
+
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
54 |
+
|
55 |
+
|
56 |
+
class Ensemble(nn.ModuleList):
|
57 |
+
# Ensemble of models
|
58 |
+
def __init__(self):
|
59 |
+
super().__init__()
|
60 |
+
|
61 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
62 |
+
y = [module(x, augment, profile, visualize)[0] for module in self]
|
63 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
64 |
+
# y = torch.stack(y).mean(0) # mean ensemble
|
65 |
+
y = torch.cat(y, 1) # nms ensemble
|
66 |
+
return y, None # inference, train output
|
67 |
+
|
68 |
+
|
69 |
+
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
70 |
+
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
71 |
+
from models.yolo import Detect, Model
|
72 |
+
|
73 |
+
model = Ensemble()
|
74 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
75 |
+
ckpt = torch.load(attempt_download(w), map_location='cpu') # load
|
76 |
+
ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
|
77 |
+
|
78 |
+
# Model compatibility updates
|
79 |
+
if not hasattr(ckpt, 'stride'):
|
80 |
+
ckpt.stride = torch.tensor([32.])
|
81 |
+
if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):
|
82 |
+
ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
|
83 |
+
|
84 |
+
model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode
|
85 |
+
|
86 |
+
# Module compatibility updates
|
87 |
+
for m in model.modules():
|
88 |
+
t = type(m)
|
89 |
+
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
90 |
+
m.inplace = inplace # torch 1.7.0 compatibility
|
91 |
+
# if t is Detect and not isinstance(m.anchor_grid, list):
|
92 |
+
# delattr(m, 'anchor_grid')
|
93 |
+
# setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
94 |
+
elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
|
95 |
+
m.recompute_scale_factor = None # torch 1.11.0 compatibility
|
96 |
+
|
97 |
+
# Return model
|
98 |
+
if len(model) == 1:
|
99 |
+
return model[-1]
|
100 |
+
|
101 |
+
# Return detection ensemble
|
102 |
+
print(f'Ensemble created with {weights}\n')
|
103 |
+
for k in 'names', 'nc', 'yaml':
|
104 |
+
setattr(model, k, getattr(model[0], k))
|
105 |
+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
106 |
+
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
|
107 |
+
return model
|
models/hub/anchors.yaml
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv3 & YOLOv5
|
2 |
+
# Default anchors for COCO data
|
3 |
+
|
4 |
+
|
5 |
+
# P5 -------------------------------------------------------------------------------------------------------------------
|
6 |
+
# P5-640:
|
7 |
+
anchors_p5_640:
|
8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
11 |
+
|
12 |
+
|
13 |
+
# P6 -------------------------------------------------------------------------------------------------------------------
|
14 |
+
# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
|
15 |
+
anchors_p6_640:
|
16 |
+
- [9,11, 21,19, 17,41] # P3/8
|
17 |
+
- [43,32, 39,70, 86,64] # P4/16
|
18 |
+
- [65,131, 134,130, 120,265] # P5/32
|
19 |
+
- [282,180, 247,354, 512,387] # P6/64
|
20 |
+
|
21 |
+
# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
|
22 |
+
anchors_p6_1280:
|
23 |
+
- [19,27, 44,40, 38,94] # P3/8
|
24 |
+
- [96,68, 86,152, 180,137] # P4/16
|
25 |
+
- [140,301, 303,264, 238,542] # P5/32
|
26 |
+
- [436,615, 739,380, 925,792] # P6/64
|
27 |
+
|
28 |
+
# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
|
29 |
+
anchors_p6_1920:
|
30 |
+
- [28,41, 67,59, 57,141] # P3/8
|
31 |
+
- [144,103, 129,227, 270,205] # P4/16
|
32 |
+
- [209,452, 455,396, 358,812] # P5/32
|
33 |
+
- [653,922, 1109,570, 1387,1187] # P6/64
|
34 |
+
|
35 |
+
|
36 |
+
# P7 -------------------------------------------------------------------------------------------------------------------
|
37 |
+
# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
|
38 |
+
anchors_p7_640:
|
39 |
+
- [11,11, 13,30, 29,20] # P3/8
|
40 |
+
- [30,46, 61,38, 39,92] # P4/16
|
41 |
+
- [78,80, 146,66, 79,163] # P5/32
|
42 |
+
- [149,150, 321,143, 157,303] # P6/64
|
43 |
+
- [257,402, 359,290, 524,372] # P7/128
|
44 |
+
|
45 |
+
# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
|
46 |
+
anchors_p7_1280:
|
47 |
+
- [19,22, 54,36, 32,77] # P3/8
|
48 |
+
- [70,83, 138,71, 75,173] # P4/16
|
49 |
+
- [165,159, 148,334, 375,151] # P5/32
|
50 |
+
- [334,317, 251,626, 499,474] # P6/64
|
51 |
+
- [750,326, 534,814, 1079,818] # P7/128
|
52 |
+
|
53 |
+
# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
|
54 |
+
anchors_p7_1920:
|
55 |
+
- [29,34, 81,55, 47,115] # P3/8
|
56 |
+
- [105,124, 207,107, 113,259] # P4/16
|
57 |
+
- [247,238, 222,500, 563,227] # P5/32
|
58 |
+
- [501,476, 376,939, 749,711] # P6/64
|
59 |
+
- [1126,489, 801,1222, 1618,1227] # P7/128
|
models/hub/yolov3-spp.yaml
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv3
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
11 |
+
|
12 |
+
# darknet53 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
16 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
17 |
+
[-1, 1, Bottleneck, [64]],
|
18 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
19 |
+
[-1, 2, Bottleneck, [128]],
|
20 |
+
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
21 |
+
[-1, 8, Bottleneck, [256]],
|
22 |
+
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
23 |
+
[-1, 8, Bottleneck, [512]],
|
24 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
25 |
+
[-1, 4, Bottleneck, [1024]], # 10
|
26 |
+
]
|
27 |
+
|
28 |
+
# YOLOv3-SPP head
|
29 |
+
head:
|
30 |
+
[[-1, 1, Bottleneck, [1024, False]],
|
31 |
+
[-1, 1, SPP, [512, [5, 9, 13]]],
|
32 |
+
[-1, 1, Conv, [1024, 3, 1]],
|
33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
34 |
+
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
35 |
+
|
36 |
+
[-2, 1, Conv, [256, 1, 1]],
|
37 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
38 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
39 |
+
[-1, 1, Bottleneck, [512, False]],
|
40 |
+
[-1, 1, Bottleneck, [512, False]],
|
41 |
+
[-1, 1, Conv, [256, 1, 1]],
|
42 |
+
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
43 |
+
|
44 |
+
[-2, 1, Conv, [128, 1, 1]],
|
45 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
46 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
47 |
+
[-1, 1, Bottleneck, [256, False]],
|
48 |
+
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
49 |
+
|
50 |
+
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
51 |
+
]
|
models/hub/yolov3-tiny.yaml
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv3
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [10,14, 23,27, 37,58] # P4/16
|
9 |
+
- [81,82, 135,169, 344,319] # P5/32
|
10 |
+
|
11 |
+
# YOLOv3-tiny backbone
|
12 |
+
backbone:
|
13 |
+
# [from, number, module, args]
|
14 |
+
[[-1, 1, Conv, [16, 3, 1]], # 0
|
15 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
|
16 |
+
[-1, 1, Conv, [32, 3, 1]],
|
17 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
|
18 |
+
[-1, 1, Conv, [64, 3, 1]],
|
19 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
|
20 |
+
[-1, 1, Conv, [128, 3, 1]],
|
21 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
|
22 |
+
[-1, 1, Conv, [256, 3, 1]],
|
23 |
+
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
|
24 |
+
[-1, 1, Conv, [512, 3, 1]],
|
25 |
+
[-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
|
26 |
+
[-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
|
27 |
+
]
|
28 |
+
|
29 |
+
# YOLOv3-tiny head
|
30 |
+
head:
|
31 |
+
[[-1, 1, Conv, [1024, 3, 1]],
|
32 |
+
[-1, 1, Conv, [256, 1, 1]],
|
33 |
+
[-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
|
34 |
+
|
35 |
+
[-2, 1, Conv, [128, 1, 1]],
|
36 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
37 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
38 |
+
[-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
|
39 |
+
|
40 |
+
[[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
|
41 |
+
]
|
models/hub/yolov3.yaml
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv3
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors:
|
8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
11 |
+
|
12 |
+
# darknet53 backbone
|
13 |
+
backbone:
|
14 |
+
# [from, number, module, args]
|
15 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
16 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
17 |
+
[-1, 1, Bottleneck, [64]],
|
18 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
19 |
+
[-1, 2, Bottleneck, [128]],
|
20 |
+
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
21 |
+
[-1, 8, Bottleneck, [256]],
|
22 |
+
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
23 |
+
[-1, 8, Bottleneck, [512]],
|
24 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
25 |
+
[-1, 4, Bottleneck, [1024]], # 10
|
26 |
+
]
|
27 |
+
|
28 |
+
# YOLOv3 head
|
29 |
+
head:
|
30 |
+
[[-1, 1, Bottleneck, [1024, False]],
|
31 |
+
[-1, 1, Conv, [512, 1, 1]],
|
32 |
+
[-1, 1, Conv, [1024, 3, 1]],
|
33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
34 |
+
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
35 |
+
|
36 |
+
[-2, 1, Conv, [256, 1, 1]],
|
37 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
38 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
39 |
+
[-1, 1, Bottleneck, [512, False]],
|
40 |
+
[-1, 1, Bottleneck, [512, False]],
|
41 |
+
[-1, 1, Conv, [256, 1, 1]],
|
42 |
+
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
43 |
+
|
44 |
+
[-2, 1, Conv, [128, 1, 1]],
|
45 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
46 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
47 |
+
[-1, 1, Bottleneck, [256, False]],
|
48 |
+
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
49 |
+
|
50 |
+
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
51 |
+
]
|
models/panoptic/yolov7-af-pan.yaml
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv7
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
sem_nc: 93 # number of stuff classes
|
6 |
+
depth_multiple: 1.0 # model depth multiple
|
7 |
+
width_multiple: 1.0 # layer channel multiple
|
8 |
+
anchors: 3
|
9 |
+
|
10 |
+
# YOLOv7 backbone
|
11 |
+
backbone:
|
12 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
13 |
+
|
14 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
15 |
+
[-1, 1, Conv, [64, 3, 1]],
|
16 |
+
|
17 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
18 |
+
[-1, 1, Conv, [64, 1, 1]],
|
19 |
+
[-2, 1, Conv, [64, 1, 1]],
|
20 |
+
[-1, 1, Conv, [64, 3, 1]],
|
21 |
+
[-1, 1, Conv, [64, 3, 1]],
|
22 |
+
[-1, 1, Conv, [64, 3, 1]],
|
23 |
+
[-1, 1, Conv, [64, 3, 1]],
|
24 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
25 |
+
[-1, 1, Conv, [256, 1, 1]], # 11
|
26 |
+
|
27 |
+
[-1, 1, MP, []],
|
28 |
+
[-1, 1, Conv, [128, 1, 1]],
|
29 |
+
[-3, 1, Conv, [128, 1, 1]],
|
30 |
+
[-1, 1, Conv, [128, 3, 2]],
|
31 |
+
[[-1, -3], 1, Concat, [1]], # 16-P3/8
|
32 |
+
[-1, 1, Conv, [128, 1, 1]],
|
33 |
+
[-2, 1, Conv, [128, 1, 1]],
|
34 |
+
[-1, 1, Conv, [128, 3, 1]],
|
35 |
+
[-1, 1, Conv, [128, 3, 1]],
|
36 |
+
[-1, 1, Conv, [128, 3, 1]],
|
37 |
+
[-1, 1, Conv, [128, 3, 1]],
|
38 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
39 |
+
[-1, 1, Conv, [512, 1, 1]], # 24
|
40 |
+
|
41 |
+
[-1, 1, MP, []],
|
42 |
+
[-1, 1, Conv, [256, 1, 1]],
|
43 |
+
[-3, 1, Conv, [256, 1, 1]],
|
44 |
+
[-1, 1, Conv, [256, 3, 2]],
|
45 |
+
[[-1, -3], 1, Concat, [1]], # 29-P4/16
|
46 |
+
[-1, 1, Conv, [256, 1, 1]],
|
47 |
+
[-2, 1, Conv, [256, 1, 1]],
|
48 |
+
[-1, 1, Conv, [256, 3, 1]],
|
49 |
+
[-1, 1, Conv, [256, 3, 1]],
|
50 |
+
[-1, 1, Conv, [256, 3, 1]],
|
51 |
+
[-1, 1, Conv, [256, 3, 1]],
|
52 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
53 |
+
[-1, 1, Conv, [1024, 1, 1]], # 37
|
54 |
+
|
55 |
+
[-1, 1, MP, []],
|
56 |
+
[-1, 1, Conv, [512, 1, 1]],
|
57 |
+
[-3, 1, Conv, [512, 1, 1]],
|
58 |
+
[-1, 1, Conv, [512, 3, 2]],
|
59 |
+
[[-1, -3], 1, Concat, [1]], # 42-P5/32
|
60 |
+
[-1, 1, Conv, [256, 1, 1]],
|
61 |
+
[-2, 1, Conv, [256, 1, 1]],
|
62 |
+
[-1, 1, Conv, [256, 3, 1]],
|
63 |
+
[-1, 1, Conv, [256, 3, 1]],
|
64 |
+
[-1, 1, Conv, [256, 3, 1]],
|
65 |
+
[-1, 1, Conv, [256, 3, 1]],
|
66 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
67 |
+
[-1, 1, Conv, [1024, 1, 1]], # 50
|
68 |
+
]
|
69 |
+
|
70 |
+
# yolov7 head
|
71 |
+
head:
|
72 |
+
[[-1, 1, SPPCSPC, [512]], # 51
|
73 |
+
|
74 |
+
[-1, 1, Conv, [256, 1, 1]],
|
75 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
76 |
+
[37, 1, Conv, [256, 1, 1]], # route backbone P4
|
77 |
+
[[-1, -2], 1, Concat, [1]],
|
78 |
+
|
79 |
+
[-1, 1, Conv, [256, 1, 1]],
|
80 |
+
[-2, 1, Conv, [256, 1, 1]],
|
81 |
+
[-1, 1, Conv, [128, 3, 1]],
|
82 |
+
[-1, 1, Conv, [128, 3, 1]],
|
83 |
+
[-1, 1, Conv, [128, 3, 1]],
|
84 |
+
[-1, 1, Conv, [128, 3, 1]],
|
85 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
86 |
+
[-1, 1, Conv, [256, 1, 1]], # 63
|
87 |
+
|
88 |
+
[-1, 1, Conv, [128, 1, 1]],
|
89 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
90 |
+
[24, 1, Conv, [128, 1, 1]], # route backbone P3
|
91 |
+
[[-1, -2], 1, Concat, [1]],
|
92 |
+
|
93 |
+
[-1, 1, Conv, [128, 1, 1]],
|
94 |
+
[-2, 1, Conv, [128, 1, 1]],
|
95 |
+
[-1, 1, Conv, [64, 3, 1]],
|
96 |
+
[-1, 1, Conv, [64, 3, 1]],
|
97 |
+
[-1, 1, Conv, [64, 3, 1]],
|
98 |
+
[-1, 1, Conv, [64, 3, 1]],
|
99 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
100 |
+
[-1, 1, Conv, [128, 1, 1]], # 75
|
101 |
+
|
102 |
+
[-1, 1, MP, []],
|
103 |
+
[-1, 1, Conv, [128, 1, 1]],
|
104 |
+
[-3, 1, Conv, [128, 1, 1]],
|
105 |
+
[-1, 1, Conv, [128, 3, 2]],
|
106 |
+
[[-1, -3, 63], 1, Concat, [1]],
|
107 |
+
|
108 |
+
[-1, 1, Conv, [256, 1, 1]],
|
109 |
+
[-2, 1, Conv, [256, 1, 1]],
|
110 |
+
[-1, 1, Conv, [128, 3, 1]],
|
111 |
+
[-1, 1, Conv, [128, 3, 1]],
|
112 |
+
[-1, 1, Conv, [128, 3, 1]],
|
113 |
+
[-1, 1, Conv, [128, 3, 1]],
|
114 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
115 |
+
[-1, 1, Conv, [256, 1, 1]], # 88
|
116 |
+
|
117 |
+
[-1, 1, MP, []],
|
118 |
+
[-1, 1, Conv, [256, 1, 1]],
|
119 |
+
[-3, 1, Conv, [256, 1, 1]],
|
120 |
+
[-1, 1, Conv, [256, 3, 2]],
|
121 |
+
[[-1, -3, 51], 1, Concat, [1]],
|
122 |
+
|
123 |
+
[-1, 1, Conv, [512, 1, 1]],
|
124 |
+
[-2, 1, Conv, [512, 1, 1]],
|
125 |
+
[-1, 1, Conv, [256, 3, 1]],
|
126 |
+
[-1, 1, Conv, [256, 3, 1]],
|
127 |
+
[-1, 1, Conv, [256, 3, 1]],
|
128 |
+
[-1, 1, Conv, [256, 3, 1]],
|
129 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
130 |
+
[-1, 1, Conv, [512, 1, 1]], # 101
|
131 |
+
|
132 |
+
[75, 1, Conv, [256, 3, 1]],
|
133 |
+
[88, 1, Conv, [512, 3, 1]],
|
134 |
+
[101, 1, Conv, [1024, 3, 1]],
|
135 |
+
|
136 |
+
[[102, 103, 104], 1, Panoptic, [nc, 93, 32, 256]], # Panoptic(P3, P4, P5)
|
137 |
+
]
|
models/segment/yolov7-af-seg.yaml
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv7
|
2 |
+
|
3 |
+
# Parameters
|
4 |
+
nc: 80 # number of classes
|
5 |
+
depth_multiple: 1.0 # model depth multiple
|
6 |
+
width_multiple: 1.0 # layer channel multiple
|
7 |
+
anchors: 3
|
8 |
+
|
9 |
+
# YOLOv7 backbone
|
10 |
+
backbone:
|
11 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
12 |
+
|
13 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
14 |
+
[-1, 1, Conv, [64, 3, 1]],
|
15 |
+
|
16 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
17 |
+
[-1, 1, Conv, [64, 1, 1]],
|
18 |
+
[-2, 1, Conv, [64, 1, 1]],
|
19 |
+
[-1, 1, Conv, [64, 3, 1]],
|
20 |
+
[-1, 1, Conv, [64, 3, 1]],
|
21 |
+
[-1, 1, Conv, [64, 3, 1]],
|
22 |
+
[-1, 1, Conv, [64, 3, 1]],
|
23 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
24 |
+
[-1, 1, Conv, [256, 1, 1]], # 11
|
25 |
+
|
26 |
+
[-1, 1, MP, []],
|
27 |
+
[-1, 1, Conv, [128, 1, 1]],
|
28 |
+
[-3, 1, Conv, [128, 1, 1]],
|
29 |
+
[-1, 1, Conv, [128, 3, 2]],
|
30 |
+
[[-1, -3], 1, Concat, [1]], # 16-P3/8
|
31 |
+
[-1, 1, Conv, [128, 1, 1]],
|
32 |
+
[-2, 1, Conv, [128, 1, 1]],
|
33 |
+
[-1, 1, Conv, [128, 3, 1]],
|
34 |
+
[-1, 1, Conv, [128, 3, 1]],
|
35 |
+
[-1, 1, Conv, [128, 3, 1]],
|
36 |
+
[-1, 1, Conv, [128, 3, 1]],
|
37 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
38 |
+
[-1, 1, Conv, [512, 1, 1]], # 24
|
39 |
+
|
40 |
+
[-1, 1, MP, []],
|
41 |
+
[-1, 1, Conv, [256, 1, 1]],
|
42 |
+
[-3, 1, Conv, [256, 1, 1]],
|
43 |
+
[-1, 1, Conv, [256, 3, 2]],
|
44 |
+
[[-1, -3], 1, Concat, [1]], # 29-P4/16
|
45 |
+
[-1, 1, Conv, [256, 1, 1]],
|
46 |
+
[-2, 1, Conv, [256, 1, 1]],
|
47 |
+
[-1, 1, Conv, [256, 3, 1]],
|
48 |
+
[-1, 1, Conv, [256, 3, 1]],
|
49 |
+
[-1, 1, Conv, [256, 3, 1]],
|
50 |
+
[-1, 1, Conv, [256, 3, 1]],
|
51 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
52 |
+
[-1, 1, Conv, [1024, 1, 1]], # 37
|
53 |
+
|
54 |
+
[-1, 1, MP, []],
|
55 |
+
[-1, 1, Conv, [512, 1, 1]],
|
56 |
+
[-3, 1, Conv, [512, 1, 1]],
|
57 |
+
[-1, 1, Conv, [512, 3, 2]],
|
58 |
+
[[-1, -3], 1, Concat, [1]], # 42-P5/32
|
59 |
+
[-1, 1, Conv, [256, 1, 1]],
|
60 |
+
[-2, 1, Conv, [256, 1, 1]],
|
61 |
+
[-1, 1, Conv, [256, 3, 1]],
|
62 |
+
[-1, 1, Conv, [256, 3, 1]],
|
63 |
+
[-1, 1, Conv, [256, 3, 1]],
|
64 |
+
[-1, 1, Conv, [256, 3, 1]],
|
65 |
+
[[-1, -3, -5, -6], 1, Concat, [1]],
|
66 |
+
[-1, 1, Conv, [1024, 1, 1]], # 50
|
67 |
+
]
|
68 |
+
|
69 |
+
# yolov7 head
|
70 |
+
head:
|
71 |
+
[[-1, 1, SPPCSPC, [512]], # 51
|
72 |
+
|
73 |
+
[-1, 1, Conv, [256, 1, 1]],
|
74 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
75 |
+
[37, 1, Conv, [256, 1, 1]], # route backbone P4
|
76 |
+
[[-1, -2], 1, Concat, [1]],
|
77 |
+
|
78 |
+
[-1, 1, Conv, [256, 1, 1]],
|
79 |
+
[-2, 1, Conv, [256, 1, 1]],
|
80 |
+
[-1, 1, Conv, [128, 3, 1]],
|
81 |
+
[-1, 1, Conv, [128, 3, 1]],
|
82 |
+
[-1, 1, Conv, [128, 3, 1]],
|
83 |
+
[-1, 1, Conv, [128, 3, 1]],
|
84 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
85 |
+
[-1, 1, Conv, [256, 1, 1]], # 63
|
86 |
+
|
87 |
+
[-1, 1, Conv, [128, 1, 1]],
|
88 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
89 |
+
[24, 1, Conv, [128, 1, 1]], # route backbone P3
|
90 |
+
[[-1, -2], 1, Concat, [1]],
|
91 |
+
|
92 |
+
[-1, 1, Conv, [128, 1, 1]],
|
93 |
+
[-2, 1, Conv, [128, 1, 1]],
|
94 |
+
[-1, 1, Conv, [64, 3, 1]],
|
95 |
+
[-1, 1, Conv, [64, 3, 1]],
|
96 |
+
[-1, 1, Conv, [64, 3, 1]],
|
97 |
+
[-1, 1, Conv, [64, 3, 1]],
|
98 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
99 |
+
[-1, 1, Conv, [128, 1, 1]], # 75
|
100 |
+
|
101 |
+
[-1, 1, MP, []],
|
102 |
+
[-1, 1, Conv, [128, 1, 1]],
|
103 |
+
[-3, 1, Conv, [128, 1, 1]],
|
104 |
+
[-1, 1, Conv, [128, 3, 2]],
|
105 |
+
[[-1, -3, 63], 1, Concat, [1]],
|
106 |
+
|
107 |
+
[-1, 1, Conv, [256, 1, 1]],
|
108 |
+
[-2, 1, Conv, [256, 1, 1]],
|
109 |
+
[-1, 1, Conv, [128, 3, 1]],
|
110 |
+
[-1, 1, Conv, [128, 3, 1]],
|
111 |
+
[-1, 1, Conv, [128, 3, 1]],
|
112 |
+
[-1, 1, Conv, [128, 3, 1]],
|
113 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
114 |
+
[-1, 1, Conv, [256, 1, 1]], # 88
|
115 |
+
|
116 |
+
[-1, 1, MP, []],
|
117 |
+
[-1, 1, Conv, [256, 1, 1]],
|
118 |
+
[-3, 1, Conv, [256, 1, 1]],
|
119 |
+
[-1, 1, Conv, [256, 3, 2]],
|
120 |
+
[[-1, -3, 51], 1, Concat, [1]],
|
121 |
+
|
122 |
+
[-1, 1, Conv, [512, 1, 1]],
|
123 |
+
[-2, 1, Conv, [512, 1, 1]],
|
124 |
+
[-1, 1, Conv, [256, 3, 1]],
|
125 |
+
[-1, 1, Conv, [256, 3, 1]],
|
126 |
+
[-1, 1, Conv, [256, 3, 1]],
|
127 |
+
[-1, 1, Conv, [256, 3, 1]],
|
128 |
+
[[-1, -2, -3, -4, -5, -6], 1, Concat, [1]],
|
129 |
+
[-1, 1, Conv, [512, 1, 1]], # 101
|
130 |
+
|
131 |
+
[75, 1, Conv, [256, 3, 1]],
|
132 |
+
[88, 1, Conv, [512, 3, 1]],
|
133 |
+
[101, 1, Conv, [1024, 3, 1]],
|
134 |
+
|
135 |
+
[[102, 103, 104], 1, Segment, [nc, 32, 256]], # Segment(P3, P4, P5)
|
136 |
+
]
|
models/tf.py
ADDED
@@ -0,0 +1,596 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
from copy import deepcopy
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
FILE = Path(__file__).resolve()
|
7 |
+
ROOT = FILE.parents[1] # YOLO root directory
|
8 |
+
if str(ROOT) not in sys.path:
|
9 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
10 |
+
# ROOT = ROOT.relative_to(Path.cwd()) # relative
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
import tensorflow as tf
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
from tensorflow import keras
|
17 |
+
|
18 |
+
from models.common import (C3, SPP, SPPF, Bottleneck, BottleneckCSP, C3x, Concat, Conv, CrossConv, DWConv,
|
19 |
+
DWConvTranspose2d, Focus, autopad)
|
20 |
+
from models.experimental import MixConv2d, attempt_load
|
21 |
+
from models.yolo import Detect, Segment
|
22 |
+
from utils.activations import SiLU
|
23 |
+
from utils.general import LOGGER, make_divisible, print_args
|
24 |
+
|
25 |
+
|
26 |
+
class TFBN(keras.layers.Layer):
|
27 |
+
# TensorFlow BatchNormalization wrapper
|
28 |
+
def __init__(self, w=None):
|
29 |
+
super().__init__()
|
30 |
+
self.bn = keras.layers.BatchNormalization(
|
31 |
+
beta_initializer=keras.initializers.Constant(w.bias.numpy()),
|
32 |
+
gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
|
33 |
+
moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
|
34 |
+
moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
|
35 |
+
epsilon=w.eps)
|
36 |
+
|
37 |
+
def call(self, inputs):
|
38 |
+
return self.bn(inputs)
|
39 |
+
|
40 |
+
|
41 |
+
class TFPad(keras.layers.Layer):
|
42 |
+
# Pad inputs in spatial dimensions 1 and 2
|
43 |
+
def __init__(self, pad):
|
44 |
+
super().__init__()
|
45 |
+
if isinstance(pad, int):
|
46 |
+
self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
|
47 |
+
else: # tuple/list
|
48 |
+
self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]])
|
49 |
+
|
50 |
+
def call(self, inputs):
|
51 |
+
return tf.pad(inputs, self.pad, mode='constant', constant_values=0)
|
52 |
+
|
53 |
+
|
54 |
+
class TFConv(keras.layers.Layer):
|
55 |
+
# Standard convolution
|
56 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
|
57 |
+
# ch_in, ch_out, weights, kernel, stride, padding, groups
|
58 |
+
super().__init__()
|
59 |
+
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
|
60 |
+
# TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
|
61 |
+
# see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
|
62 |
+
conv = keras.layers.Conv2D(
|
63 |
+
filters=c2,
|
64 |
+
kernel_size=k,
|
65 |
+
strides=s,
|
66 |
+
padding='SAME' if s == 1 else 'VALID',
|
67 |
+
use_bias=not hasattr(w, 'bn'),
|
68 |
+
kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
|
69 |
+
bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
|
70 |
+
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
|
71 |
+
self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
|
72 |
+
self.act = activations(w.act) if act else tf.identity
|
73 |
+
|
74 |
+
def call(self, inputs):
|
75 |
+
return self.act(self.bn(self.conv(inputs)))
|
76 |
+
|
77 |
+
|
78 |
+
class TFDWConv(keras.layers.Layer):
|
79 |
+
# Depthwise convolution
|
80 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None):
|
81 |
+
# ch_in, ch_out, weights, kernel, stride, padding, groups
|
82 |
+
super().__init__()
|
83 |
+
assert c2 % c1 == 0, f'TFDWConv() output={c2} must be a multiple of input={c1} channels'
|
84 |
+
conv = keras.layers.DepthwiseConv2D(
|
85 |
+
kernel_size=k,
|
86 |
+
depth_multiplier=c2 // c1,
|
87 |
+
strides=s,
|
88 |
+
padding='SAME' if s == 1 else 'VALID',
|
89 |
+
use_bias=not hasattr(w, 'bn'),
|
90 |
+
depthwise_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
|
91 |
+
bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))
|
92 |
+
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
|
93 |
+
self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity
|
94 |
+
self.act = activations(w.act) if act else tf.identity
|
95 |
+
|
96 |
+
def call(self, inputs):
|
97 |
+
return self.act(self.bn(self.conv(inputs)))
|
98 |
+
|
99 |
+
|
100 |
+
class TFDWConvTranspose2d(keras.layers.Layer):
|
101 |
+
# Depthwise ConvTranspose2d
|
102 |
+
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None):
|
103 |
+
# ch_in, ch_out, weights, kernel, stride, padding, groups
|
104 |
+
super().__init__()
|
105 |
+
assert c1 == c2, f'TFDWConv() output={c2} must be equal to input={c1} channels'
|
106 |
+
assert k == 4 and p1 == 1, 'TFDWConv() only valid for k=4 and p1=1'
|
107 |
+
weight, bias = w.weight.permute(2, 3, 1, 0).numpy(), w.bias.numpy()
|
108 |
+
self.c1 = c1
|
109 |
+
self.conv = [
|
110 |
+
keras.layers.Conv2DTranspose(filters=1,
|
111 |
+
kernel_size=k,
|
112 |
+
strides=s,
|
113 |
+
padding='VALID',
|
114 |
+
output_padding=p2,
|
115 |
+
use_bias=True,
|
116 |
+
kernel_initializer=keras.initializers.Constant(weight[..., i:i + 1]),
|
117 |
+
bias_initializer=keras.initializers.Constant(bias[i])) for i in range(c1)]
|
118 |
+
|
119 |
+
def call(self, inputs):
|
120 |
+
return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1]
|
121 |
+
|
122 |
+
|
123 |
+
class TFFocus(keras.layers.Layer):
|
124 |
+
# Focus wh information into c-space
|
125 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
|
126 |
+
# ch_in, ch_out, kernel, stride, padding, groups
|
127 |
+
super().__init__()
|
128 |
+
self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
|
129 |
+
|
130 |
+
def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c)
|
131 |
+
# inputs = inputs / 255 # normalize 0-255 to 0-1
|
132 |
+
inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]]
|
133 |
+
return self.conv(tf.concat(inputs, 3))
|
134 |
+
|
135 |
+
|
136 |
+
class TFBottleneck(keras.layers.Layer):
|
137 |
+
# Standard bottleneck
|
138 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion
|
139 |
+
super().__init__()
|
140 |
+
c_ = int(c2 * e) # hidden channels
|
141 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
142 |
+
self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
|
143 |
+
self.add = shortcut and c1 == c2
|
144 |
+
|
145 |
+
def call(self, inputs):
|
146 |
+
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
|
147 |
+
|
148 |
+
|
149 |
+
class TFCrossConv(keras.layers.Layer):
|
150 |
+
# Cross Convolution
|
151 |
+
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None):
|
152 |
+
super().__init__()
|
153 |
+
c_ = int(c2 * e) # hidden channels
|
154 |
+
self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1)
|
155 |
+
self.cv2 = TFConv(c_, c2, (k, 1), (s, 1), g=g, w=w.cv2)
|
156 |
+
self.add = shortcut and c1 == c2
|
157 |
+
|
158 |
+
def call(self, inputs):
|
159 |
+
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
|
160 |
+
|
161 |
+
|
162 |
+
class TFConv2d(keras.layers.Layer):
|
163 |
+
# Substitution for PyTorch nn.Conv2D
|
164 |
+
def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
|
165 |
+
super().__init__()
|
166 |
+
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
|
167 |
+
self.conv = keras.layers.Conv2D(filters=c2,
|
168 |
+
kernel_size=k,
|
169 |
+
strides=s,
|
170 |
+
padding='VALID',
|
171 |
+
use_bias=bias,
|
172 |
+
kernel_initializer=keras.initializers.Constant(
|
173 |
+
w.weight.permute(2, 3, 1, 0).numpy()),
|
174 |
+
bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None)
|
175 |
+
|
176 |
+
def call(self, inputs):
|
177 |
+
return self.conv(inputs)
|
178 |
+
|
179 |
+
|
180 |
+
class TFBottleneckCSP(keras.layers.Layer):
|
181 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
182 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
183 |
+
# ch_in, ch_out, number, shortcut, groups, expansion
|
184 |
+
super().__init__()
|
185 |
+
c_ = int(c2 * e) # hidden channels
|
186 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
187 |
+
self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
|
188 |
+
self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
|
189 |
+
self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
|
190 |
+
self.bn = TFBN(w.bn)
|
191 |
+
self.act = lambda x: keras.activations.swish(x)
|
192 |
+
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
|
193 |
+
|
194 |
+
def call(self, inputs):
|
195 |
+
y1 = self.cv3(self.m(self.cv1(inputs)))
|
196 |
+
y2 = self.cv2(inputs)
|
197 |
+
return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
|
198 |
+
|
199 |
+
|
200 |
+
class TFC3(keras.layers.Layer):
|
201 |
+
# CSP Bottleneck with 3 convolutions
|
202 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
203 |
+
# ch_in, ch_out, number, shortcut, groups, expansion
|
204 |
+
super().__init__()
|
205 |
+
c_ = int(c2 * e) # hidden channels
|
206 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
207 |
+
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
|
208 |
+
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
|
209 |
+
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
|
210 |
+
|
211 |
+
def call(self, inputs):
|
212 |
+
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
|
213 |
+
|
214 |
+
|
215 |
+
class TFC3x(keras.layers.Layer):
|
216 |
+
# 3 module with cross-convolutions
|
217 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
218 |
+
# ch_in, ch_out, number, shortcut, groups, expansion
|
219 |
+
super().__init__()
|
220 |
+
c_ = int(c2 * e) # hidden channels
|
221 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
222 |
+
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
|
223 |
+
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
|
224 |
+
self.m = keras.Sequential([
|
225 |
+
TFCrossConv(c_, c_, k=3, s=1, g=g, e=1.0, shortcut=shortcut, w=w.m[j]) for j in range(n)])
|
226 |
+
|
227 |
+
def call(self, inputs):
|
228 |
+
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
|
229 |
+
|
230 |
+
|
231 |
+
class TFSPP(keras.layers.Layer):
|
232 |
+
# Spatial pyramid pooling layer used in YOLOv3-SPP
|
233 |
+
def __init__(self, c1, c2, k=(5, 9, 13), w=None):
|
234 |
+
super().__init__()
|
235 |
+
c_ = c1 // 2 # hidden channels
|
236 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
237 |
+
self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
|
238 |
+
self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]
|
239 |
+
|
240 |
+
def call(self, inputs):
|
241 |
+
x = self.cv1(inputs)
|
242 |
+
return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
|
243 |
+
|
244 |
+
|
245 |
+
class TFSPPF(keras.layers.Layer):
|
246 |
+
# Spatial pyramid pooling-Fast layer
|
247 |
+
def __init__(self, c1, c2, k=5, w=None):
|
248 |
+
super().__init__()
|
249 |
+
c_ = c1 // 2 # hidden channels
|
250 |
+
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
251 |
+
self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)
|
252 |
+
self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME')
|
253 |
+
|
254 |
+
def call(self, inputs):
|
255 |
+
x = self.cv1(inputs)
|
256 |
+
y1 = self.m(x)
|
257 |
+
y2 = self.m(y1)
|
258 |
+
return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))
|
259 |
+
|
260 |
+
|
261 |
+
class TFDetect(keras.layers.Layer):
|
262 |
+
# TF YOLO Detect layer
|
263 |
+
def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer
|
264 |
+
super().__init__()
|
265 |
+
self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
|
266 |
+
self.nc = nc # number of classes
|
267 |
+
self.no = nc + 5 # number of outputs per anchor
|
268 |
+
self.nl = len(anchors) # number of detection layers
|
269 |
+
self.na = len(anchors[0]) // 2 # number of anchors
|
270 |
+
self.grid = [tf.zeros(1)] * self.nl # init grid
|
271 |
+
self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
|
272 |
+
self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2])
|
273 |
+
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
|
274 |
+
self.training = False # set to False after building model
|
275 |
+
self.imgsz = imgsz
|
276 |
+
for i in range(self.nl):
|
277 |
+
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
|
278 |
+
self.grid[i] = self._make_grid(nx, ny)
|
279 |
+
|
280 |
+
def call(self, inputs):
|
281 |
+
z = [] # inference output
|
282 |
+
x = []
|
283 |
+
for i in range(self.nl):
|
284 |
+
x.append(self.m[i](inputs[i]))
|
285 |
+
# x(bs,20,20,255) to x(bs,3,20,20,85)
|
286 |
+
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
|
287 |
+
x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no])
|
288 |
+
|
289 |
+
if not self.training: # inference
|
290 |
+
y = x[i]
|
291 |
+
grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5
|
292 |
+
anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4
|
293 |
+
xy = (tf.sigmoid(y[..., 0:2]) * 2 + grid) * self.stride[i] # xy
|
294 |
+
wh = tf.sigmoid(y[..., 2:4]) ** 2 * anchor_grid
|
295 |
+
# Normalize xywh to 0-1 to reduce calibration error
|
296 |
+
xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
|
297 |
+
wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
|
298 |
+
y = tf.concat([xy, wh, tf.sigmoid(y[..., 4:5 + self.nc]), y[..., 5 + self.nc:]], -1)
|
299 |
+
z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no]))
|
300 |
+
|
301 |
+
return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1),)
|
302 |
+
|
303 |
+
@staticmethod
|
304 |
+
def _make_grid(nx=20, ny=20):
|
305 |
+
# yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
|
306 |
+
# return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
|
307 |
+
xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
|
308 |
+
return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
|
309 |
+
|
310 |
+
|
311 |
+
class TFSegment(TFDetect):
|
312 |
+
# YOLO Segment head for segmentation models
|
313 |
+
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), imgsz=(640, 640), w=None):
|
314 |
+
super().__init__(nc, anchors, ch, imgsz, w)
|
315 |
+
self.nm = nm # number of masks
|
316 |
+
self.npr = npr # number of protos
|
317 |
+
self.no = 5 + nc + self.nm # number of outputs per anchor
|
318 |
+
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)] # output conv
|
319 |
+
self.proto = TFProto(ch[0], self.npr, self.nm, w=w.proto) # protos
|
320 |
+
self.detect = TFDetect.call
|
321 |
+
|
322 |
+
def call(self, x):
|
323 |
+
p = self.proto(x[0])
|
324 |
+
# p = TFUpsample(None, scale_factor=4, mode='nearest')(self.proto(x[0])) # (optional) full-size protos
|
325 |
+
p = tf.transpose(p, [0, 3, 1, 2]) # from shape(1,160,160,32) to shape(1,32,160,160)
|
326 |
+
x = self.detect(self, x)
|
327 |
+
return (x, p) if self.training else (x[0], p)
|
328 |
+
|
329 |
+
|
330 |
+
class TFProto(keras.layers.Layer):
|
331 |
+
|
332 |
+
def __init__(self, c1, c_=256, c2=32, w=None):
|
333 |
+
super().__init__()
|
334 |
+
self.cv1 = TFConv(c1, c_, k=3, w=w.cv1)
|
335 |
+
self.upsample = TFUpsample(None, scale_factor=2, mode='nearest')
|
336 |
+
self.cv2 = TFConv(c_, c_, k=3, w=w.cv2)
|
337 |
+
self.cv3 = TFConv(c_, c2, w=w.cv3)
|
338 |
+
|
339 |
+
def call(self, inputs):
|
340 |
+
return self.cv3(self.cv2(self.upsample(self.cv1(inputs))))
|
341 |
+
|
342 |
+
|
343 |
+
class TFUpsample(keras.layers.Layer):
|
344 |
+
# TF version of torch.nn.Upsample()
|
345 |
+
def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w'
|
346 |
+
super().__init__()
|
347 |
+
assert scale_factor % 2 == 0, "scale_factor must be multiple of 2"
|
348 |
+
self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * scale_factor, x.shape[2] * scale_factor), mode)
|
349 |
+
# self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
|
350 |
+
# with default arguments: align_corners=False, half_pixel_centers=False
|
351 |
+
# self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
|
352 |
+
# size=(x.shape[1] * 2, x.shape[2] * 2))
|
353 |
+
|
354 |
+
def call(self, inputs):
|
355 |
+
return self.upsample(inputs)
|
356 |
+
|
357 |
+
|
358 |
+
class TFConcat(keras.layers.Layer):
|
359 |
+
# TF version of torch.concat()
|
360 |
+
def __init__(self, dimension=1, w=None):
|
361 |
+
super().__init__()
|
362 |
+
assert dimension == 1, "convert only NCHW to NHWC concat"
|
363 |
+
self.d = 3
|
364 |
+
|
365 |
+
def call(self, inputs):
|
366 |
+
return tf.concat(inputs, self.d)
|
367 |
+
|
368 |
+
|
369 |
+
def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3)
|
370 |
+
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
|
371 |
+
anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
|
372 |
+
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
|
373 |
+
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
|
374 |
+
|
375 |
+
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
|
376 |
+
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
|
377 |
+
m_str = m
|
378 |
+
m = eval(m) if isinstance(m, str) else m # eval strings
|
379 |
+
for j, a in enumerate(args):
|
380 |
+
try:
|
381 |
+
args[j] = eval(a) if isinstance(a, str) else a # eval strings
|
382 |
+
except NameError:
|
383 |
+
pass
|
384 |
+
|
385 |
+
n = max(round(n * gd), 1) if n > 1 else n # depth gain
|
386 |
+
if m in [
|
387 |
+
nn.Conv2d, Conv, DWConv, DWConvTranspose2d, Bottleneck, SPP, SPPF, MixConv2d, Focus, CrossConv,
|
388 |
+
BottleneckCSP, C3, C3x]:
|
389 |
+
c1, c2 = ch[f], args[0]
|
390 |
+
c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
|
391 |
+
|
392 |
+
args = [c1, c2, *args[1:]]
|
393 |
+
if m in [BottleneckCSP, C3, C3x]:
|
394 |
+
args.insert(2, n)
|
395 |
+
n = 1
|
396 |
+
elif m is nn.BatchNorm2d:
|
397 |
+
args = [ch[f]]
|
398 |
+
elif m is Concat:
|
399 |
+
c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
|
400 |
+
elif m in [Detect, Segment]:
|
401 |
+
args.append([ch[x + 1] for x in f])
|
402 |
+
if isinstance(args[1], int): # number of anchors
|
403 |
+
args[1] = [list(range(args[1] * 2))] * len(f)
|
404 |
+
if m is Segment:
|
405 |
+
args[3] = make_divisible(args[3] * gw, 8)
|
406 |
+
args.append(imgsz)
|
407 |
+
else:
|
408 |
+
c2 = ch[f]
|
409 |
+
|
410 |
+
tf_m = eval('TF' + m_str.replace('nn.', ''))
|
411 |
+
m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \
|
412 |
+
else tf_m(*args, w=model.model[i]) # module
|
413 |
+
|
414 |
+
torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
|
415 |
+
t = str(m)[8:-2].replace('__main__.', '') # module type
|
416 |
+
np = sum(x.numel() for x in torch_m_.parameters()) # number params
|
417 |
+
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
|
418 |
+
LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print
|
419 |
+
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
|
420 |
+
layers.append(m_)
|
421 |
+
ch.append(c2)
|
422 |
+
return keras.Sequential(layers), sorted(save)
|
423 |
+
|
424 |
+
|
425 |
+
class TFModel:
|
426 |
+
# TF YOLO model
|
427 |
+
def __init__(self, cfg='yolo.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes
|
428 |
+
super().__init__()
|
429 |
+
if isinstance(cfg, dict):
|
430 |
+
self.yaml = cfg # model dict
|
431 |
+
else: # is *.yaml
|
432 |
+
import yaml # for torch hub
|
433 |
+
self.yaml_file = Path(cfg).name
|
434 |
+
with open(cfg) as f:
|
435 |
+
self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
|
436 |
+
|
437 |
+
# Define model
|
438 |
+
if nc and nc != self.yaml['nc']:
|
439 |
+
LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}")
|
440 |
+
self.yaml['nc'] = nc # override yaml value
|
441 |
+
self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
|
442 |
+
|
443 |
+
def predict(self,
|
444 |
+
inputs,
|
445 |
+
tf_nms=False,
|
446 |
+
agnostic_nms=False,
|
447 |
+
topk_per_class=100,
|
448 |
+
topk_all=100,
|
449 |
+
iou_thres=0.45,
|
450 |
+
conf_thres=0.25):
|
451 |
+
y = [] # outputs
|
452 |
+
x = inputs
|
453 |
+
for m in self.model.layers:
|
454 |
+
if m.f != -1: # if not from previous layer
|
455 |
+
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
|
456 |
+
|
457 |
+
x = m(x) # run
|
458 |
+
y.append(x if m.i in self.savelist else None) # save output
|
459 |
+
|
460 |
+
# Add TensorFlow NMS
|
461 |
+
if tf_nms:
|
462 |
+
boxes = self._xywh2xyxy(x[0][..., :4])
|
463 |
+
probs = x[0][:, :, 4:5]
|
464 |
+
classes = x[0][:, :, 5:]
|
465 |
+
scores = probs * classes
|
466 |
+
if agnostic_nms:
|
467 |
+
nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
|
468 |
+
else:
|
469 |
+
boxes = tf.expand_dims(boxes, 2)
|
470 |
+
nms = tf.image.combined_non_max_suppression(boxes,
|
471 |
+
scores,
|
472 |
+
topk_per_class,
|
473 |
+
topk_all,
|
474 |
+
iou_thres,
|
475 |
+
conf_thres,
|
476 |
+
clip_boxes=False)
|
477 |
+
return (nms,)
|
478 |
+
return x # output [1,6300,85] = [xywh, conf, class0, class1, ...]
|
479 |
+
# x = x[0] # [x(1,6300,85), ...] to x(6300,85)
|
480 |
+
# xywh = x[..., :4] # x(6300,4) boxes
|
481 |
+
# conf = x[..., 4:5] # x(6300,1) confidences
|
482 |
+
# cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
|
483 |
+
# return tf.concat([conf, cls, xywh], 1)
|
484 |
+
|
485 |
+
@staticmethod
|
486 |
+
def _xywh2xyxy(xywh):
|
487 |
+
# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
|
488 |
+
x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
|
489 |
+
return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
|
490 |
+
|
491 |
+
|
492 |
+
class AgnosticNMS(keras.layers.Layer):
|
493 |
+
# TF Agnostic NMS
|
494 |
+
def call(self, input, topk_all, iou_thres, conf_thres):
|
495 |
+
# wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450
|
496 |
+
return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres),
|
497 |
+
input,
|
498 |
+
fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
|
499 |
+
name='agnostic_nms')
|
500 |
+
|
501 |
+
@staticmethod
|
502 |
+
def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS
|
503 |
+
boxes, classes, scores = x
|
504 |
+
class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
|
505 |
+
scores_inp = tf.reduce_max(scores, -1)
|
506 |
+
selected_inds = tf.image.non_max_suppression(boxes,
|
507 |
+
scores_inp,
|
508 |
+
max_output_size=topk_all,
|
509 |
+
iou_threshold=iou_thres,
|
510 |
+
score_threshold=conf_thres)
|
511 |
+
selected_boxes = tf.gather(boxes, selected_inds)
|
512 |
+
padded_boxes = tf.pad(selected_boxes,
|
513 |
+
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
|
514 |
+
mode="CONSTANT",
|
515 |
+
constant_values=0.0)
|
516 |
+
selected_scores = tf.gather(scores_inp, selected_inds)
|
517 |
+
padded_scores = tf.pad(selected_scores,
|
518 |
+
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
|
519 |
+
mode="CONSTANT",
|
520 |
+
constant_values=-1.0)
|
521 |
+
selected_classes = tf.gather(class_inds, selected_inds)
|
522 |
+
padded_classes = tf.pad(selected_classes,
|
523 |
+
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
|
524 |
+
mode="CONSTANT",
|
525 |
+
constant_values=-1.0)
|
526 |
+
valid_detections = tf.shape(selected_inds)[0]
|
527 |
+
return padded_boxes, padded_scores, padded_classes, valid_detections
|
528 |
+
|
529 |
+
|
530 |
+
def activations(act=nn.SiLU):
|
531 |
+
# Returns TF activation from input PyTorch activation
|
532 |
+
if isinstance(act, nn.LeakyReLU):
|
533 |
+
return lambda x: keras.activations.relu(x, alpha=0.1)
|
534 |
+
elif isinstance(act, nn.Hardswish):
|
535 |
+
return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667
|
536 |
+
elif isinstance(act, (nn.SiLU, SiLU)):
|
537 |
+
return lambda x: keras.activations.swish(x)
|
538 |
+
else:
|
539 |
+
raise Exception(f'no matching TensorFlow activation found for PyTorch activation {act}')
|
540 |
+
|
541 |
+
|
542 |
+
def representative_dataset_gen(dataset, ncalib=100):
|
543 |
+
# Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays
|
544 |
+
for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
|
545 |
+
im = np.transpose(img, [1, 2, 0])
|
546 |
+
im = np.expand_dims(im, axis=0).astype(np.float32)
|
547 |
+
im /= 255
|
548 |
+
yield [im]
|
549 |
+
if n >= ncalib:
|
550 |
+
break
|
551 |
+
|
552 |
+
|
553 |
+
def run(
|
554 |
+
weights=ROOT / 'yolo.pt', # weights path
|
555 |
+
imgsz=(640, 640), # inference size h,w
|
556 |
+
batch_size=1, # batch size
|
557 |
+
dynamic=False, # dynamic batch size
|
558 |
+
):
|
559 |
+
# PyTorch model
|
560 |
+
im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
|
561 |
+
model = attempt_load(weights, device=torch.device('cpu'), inplace=True, fuse=False)
|
562 |
+
_ = model(im) # inference
|
563 |
+
model.info()
|
564 |
+
|
565 |
+
# TensorFlow model
|
566 |
+
im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
|
567 |
+
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
568 |
+
_ = tf_model.predict(im) # inference
|
569 |
+
|
570 |
+
# Keras model
|
571 |
+
im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
|
572 |
+
keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
|
573 |
+
keras_model.summary()
|
574 |
+
|
575 |
+
LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.')
|
576 |
+
|
577 |
+
|
578 |
+
def parse_opt():
|
579 |
+
parser = argparse.ArgumentParser()
|
580 |
+
parser.add_argument('--weights', type=str, default=ROOT / 'yolo.pt', help='weights path')
|
581 |
+
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
|
582 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
583 |
+
parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')
|
584 |
+
opt = parser.parse_args()
|
585 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
586 |
+
print_args(vars(opt))
|
587 |
+
return opt
|
588 |
+
|
589 |
+
|
590 |
+
def main(opt):
|
591 |
+
run(**vars(opt))
|
592 |
+
|
593 |
+
|
594 |
+
if __name__ == "__main__":
|
595 |
+
opt = parse_opt()
|
596 |
+
main(opt)
|
models/yolo.py
ADDED
@@ -0,0 +1,763 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import platform
|
4 |
+
import sys
|
5 |
+
from copy import deepcopy
|
6 |
+
from pathlib import Path
|
7 |
+
|
8 |
+
FILE = Path(__file__).resolve()
|
9 |
+
ROOT = FILE.parents[1] # YOLO root directory
|
10 |
+
if str(ROOT) not in sys.path:
|
11 |
+
sys.path.append(str(ROOT)) # add ROOT to PATH
|
12 |
+
if platform.system() != 'Windows':
|
13 |
+
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
14 |
+
|
15 |
+
from models.common import *
|
16 |
+
from models.experimental import *
|
17 |
+
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
|
18 |
+
from utils.plots import feature_visualization
|
19 |
+
from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
|
20 |
+
time_sync)
|
21 |
+
from utils.tal.anchor_generator import make_anchors, dist2bbox
|
22 |
+
|
23 |
+
try:
|
24 |
+
import thop # for FLOPs computation
|
25 |
+
except ImportError:
|
26 |
+
thop = None
|
27 |
+
|
28 |
+
|
29 |
+
class Detect(nn.Module):
|
30 |
+
# YOLO Detect head for detection models
|
31 |
+
dynamic = False # force grid reconstruction
|
32 |
+
export = False # export mode
|
33 |
+
shape = None
|
34 |
+
anchors = torch.empty(0) # init
|
35 |
+
strides = torch.empty(0) # init
|
36 |
+
|
37 |
+
def __init__(self, nc=80, ch=(), inplace=True): # detection layer
|
38 |
+
super().__init__()
|
39 |
+
self.nc = nc # number of classes
|
40 |
+
self.nl = len(ch) # number of detection layers
|
41 |
+
self.reg_max = 16
|
42 |
+
self.no = nc + self.reg_max * 4 # number of outputs per anchor
|
43 |
+
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
44 |
+
self.stride = torch.zeros(self.nl) # strides computed during build
|
45 |
+
|
46 |
+
c2, c3 = max((ch[0] // 4, self.reg_max * 4, 16)), max((ch[0], min((self.nc * 2, 128)))) # channels
|
47 |
+
self.cv2 = nn.ModuleList(
|
48 |
+
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch)
|
49 |
+
self.cv3 = nn.ModuleList(
|
50 |
+
nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)
|
51 |
+
self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()
|
52 |
+
|
53 |
+
def forward(self, x):
|
54 |
+
shape = x[0].shape # BCHW
|
55 |
+
for i in range(self.nl):
|
56 |
+
x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
|
57 |
+
if self.training:
|
58 |
+
return x
|
59 |
+
elif self.dynamic or self.shape != shape:
|
60 |
+
self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))
|
61 |
+
self.shape = shape
|
62 |
+
|
63 |
+
box, cls = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2).split((self.reg_max * 4, self.nc), 1)
|
64 |
+
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
65 |
+
y = torch.cat((dbox, cls.sigmoid()), 1)
|
66 |
+
return y if self.export else (y, x)
|
67 |
+
|
68 |
+
def bias_init(self):
|
69 |
+
# Initialize Detect() biases, WARNING: requires stride availability
|
70 |
+
m = self # self.model[-1] # Detect() module
|
71 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
|
72 |
+
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
|
73 |
+
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
|
74 |
+
a[-1].bias.data[:] = 1.0 # box
|
75 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
76 |
+
|
77 |
+
|
78 |
+
class DDetect(nn.Module):
|
79 |
+
# YOLO Detect head for detection models
|
80 |
+
dynamic = False # force grid reconstruction
|
81 |
+
export = False # export mode
|
82 |
+
shape = None
|
83 |
+
anchors = torch.empty(0) # init
|
84 |
+
strides = torch.empty(0) # init
|
85 |
+
|
86 |
+
def __init__(self, nc=80, ch=(), inplace=True): # detection layer
|
87 |
+
super().__init__()
|
88 |
+
self.nc = nc # number of classes
|
89 |
+
self.nl = len(ch) # number of detection layers
|
90 |
+
self.reg_max = 16
|
91 |
+
self.no = nc + self.reg_max * 4 # number of outputs per anchor
|
92 |
+
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
93 |
+
self.stride = torch.zeros(self.nl) # strides computed during build
|
94 |
+
|
95 |
+
c2, c3 = make_divisible(max((ch[0] // 4, self.reg_max * 4, 16)), 4), max((ch[0], min((self.nc * 2, 128)))) # channels
|
96 |
+
self.cv2 = nn.ModuleList(
|
97 |
+
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3, g=4), nn.Conv2d(c2, 4 * self.reg_max, 1, groups=4)) for x in ch)
|
98 |
+
self.cv3 = nn.ModuleList(
|
99 |
+
nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)
|
100 |
+
self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()
|
101 |
+
|
102 |
+
def forward(self, x):
|
103 |
+
shape = x[0].shape # BCHW
|
104 |
+
for i in range(self.nl):
|
105 |
+
x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
|
106 |
+
if self.training:
|
107 |
+
return x
|
108 |
+
elif self.dynamic or self.shape != shape:
|
109 |
+
self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))
|
110 |
+
self.shape = shape
|
111 |
+
|
112 |
+
box, cls = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2).split((self.reg_max * 4, self.nc), 1)
|
113 |
+
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
114 |
+
y = torch.cat((dbox, cls.sigmoid()), 1)
|
115 |
+
return y if self.export else (y, x)
|
116 |
+
|
117 |
+
def bias_init(self):
|
118 |
+
# Initialize Detect() biases, WARNING: requires stride availability
|
119 |
+
m = self # self.model[-1] # Detect() module
|
120 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
|
121 |
+
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
|
122 |
+
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
|
123 |
+
a[-1].bias.data[:] = 1.0 # box
|
124 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
125 |
+
|
126 |
+
|
127 |
+
class DualDetect(nn.Module):
|
128 |
+
# YOLO Detect head for detection models
|
129 |
+
dynamic = False # force grid reconstruction
|
130 |
+
export = False # export mode
|
131 |
+
shape = None
|
132 |
+
anchors = torch.empty(0) # init
|
133 |
+
strides = torch.empty(0) # init
|
134 |
+
|
135 |
+
def __init__(self, nc=80, ch=(), inplace=True): # detection layer
|
136 |
+
super().__init__()
|
137 |
+
self.nc = nc # number of classes
|
138 |
+
self.nl = len(ch) // 2 # number of detection layers
|
139 |
+
self.reg_max = 16
|
140 |
+
self.no = nc + self.reg_max * 4 # number of outputs per anchor
|
141 |
+
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
142 |
+
self.stride = torch.zeros(self.nl) # strides computed during build
|
143 |
+
|
144 |
+
c2, c3 = max((ch[0] // 4, self.reg_max * 4, 16)), max((ch[0], min((self.nc * 2, 128)))) # channels
|
145 |
+
c4, c5 = max((ch[self.nl] // 4, self.reg_max * 4, 16)), max((ch[self.nl], min((self.nc * 2, 128)))) # channels
|
146 |
+
self.cv2 = nn.ModuleList(
|
147 |
+
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch[:self.nl])
|
148 |
+
self.cv3 = nn.ModuleList(
|
149 |
+
nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch[:self.nl])
|
150 |
+
self.cv4 = nn.ModuleList(
|
151 |
+
nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, 4 * self.reg_max, 1)) for x in ch[self.nl:])
|
152 |
+
self.cv5 = nn.ModuleList(
|
153 |
+
nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nc, 1)) for x in ch[self.nl:])
|
154 |
+
self.dfl = DFL(self.reg_max)
|
155 |
+
self.dfl2 = DFL(self.reg_max)
|
156 |
+
|
157 |
+
def forward(self, x):
|
158 |
+
shape = x[0].shape # BCHW
|
159 |
+
d1 = []
|
160 |
+
d2 = []
|
161 |
+
for i in range(self.nl):
|
162 |
+
d1.append(torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1))
|
163 |
+
d2.append(torch.cat((self.cv4[i](x[self.nl+i]), self.cv5[i](x[self.nl+i])), 1))
|
164 |
+
if self.training:
|
165 |
+
return [d1, d2]
|
166 |
+
elif self.dynamic or self.shape != shape:
|
167 |
+
self.anchors, self.strides = (d1.transpose(0, 1) for d1 in make_anchors(d1, self.stride, 0.5))
|
168 |
+
self.shape = shape
|
169 |
+
|
170 |
+
box, cls = torch.cat([di.view(shape[0], self.no, -1) for di in d1], 2).split((self.reg_max * 4, self.nc), 1)
|
171 |
+
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
172 |
+
box2, cls2 = torch.cat([di.view(shape[0], self.no, -1) for di in d2], 2).split((self.reg_max * 4, self.nc), 1)
|
173 |
+
dbox2 = dist2bbox(self.dfl2(box2), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
174 |
+
y = [torch.cat((dbox, cls.sigmoid()), 1), torch.cat((dbox2, cls2.sigmoid()), 1)]
|
175 |
+
return y if self.export else (y, [d1, d2])
|
176 |
+
|
177 |
+
def bias_init(self):
|
178 |
+
# Initialize Detect() biases, WARNING: requires stride availability
|
179 |
+
m = self # self.model[-1] # Detect() module
|
180 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
|
181 |
+
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
|
182 |
+
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
|
183 |
+
a[-1].bias.data[:] = 1.0 # box
|
184 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
185 |
+
for a, b, s in zip(m.cv4, m.cv5, m.stride): # from
|
186 |
+
a[-1].bias.data[:] = 1.0 # box
|
187 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
188 |
+
|
189 |
+
|
190 |
+
class DualDDetect(nn.Module):
|
191 |
+
# YOLO Detect head for detection models
|
192 |
+
dynamic = False # force grid reconstruction
|
193 |
+
export = False # export mode
|
194 |
+
shape = None
|
195 |
+
anchors = torch.empty(0) # init
|
196 |
+
strides = torch.empty(0) # init
|
197 |
+
|
198 |
+
def __init__(self, nc=80, ch=(), inplace=True): # detection layer
|
199 |
+
super().__init__()
|
200 |
+
self.nc = nc # number of classes
|
201 |
+
self.nl = len(ch) // 2 # number of detection layers
|
202 |
+
self.reg_max = 16
|
203 |
+
self.no = nc + self.reg_max * 4 # number of outputs per anchor
|
204 |
+
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
205 |
+
self.stride = torch.zeros(self.nl) # strides computed during build
|
206 |
+
|
207 |
+
c2, c3 = make_divisible(max((ch[0] // 4, self.reg_max * 4, 16)), 4), max((ch[0], min((self.nc * 2, 128)))) # channels
|
208 |
+
c4, c5 = make_divisible(max((ch[self.nl] // 4, self.reg_max * 4, 16)), 4), max((ch[self.nl], min((self.nc * 2, 128)))) # channels
|
209 |
+
self.cv2 = nn.ModuleList(
|
210 |
+
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3, g=4), nn.Conv2d(c2, 4 * self.reg_max, 1, groups=4)) for x in ch[:self.nl])
|
211 |
+
self.cv3 = nn.ModuleList(
|
212 |
+
nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch[:self.nl])
|
213 |
+
self.cv4 = nn.ModuleList(
|
214 |
+
nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3, g=4), nn.Conv2d(c4, 4 * self.reg_max, 1, groups=4)) for x in ch[self.nl:])
|
215 |
+
self.cv5 = nn.ModuleList(
|
216 |
+
nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nc, 1)) for x in ch[self.nl:])
|
217 |
+
self.dfl = DFL(self.reg_max)
|
218 |
+
self.dfl2 = DFL(self.reg_max)
|
219 |
+
|
220 |
+
def forward(self, x):
|
221 |
+
shape = x[0].shape # BCHW
|
222 |
+
d1 = []
|
223 |
+
d2 = []
|
224 |
+
for i in range(self.nl):
|
225 |
+
d1.append(torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1))
|
226 |
+
d2.append(torch.cat((self.cv4[i](x[self.nl+i]), self.cv5[i](x[self.nl+i])), 1))
|
227 |
+
if self.training:
|
228 |
+
return [d1, d2]
|
229 |
+
elif self.dynamic or self.shape != shape:
|
230 |
+
self.anchors, self.strides = (d1.transpose(0, 1) for d1 in make_anchors(d1, self.stride, 0.5))
|
231 |
+
self.shape = shape
|
232 |
+
|
233 |
+
box, cls = torch.cat([di.view(shape[0], self.no, -1) for di in d1], 2).split((self.reg_max * 4, self.nc), 1)
|
234 |
+
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
235 |
+
box2, cls2 = torch.cat([di.view(shape[0], self.no, -1) for di in d2], 2).split((self.reg_max * 4, self.nc), 1)
|
236 |
+
dbox2 = dist2bbox(self.dfl2(box2), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
237 |
+
y = [torch.cat((dbox, cls.sigmoid()), 1), torch.cat((dbox2, cls2.sigmoid()), 1)]
|
238 |
+
return y if self.export else (y, [d1, d2])
|
239 |
+
#y = torch.cat((dbox2, cls2.sigmoid()), 1)
|
240 |
+
#return y if self.export else (y, d2)
|
241 |
+
#y1 = torch.cat((dbox, cls.sigmoid()), 1)
|
242 |
+
#y2 = torch.cat((dbox2, cls2.sigmoid()), 1)
|
243 |
+
#return [y1, y2] if self.export else [(y1, d1), (y2, d2)]
|
244 |
+
#return [y1, y2] if self.export else [(y1, y2), (d1, d2)]
|
245 |
+
|
246 |
+
def bias_init(self):
|
247 |
+
# Initialize Detect() biases, WARNING: requires stride availability
|
248 |
+
m = self # self.model[-1] # Detect() module
|
249 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
|
250 |
+
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
|
251 |
+
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
|
252 |
+
a[-1].bias.data[:] = 1.0 # box
|
253 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
254 |
+
for a, b, s in zip(m.cv4, m.cv5, m.stride): # from
|
255 |
+
a[-1].bias.data[:] = 1.0 # box
|
256 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
257 |
+
|
258 |
+
|
259 |
+
class TripleDetect(nn.Module):
|
260 |
+
# YOLO Detect head for detection models
|
261 |
+
dynamic = False # force grid reconstruction
|
262 |
+
export = False # export mode
|
263 |
+
shape = None
|
264 |
+
anchors = torch.empty(0) # init
|
265 |
+
strides = torch.empty(0) # init
|
266 |
+
|
267 |
+
def __init__(self, nc=80, ch=(), inplace=True): # detection layer
|
268 |
+
super().__init__()
|
269 |
+
self.nc = nc # number of classes
|
270 |
+
self.nl = len(ch) // 3 # number of detection layers
|
271 |
+
self.reg_max = 16
|
272 |
+
self.no = nc + self.reg_max * 4 # number of outputs per anchor
|
273 |
+
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
274 |
+
self.stride = torch.zeros(self.nl) # strides computed during build
|
275 |
+
|
276 |
+
c2, c3 = max((ch[0] // 4, self.reg_max * 4, 16)), max((ch[0], min((self.nc * 2, 128)))) # channels
|
277 |
+
c4, c5 = max((ch[self.nl] // 4, self.reg_max * 4, 16)), max((ch[self.nl], min((self.nc * 2, 128)))) # channels
|
278 |
+
c6, c7 = max((ch[self.nl * 2] // 4, self.reg_max * 4, 16)), max((ch[self.nl * 2], min((self.nc * 2, 128)))) # channels
|
279 |
+
self.cv2 = nn.ModuleList(
|
280 |
+
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch[:self.nl])
|
281 |
+
self.cv3 = nn.ModuleList(
|
282 |
+
nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch[:self.nl])
|
283 |
+
self.cv4 = nn.ModuleList(
|
284 |
+
nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, 4 * self.reg_max, 1)) for x in ch[self.nl:self.nl*2])
|
285 |
+
self.cv5 = nn.ModuleList(
|
286 |
+
nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nc, 1)) for x in ch[self.nl:self.nl*2])
|
287 |
+
self.cv6 = nn.ModuleList(
|
288 |
+
nn.Sequential(Conv(x, c6, 3), Conv(c6, c6, 3), nn.Conv2d(c6, 4 * self.reg_max, 1)) for x in ch[self.nl*2:self.nl*3])
|
289 |
+
self.cv7 = nn.ModuleList(
|
290 |
+
nn.Sequential(Conv(x, c7, 3), Conv(c7, c7, 3), nn.Conv2d(c7, self.nc, 1)) for x in ch[self.nl*2:self.nl*3])
|
291 |
+
self.dfl = DFL(self.reg_max)
|
292 |
+
self.dfl2 = DFL(self.reg_max)
|
293 |
+
self.dfl3 = DFL(self.reg_max)
|
294 |
+
|
295 |
+
def forward(self, x):
|
296 |
+
shape = x[0].shape # BCHW
|
297 |
+
d1 = []
|
298 |
+
d2 = []
|
299 |
+
d3 = []
|
300 |
+
for i in range(self.nl):
|
301 |
+
d1.append(torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1))
|
302 |
+
d2.append(torch.cat((self.cv4[i](x[self.nl+i]), self.cv5[i](x[self.nl+i])), 1))
|
303 |
+
d3.append(torch.cat((self.cv6[i](x[self.nl*2+i]), self.cv7[i](x[self.nl*2+i])), 1))
|
304 |
+
if self.training:
|
305 |
+
return [d1, d2, d3]
|
306 |
+
elif self.dynamic or self.shape != shape:
|
307 |
+
self.anchors, self.strides = (d1.transpose(0, 1) for d1 in make_anchors(d1, self.stride, 0.5))
|
308 |
+
self.shape = shape
|
309 |
+
|
310 |
+
box, cls = torch.cat([di.view(shape[0], self.no, -1) for di in d1], 2).split((self.reg_max * 4, self.nc), 1)
|
311 |
+
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
312 |
+
box2, cls2 = torch.cat([di.view(shape[0], self.no, -1) for di in d2], 2).split((self.reg_max * 4, self.nc), 1)
|
313 |
+
dbox2 = dist2bbox(self.dfl2(box2), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
314 |
+
box3, cls3 = torch.cat([di.view(shape[0], self.no, -1) for di in d3], 2).split((self.reg_max * 4, self.nc), 1)
|
315 |
+
dbox3 = dist2bbox(self.dfl3(box3), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
316 |
+
y = [torch.cat((dbox, cls.sigmoid()), 1), torch.cat((dbox2, cls2.sigmoid()), 1), torch.cat((dbox3, cls3.sigmoid()), 1)]
|
317 |
+
return y if self.export else (y, [d1, d2, d3])
|
318 |
+
|
319 |
+
def bias_init(self):
|
320 |
+
# Initialize Detect() biases, WARNING: requires stride availability
|
321 |
+
m = self # self.model[-1] # Detect() module
|
322 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
|
323 |
+
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
|
324 |
+
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
|
325 |
+
a[-1].bias.data[:] = 1.0 # box
|
326 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
327 |
+
for a, b, s in zip(m.cv4, m.cv5, m.stride): # from
|
328 |
+
a[-1].bias.data[:] = 1.0 # box
|
329 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
330 |
+
for a, b, s in zip(m.cv6, m.cv7, m.stride): # from
|
331 |
+
a[-1].bias.data[:] = 1.0 # box
|
332 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
333 |
+
|
334 |
+
|
335 |
+
class TripleDDetect(nn.Module):
|
336 |
+
# YOLO Detect head for detection models
|
337 |
+
dynamic = False # force grid reconstruction
|
338 |
+
export = False # export mode
|
339 |
+
shape = None
|
340 |
+
anchors = torch.empty(0) # init
|
341 |
+
strides = torch.empty(0) # init
|
342 |
+
|
343 |
+
def __init__(self, nc=80, ch=(), inplace=True): # detection layer
|
344 |
+
super().__init__()
|
345 |
+
self.nc = nc # number of classes
|
346 |
+
self.nl = len(ch) // 3 # number of detection layers
|
347 |
+
self.reg_max = 16
|
348 |
+
self.no = nc + self.reg_max * 4 # number of outputs per anchor
|
349 |
+
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
350 |
+
self.stride = torch.zeros(self.nl) # strides computed during build
|
351 |
+
|
352 |
+
c2, c3 = make_divisible(max((ch[0] // 4, self.reg_max * 4, 16)), 4), \
|
353 |
+
max((ch[0], min((self.nc * 2, 128)))) # channels
|
354 |
+
c4, c5 = make_divisible(max((ch[self.nl] // 4, self.reg_max * 4, 16)), 4), \
|
355 |
+
max((ch[self.nl], min((self.nc * 2, 128)))) # channels
|
356 |
+
c6, c7 = make_divisible(max((ch[self.nl * 2] // 4, self.reg_max * 4, 16)), 4), \
|
357 |
+
max((ch[self.nl * 2], min((self.nc * 2, 128)))) # channels
|
358 |
+
self.cv2 = nn.ModuleList(
|
359 |
+
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3, g=4),
|
360 |
+
nn.Conv2d(c2, 4 * self.reg_max, 1, groups=4)) for x in ch[:self.nl])
|
361 |
+
self.cv3 = nn.ModuleList(
|
362 |
+
nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch[:self.nl])
|
363 |
+
self.cv4 = nn.ModuleList(
|
364 |
+
nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3, g=4),
|
365 |
+
nn.Conv2d(c4, 4 * self.reg_max, 1, groups=4)) for x in ch[self.nl:self.nl*2])
|
366 |
+
self.cv5 = nn.ModuleList(
|
367 |
+
nn.Sequential(Conv(x, c5, 3), Conv(c5, c5, 3), nn.Conv2d(c5, self.nc, 1)) for x in ch[self.nl:self.nl*2])
|
368 |
+
self.cv6 = nn.ModuleList(
|
369 |
+
nn.Sequential(Conv(x, c6, 3), Conv(c6, c6, 3, g=4),
|
370 |
+
nn.Conv2d(c6, 4 * self.reg_max, 1, groups=4)) for x in ch[self.nl*2:self.nl*3])
|
371 |
+
self.cv7 = nn.ModuleList(
|
372 |
+
nn.Sequential(Conv(x, c7, 3), Conv(c7, c7, 3), nn.Conv2d(c7, self.nc, 1)) for x in ch[self.nl*2:self.nl*3])
|
373 |
+
self.dfl = DFL(self.reg_max)
|
374 |
+
self.dfl2 = DFL(self.reg_max)
|
375 |
+
self.dfl3 = DFL(self.reg_max)
|
376 |
+
|
377 |
+
def forward(self, x):
|
378 |
+
shape = x[0].shape # BCHW
|
379 |
+
d1 = []
|
380 |
+
d2 = []
|
381 |
+
d3 = []
|
382 |
+
for i in range(self.nl):
|
383 |
+
d1.append(torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1))
|
384 |
+
d2.append(torch.cat((self.cv4[i](x[self.nl+i]), self.cv5[i](x[self.nl+i])), 1))
|
385 |
+
d3.append(torch.cat((self.cv6[i](x[self.nl*2+i]), self.cv7[i](x[self.nl*2+i])), 1))
|
386 |
+
if self.training:
|
387 |
+
return [d1, d2, d3]
|
388 |
+
elif self.dynamic or self.shape != shape:
|
389 |
+
self.anchors, self.strides = (d1.transpose(0, 1) for d1 in make_anchors(d1, self.stride, 0.5))
|
390 |
+
self.shape = shape
|
391 |
+
|
392 |
+
box, cls = torch.cat([di.view(shape[0], self.no, -1) for di in d1], 2).split((self.reg_max * 4, self.nc), 1)
|
393 |
+
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
394 |
+
box2, cls2 = torch.cat([di.view(shape[0], self.no, -1) for di in d2], 2).split((self.reg_max * 4, self.nc), 1)
|
395 |
+
dbox2 = dist2bbox(self.dfl2(box2), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
396 |
+
box3, cls3 = torch.cat([di.view(shape[0], self.no, -1) for di in d3], 2).split((self.reg_max * 4, self.nc), 1)
|
397 |
+
dbox3 = dist2bbox(self.dfl3(box3), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
|
398 |
+
#y = [torch.cat((dbox, cls.sigmoid()), 1), torch.cat((dbox2, cls2.sigmoid()), 1), torch.cat((dbox3, cls3.sigmoid()), 1)]
|
399 |
+
#return y if self.export else (y, [d1, d2, d3])
|
400 |
+
y = torch.cat((dbox3, cls3.sigmoid()), 1)
|
401 |
+
return y if self.export else (y, d3)
|
402 |
+
|
403 |
+
def bias_init(self):
|
404 |
+
# Initialize Detect() biases, WARNING: requires stride availability
|
405 |
+
m = self # self.model[-1] # Detect() module
|
406 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
|
407 |
+
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
|
408 |
+
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
|
409 |
+
a[-1].bias.data[:] = 1.0 # box
|
410 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
411 |
+
for a, b, s in zip(m.cv4, m.cv5, m.stride): # from
|
412 |
+
a[-1].bias.data[:] = 1.0 # box
|
413 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
414 |
+
for a, b, s in zip(m.cv6, m.cv7, m.stride): # from
|
415 |
+
a[-1].bias.data[:] = 1.0 # box
|
416 |
+
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (5 objects and 80 classes per 640 image)
|
417 |
+
|
418 |
+
|
419 |
+
class Segment(Detect):
|
420 |
+
# YOLO Segment head for segmentation models
|
421 |
+
def __init__(self, nc=80, nm=32, npr=256, ch=(), inplace=True):
|
422 |
+
super().__init__(nc, ch, inplace)
|
423 |
+
self.nm = nm # number of masks
|
424 |
+
self.npr = npr # number of protos
|
425 |
+
self.proto = Proto(ch[0], self.npr, self.nm) # protos
|
426 |
+
self.detect = Detect.forward
|
427 |
+
|
428 |
+
c4 = max(ch[0] // 4, self.nm)
|
429 |
+
self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch)
|
430 |
+
|
431 |
+
def forward(self, x):
|
432 |
+
p = self.proto(x[0])
|
433 |
+
bs = p.shape[0]
|
434 |
+
|
435 |
+
mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
|
436 |
+
x = self.detect(self, x)
|
437 |
+
if self.training:
|
438 |
+
return x, mc, p
|
439 |
+
return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))
|
440 |
+
|
441 |
+
|
442 |
+
class Panoptic(Detect):
|
443 |
+
# YOLO Panoptic head for panoptic segmentation models
|
444 |
+
def __init__(self, nc=80, sem_nc=93, nm=32, npr=256, ch=(), inplace=True):
|
445 |
+
super().__init__(nc, ch, inplace)
|
446 |
+
self.sem_nc = sem_nc
|
447 |
+
self.nm = nm # number of masks
|
448 |
+
self.npr = npr # number of protos
|
449 |
+
self.proto = Proto(ch[0], self.npr, self.nm) # protos
|
450 |
+
self.uconv = UConv(ch[0], ch[0]//4, self.sem_nc+self.nc)
|
451 |
+
self.detect = Detect.forward
|
452 |
+
|
453 |
+
c4 = max(ch[0] // 4, self.nm)
|
454 |
+
self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch)
|
455 |
+
|
456 |
+
|
457 |
+
def forward(self, x):
|
458 |
+
p = self.proto(x[0])
|
459 |
+
s = self.uconv(x[0])
|
460 |
+
bs = p.shape[0]
|
461 |
+
|
462 |
+
mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
|
463 |
+
x = self.detect(self, x)
|
464 |
+
if self.training:
|
465 |
+
return x, mc, p, s
|
466 |
+
return (torch.cat([x, mc], 1), p, s) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p, s))
|
467 |
+
|
468 |
+
|
469 |
+
class BaseModel(nn.Module):
|
470 |
+
# YOLO base model
|
471 |
+
def forward(self, x, profile=False, visualize=False):
|
472 |
+
return self._forward_once(x, profile, visualize) # single-scale inference, train
|
473 |
+
|
474 |
+
def _forward_once(self, x, profile=False, visualize=False):
|
475 |
+
y, dt = [], [] # outputs
|
476 |
+
for m in self.model:
|
477 |
+
if m.f != -1: # if not from previous layer
|
478 |
+
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
|
479 |
+
if profile:
|
480 |
+
self._profile_one_layer(m, x, dt)
|
481 |
+
x = m(x) # run
|
482 |
+
y.append(x if m.i in self.save else None) # save output
|
483 |
+
if visualize:
|
484 |
+
feature_visualization(x, m.type, m.i, save_dir=visualize)
|
485 |
+
return x
|
486 |
+
|
487 |
+
def _profile_one_layer(self, m, x, dt):
|
488 |
+
c = m == self.model[-1] # is final layer, copy input as inplace fix
|
489 |
+
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
|
490 |
+
t = time_sync()
|
491 |
+
for _ in range(10):
|
492 |
+
m(x.copy() if c else x)
|
493 |
+
dt.append((time_sync() - t) * 100)
|
494 |
+
if m == self.model[0]:
|
495 |
+
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
|
496 |
+
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
|
497 |
+
if c:
|
498 |
+
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
|
499 |
+
|
500 |
+
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
|
501 |
+
LOGGER.info('Fusing layers... ')
|
502 |
+
for m in self.model.modules():
|
503 |
+
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
|
504 |
+
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
|
505 |
+
delattr(m, 'bn') # remove batchnorm
|
506 |
+
m.forward = m.forward_fuse # update forward
|
507 |
+
self.info()
|
508 |
+
return self
|
509 |
+
|
510 |
+
def info(self, verbose=False, img_size=640): # print model information
|
511 |
+
model_info(self, verbose, img_size)
|
512 |
+
|
513 |
+
def _apply(self, fn):
|
514 |
+
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
|
515 |
+
self = super()._apply(fn)
|
516 |
+
m = self.model[-1] # Detect()
|
517 |
+
if isinstance(m, (Detect, DualDetect, TripleDetect, DDetect, DualDDetect, TripleDDetect, Segment)):
|
518 |
+
m.stride = fn(m.stride)
|
519 |
+
m.anchors = fn(m.anchors)
|
520 |
+
m.strides = fn(m.strides)
|
521 |
+
# m.grid = list(map(fn, m.grid))
|
522 |
+
return self
|
523 |
+
|
524 |
+
|
525 |
+
class DetectionModel(BaseModel):
|
526 |
+
# YOLO detection model
|
527 |
+
def __init__(self, cfg='yolo.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
|
528 |
+
super().__init__()
|
529 |
+
if isinstance(cfg, dict):
|
530 |
+
self.yaml = cfg # model dict
|
531 |
+
else: # is *.yaml
|
532 |
+
import yaml # for torch hub
|
533 |
+
self.yaml_file = Path(cfg).name
|
534 |
+
with open(cfg, encoding='ascii', errors='ignore') as f:
|
535 |
+
self.yaml = yaml.safe_load(f) # model dict
|
536 |
+
|
537 |
+
# Define model
|
538 |
+
ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
|
539 |
+
if nc and nc != self.yaml['nc']:
|
540 |
+
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
|
541 |
+
self.yaml['nc'] = nc # override yaml value
|
542 |
+
if anchors:
|
543 |
+
LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
|
544 |
+
self.yaml['anchors'] = round(anchors) # override yaml value
|
545 |
+
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
|
546 |
+
self.names = [str(i) for i in range(self.yaml['nc'])] # default names
|
547 |
+
self.inplace = self.yaml.get('inplace', True)
|
548 |
+
|
549 |
+
# Build strides, anchors
|
550 |
+
m = self.model[-1] # Detect()
|
551 |
+
if isinstance(m, (Detect, DDetect, Segment)):
|
552 |
+
s = 256 # 2x min stride
|
553 |
+
m.inplace = self.inplace
|
554 |
+
forward = lambda x: self.forward(x)[0] if isinstance(m, (Segment)) else self.forward(x)
|
555 |
+
m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))]) # forward
|
556 |
+
# check_anchor_order(m)
|
557 |
+
# m.anchors /= m.stride.view(-1, 1, 1)
|
558 |
+
self.stride = m.stride
|
559 |
+
m.bias_init() # only run once
|
560 |
+
if isinstance(m, (DualDetect, TripleDetect, DualDDetect, TripleDDetect)):
|
561 |
+
s = 256 # 2x min stride
|
562 |
+
m.inplace = self.inplace
|
563 |
+
#forward = lambda x: self.forward(x)[0][0] if isinstance(m, (DualSegment)) else self.forward(x)[0]
|
564 |
+
forward = lambda x: self.forward(x)[0]
|
565 |
+
m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))]) # forward
|
566 |
+
# check_anchor_order(m)
|
567 |
+
# m.anchors /= m.stride.view(-1, 1, 1)
|
568 |
+
self.stride = m.stride
|
569 |
+
m.bias_init() # only run once
|
570 |
+
|
571 |
+
# Init weights, biases
|
572 |
+
initialize_weights(self)
|
573 |
+
self.info()
|
574 |
+
LOGGER.info('')
|
575 |
+
|
576 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
577 |
+
if augment:
|
578 |
+
return self._forward_augment(x) # augmented inference, None
|
579 |
+
return self._forward_once(x, profile, visualize) # single-scale inference, train
|
580 |
+
|
581 |
+
def _forward_augment(self, x):
|
582 |
+
img_size = x.shape[-2:] # height, width
|
583 |
+
s = [1, 0.83, 0.67] # scales
|
584 |
+
f = [None, 3, None] # flips (2-ud, 3-lr)
|
585 |
+
y = [] # outputs
|
586 |
+
for si, fi in zip(s, f):
|
587 |
+
xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
|
588 |
+
yi = self._forward_once(xi)[0] # forward
|
589 |
+
# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
|
590 |
+
yi = self._descale_pred(yi, fi, si, img_size)
|
591 |
+
y.append(yi)
|
592 |
+
y = self._clip_augmented(y) # clip augmented tails
|
593 |
+
return torch.cat(y, 1), None # augmented inference, train
|
594 |
+
|
595 |
+
def _descale_pred(self, p, flips, scale, img_size):
|
596 |
+
# de-scale predictions following augmented inference (inverse operation)
|
597 |
+
if self.inplace:
|
598 |
+
p[..., :4] /= scale # de-scale
|
599 |
+
if flips == 2:
|
600 |
+
p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
|
601 |
+
elif flips == 3:
|
602 |
+
p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
|
603 |
+
else:
|
604 |
+
x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
|
605 |
+
if flips == 2:
|
606 |
+
y = img_size[0] - y # de-flip ud
|
607 |
+
elif flips == 3:
|
608 |
+
x = img_size[1] - x # de-flip lr
|
609 |
+
p = torch.cat((x, y, wh, p[..., 4:]), -1)
|
610 |
+
return p
|
611 |
+
|
612 |
+
def _clip_augmented(self, y):
|
613 |
+
# Clip YOLO augmented inference tails
|
614 |
+
nl = self.model[-1].nl # number of detection layers (P3-P5)
|
615 |
+
g = sum(4 ** x for x in range(nl)) # grid points
|
616 |
+
e = 1 # exclude layer count
|
617 |
+
i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
|
618 |
+
y[0] = y[0][:, :-i] # large
|
619 |
+
i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
|
620 |
+
y[-1] = y[-1][:, i:] # small
|
621 |
+
return y
|
622 |
+
|
623 |
+
|
624 |
+
Model = DetectionModel # retain YOLO 'Model' class for backwards compatibility
|
625 |
+
|
626 |
+
|
627 |
+
class SegmentationModel(DetectionModel):
|
628 |
+
# YOLO segmentation model
|
629 |
+
def __init__(self, cfg='yolo-seg.yaml', ch=3, nc=None, anchors=None):
|
630 |
+
super().__init__(cfg, ch, nc, anchors)
|
631 |
+
|
632 |
+
|
633 |
+
class ClassificationModel(BaseModel):
|
634 |
+
# YOLO classification model
|
635 |
+
def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index
|
636 |
+
super().__init__()
|
637 |
+
self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
|
638 |
+
|
639 |
+
def _from_detection_model(self, model, nc=1000, cutoff=10):
|
640 |
+
# Create a YOLO classification model from a YOLO detection model
|
641 |
+
if isinstance(model, DetectMultiBackend):
|
642 |
+
model = model.model # unwrap DetectMultiBackend
|
643 |
+
model.model = model.model[:cutoff] # backbone
|
644 |
+
m = model.model[-1] # last layer
|
645 |
+
ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module
|
646 |
+
c = Classify(ch, nc) # Classify()
|
647 |
+
c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type
|
648 |
+
model.model[-1] = c # replace
|
649 |
+
self.model = model.model
|
650 |
+
self.stride = model.stride
|
651 |
+
self.save = []
|
652 |
+
self.nc = nc
|
653 |
+
|
654 |
+
def _from_yaml(self, cfg):
|
655 |
+
# Create a YOLO classification model from a *.yaml file
|
656 |
+
self.model = None
|
657 |
+
|
658 |
+
|
659 |
+
def parse_model(d, ch): # model_dict, input_channels(3)
|
660 |
+
# Parse a YOLO model.yaml dictionary
|
661 |
+
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
|
662 |
+
anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation')
|
663 |
+
if act:
|
664 |
+
Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
|
665 |
+
LOGGER.info(f"{colorstr('activation:')} {act}") # print
|
666 |
+
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
|
667 |
+
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
|
668 |
+
|
669 |
+
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
|
670 |
+
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
|
671 |
+
m = eval(m) if isinstance(m, str) else m # eval strings
|
672 |
+
for j, a in enumerate(args):
|
673 |
+
with contextlib.suppress(NameError):
|
674 |
+
args[j] = eval(a) if isinstance(a, str) else a # eval strings
|
675 |
+
|
676 |
+
n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
|
677 |
+
if m in {
|
678 |
+
Conv, AConv, ConvTranspose,
|
679 |
+
Bottleneck, SPP, SPPF, DWConv, BottleneckCSP, nn.ConvTranspose2d, DWConvTranspose2d, SPPCSPC, ADown,
|
680 |
+
RepNCSPELAN4, SPPELAN}:
|
681 |
+
c1, c2 = ch[f], args[0]
|
682 |
+
if c2 != no: # if not output
|
683 |
+
c2 = make_divisible(c2 * gw, 8)
|
684 |
+
|
685 |
+
args = [c1, c2, *args[1:]]
|
686 |
+
if m in {BottleneckCSP, SPPCSPC}:
|
687 |
+
args.insert(2, n) # number of repeats
|
688 |
+
n = 1
|
689 |
+
elif m is nn.BatchNorm2d:
|
690 |
+
args = [ch[f]]
|
691 |
+
elif m is Concat:
|
692 |
+
c2 = sum(ch[x] for x in f)
|
693 |
+
elif m is Shortcut:
|
694 |
+
c2 = ch[f[0]]
|
695 |
+
elif m is ReOrg:
|
696 |
+
c2 = ch[f] * 4
|
697 |
+
elif m is CBLinear:
|
698 |
+
c2 = args[0]
|
699 |
+
c1 = ch[f]
|
700 |
+
args = [c1, c2, *args[1:]]
|
701 |
+
elif m is CBFuse:
|
702 |
+
c2 = ch[f[-1]]
|
703 |
+
# TODO: channel, gw, gd
|
704 |
+
elif m in {Detect, DualDetect, TripleDetect, DDetect, DualDDetect, TripleDDetect, Segment}:
|
705 |
+
args.append([ch[x] for x in f])
|
706 |
+
# if isinstance(args[1], int): # number of anchors
|
707 |
+
# args[1] = [list(range(args[1] * 2))] * len(f)
|
708 |
+
if m in {Segment}:
|
709 |
+
args[2] = make_divisible(args[2] * gw, 8)
|
710 |
+
elif m is Contract:
|
711 |
+
c2 = ch[f] * args[0] ** 2
|
712 |
+
elif m is Expand:
|
713 |
+
c2 = ch[f] // args[0] ** 2
|
714 |
+
else:
|
715 |
+
c2 = ch[f]
|
716 |
+
|
717 |
+
m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
|
718 |
+
t = str(m)[8:-2].replace('__main__.', '') # module type
|
719 |
+
np = sum(x.numel() for x in m_.parameters()) # number params
|
720 |
+
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
|
721 |
+
LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
|
722 |
+
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
|
723 |
+
layers.append(m_)
|
724 |
+
if i == 0:
|
725 |
+
ch = []
|
726 |
+
ch.append(c2)
|
727 |
+
return nn.Sequential(*layers), sorted(save)
|
728 |
+
|
729 |
+
|
730 |
+
if __name__ == '__main__':
|
731 |
+
parser = argparse.ArgumentParser()
|
732 |
+
parser.add_argument('--cfg', type=str, default='yolo.yaml', help='model.yaml')
|
733 |
+
parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
|
734 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
735 |
+
parser.add_argument('--profile', action='store_true', help='profile model speed')
|
736 |
+
parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
|
737 |
+
parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
|
738 |
+
opt = parser.parse_args()
|
739 |
+
opt.cfg = check_yaml(opt.cfg) # check YAML
|
740 |
+
print_args(vars(opt))
|
741 |
+
device = select_device(opt.device)
|
742 |
+
|
743 |
+
# Create model
|
744 |
+
im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
|
745 |
+
model = Model(opt.cfg).to(device)
|
746 |
+
model.eval()
|
747 |
+
|
748 |
+
# Options
|
749 |
+
if opt.line_profile: # profile layer by layer
|
750 |
+
model(im, profile=True)
|
751 |
+
|
752 |
+
elif opt.profile: # profile forward-backward
|
753 |
+
results = profile(input=im, ops=[model], n=3)
|
754 |
+
|
755 |
+
elif opt.test: # test all models
|
756 |
+
for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
|
757 |
+
try:
|
758 |
+
_ = Model(cfg)
|
759 |
+
except Exception as e:
|
760 |
+
print(f'Error in {cfg}: {e}')
|
761 |
+
|
762 |
+
else: # report fused model summary
|
763 |
+
model.fuse()
|