CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/models/experimental.py
Views: 475
1
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
"""
3
Experimental modules
4
"""
5
import math
6
7
import numpy as np
8
import torch
9
import torch.nn as nn
10
11
from models.common import Conv
12
from utils.downloads import attempt_download
13
14
15
class CrossConv(nn.Module):
16
# Cross Convolution Downsample
17
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
18
# ch_in, ch_out, kernel, stride, groups, expansion, shortcut
19
super().__init__()
20
c_ = int(c2 * e) # hidden channels
21
self.cv1 = Conv(c1, c_, (1, k), (1, s))
22
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
23
self.add = shortcut and c1 == c2
24
25
def forward(self, x):
26
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
27
28
29
class Sum(nn.Module):
30
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
31
def __init__(self, n, weight=False): # n: number of inputs
32
super().__init__()
33
self.weight = weight # apply weights boolean
34
self.iter = range(n - 1) # iter object
35
if weight:
36
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
37
38
def forward(self, x):
39
y = x[0] # no weight
40
if self.weight:
41
w = torch.sigmoid(self.w) * 2
42
for i in self.iter:
43
y = y + x[i + 1] * w[i]
44
else:
45
for i in self.iter:
46
y = y + x[i + 1]
47
return y
48
49
50
class MixConv2d(nn.Module):
51
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
52
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
53
super().__init__()
54
n = len(k) # number of convolutions
55
if equal_ch: # equal c_ per group
56
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
57
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
58
else: # equal weight.numel() per group
59
b = [c2] + [0] * n
60
a = np.eye(n + 1, n, k=-1)
61
a -= np.roll(a, 1, axis=1)
62
a *= np.array(k) ** 2
63
a[0] = 1
64
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
65
66
self.m = nn.ModuleList(
67
[nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
68
self.bn = nn.BatchNorm2d(c2)
69
self.act = nn.SiLU()
70
71
def forward(self, x):
72
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
73
74
75
class Ensemble(nn.ModuleList):
76
# Ensemble of models
77
def __init__(self):
78
super().__init__()
79
80
def forward(self, x, augment=False, profile=False, visualize=False):
81
y = []
82
for module in self:
83
y.append(module(x, augment, profile, visualize)[0])
84
# y = torch.stack(y).max(0)[0] # max ensemble
85
# y = torch.stack(y).mean(0) # mean ensemble
86
y = torch.cat(y, 1) # nms ensemble
87
return y, None # inference, train output
88
89
90
def attempt_load(weights, map_location=None, inplace=True, fuse=True):
91
from models.yolo import Detect, Model
92
93
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
94
model = Ensemble()
95
for w in weights if isinstance(weights, list) else [weights]:
96
ckpt = torch.load(attempt_download(w), map_location=map_location) # load
97
if fuse:
98
model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
99
else:
100
model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # without layer fuse
101
102
# Compatibility updates
103
for m in model.modules():
104
if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
105
m.inplace = inplace # pytorch 1.7.0 compatibility
106
if type(m) is Detect:
107
if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility
108
delattr(m, 'anchor_grid')
109
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
110
elif type(m) is Conv:
111
m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
112
113
if len(model) == 1:
114
return model[-1] # return model
115
else:
116
print(f'Ensemble created with {weights}\n')
117
for k in ['names']:
118
setattr(model, k, getattr(model[-1], k))
119
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
120
return model # return ensemble
121
122