Spaces:
Sleeping
Sleeping
Update models/experimental.py
Browse files- models/experimental.py +104 -104
models/experimental.py
CHANGED
@@ -1,104 +1,104 @@
|
|
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 Sum(nn.Module):
|
16 |
-
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
17 |
-
def __init__(self, n, weight=False): # n: number of inputs
|
18 |
-
super().__init__()
|
19 |
-
self.weight = weight # apply weights boolean
|
20 |
-
self.iter = range(n - 1) # iter object
|
21 |
-
if weight:
|
22 |
-
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
23 |
-
|
24 |
-
def forward(self, x):
|
25 |
-
y = x[0] # no weight
|
26 |
-
if self.weight:
|
27 |
-
w = torch.sigmoid(self.w) * 2
|
28 |
-
for i in self.iter:
|
29 |
-
y = y + x[i + 1] * w[i]
|
30 |
-
else:
|
31 |
-
for i in self.iter:
|
32 |
-
y = y + x[i + 1]
|
33 |
-
return y
|
34 |
-
|
35 |
-
|
36 |
-
class MixConv2d(nn.Module):
|
37 |
-
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
38 |
-
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
39 |
-
super().__init__()
|
40 |
-
n = len(k) # number of convolutions
|
41 |
-
if equal_ch: # equal c_ per group
|
42 |
-
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
43 |
-
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
44 |
-
else: # equal weight.numel() per group
|
45 |
-
b = [c2] + [0] * n
|
46 |
-
a = np.eye(n + 1, n, k=-1)
|
47 |
-
a -= np.roll(a, 1, axis=1)
|
48 |
-
a *= np.array(k) ** 2
|
49 |
-
a[0] = 1
|
50 |
-
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
51 |
-
|
52 |
-
self.m = nn.ModuleList([
|
53 |
-
nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
54 |
-
self.bn = nn.BatchNorm2d(c2)
|
55 |
-
self.act = nn.SiLU()
|
56 |
-
|
57 |
-
def forward(self, x):
|
58 |
-
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
59 |
-
|
60 |
-
|
61 |
-
class Ensemble(nn.ModuleList):
|
62 |
-
# Ensemble of models
|
63 |
-
def __init__(self):
|
64 |
-
super().__init__()
|
65 |
-
|
66 |
-
def forward(self, x, augment=False, profile=False, visualize=False):
|
67 |
-
y = [module(x, augment, profile, visualize)[0] for module in self]
|
68 |
-
# y = torch.stack(y).max(0)[0] # max ensemble
|
69 |
-
# y = torch.stack(y).mean(0) # mean ensemble
|
70 |
-
y = torch.cat(y, 1) # nms ensemble
|
71 |
-
return y, None # inference, train output
|
72 |
-
|
73 |
-
|
74 |
-
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
75 |
-
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
76 |
-
from models.yolo import Detect, Model
|
77 |
-
|
78 |
-
model = Ensemble()
|
79 |
-
for w in weights if isinstance(weights, list) else [weights]:
|
80 |
-
ckpt = torch.load(attempt_download(w), map_location='cpu') # load
|
81 |
-
ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
|
82 |
-
model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode
|
83 |
-
|
84 |
-
# Compatibility updates
|
85 |
-
for m in model.modules():
|
86 |
-
t = type(m)
|
87 |
-
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
88 |
-
m.inplace = inplace # torch 1.7.0 compatibility
|
89 |
-
if t is Detect and not isinstance(m.anchor_grid, list):
|
90 |
-
delattr(m, 'anchor_grid')
|
91 |
-
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
92 |
-
elif t is Conv:
|
93 |
-
m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility
|
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 |
-
if len(model) == 1:
|
98 |
-
return model[-1] # return model
|
99 |
-
print(f'Ensemble created with {weights}\n')
|
100 |
-
for k in 'names', 'nc', 'yaml':
|
101 |
-
setattr(model, k, getattr(model[0], k))
|
102 |
-
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
103 |
-
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
|
104 |
-
return model # return ensemble
|
|
|
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 Sum(nn.Module):
|
16 |
+
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
17 |
+
def __init__(self, n, weight=False): # n: number of inputs
|
18 |
+
super().__init__()
|
19 |
+
self.weight = weight # apply weights boolean
|
20 |
+
self.iter = range(n - 1) # iter object
|
21 |
+
if weight:
|
22 |
+
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
y = x[0] # no weight
|
26 |
+
if self.weight:
|
27 |
+
w = torch.sigmoid(self.w) * 2
|
28 |
+
for i in self.iter:
|
29 |
+
y = y + x[i + 1] * w[i]
|
30 |
+
else:
|
31 |
+
for i in self.iter:
|
32 |
+
y = y + x[i + 1]
|
33 |
+
return y
|
34 |
+
|
35 |
+
|
36 |
+
class MixConv2d(nn.Module):
|
37 |
+
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
38 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
39 |
+
super().__init__()
|
40 |
+
n = len(k) # number of convolutions
|
41 |
+
if equal_ch: # equal c_ per group
|
42 |
+
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
43 |
+
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
44 |
+
else: # equal weight.numel() per group
|
45 |
+
b = [c2] + [0] * n
|
46 |
+
a = np.eye(n + 1, n, k=-1)
|
47 |
+
a -= np.roll(a, 1, axis=1)
|
48 |
+
a *= np.array(k) ** 2
|
49 |
+
a[0] = 1
|
50 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
51 |
+
|
52 |
+
self.m = nn.ModuleList([
|
53 |
+
nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
54 |
+
self.bn = nn.BatchNorm2d(c2)
|
55 |
+
self.act = nn.SiLU()
|
56 |
+
|
57 |
+
def forward(self, x):
|
58 |
+
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
59 |
+
|
60 |
+
|
61 |
+
class Ensemble(nn.ModuleList):
|
62 |
+
# Ensemble of models
|
63 |
+
def __init__(self):
|
64 |
+
super().__init__()
|
65 |
+
|
66 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
67 |
+
y = [module(x, augment, profile, visualize)[0] for module in self]
|
68 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
69 |
+
# y = torch.stack(y).mean(0) # mean ensemble
|
70 |
+
y = torch.cat(y, 1) # nms ensemble
|
71 |
+
return y, None # inference, train output
|
72 |
+
|
73 |
+
|
74 |
+
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
75 |
+
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
76 |
+
from models.yolo import Detect, Model
|
77 |
+
|
78 |
+
model = Ensemble()
|
79 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
80 |
+
ckpt = torch.load(attempt_download(w), map_location='cpu', weights_only = False) # load
|
81 |
+
ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
|
82 |
+
model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode
|
83 |
+
|
84 |
+
# Compatibility updates
|
85 |
+
for m in model.modules():
|
86 |
+
t = type(m)
|
87 |
+
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
88 |
+
m.inplace = inplace # torch 1.7.0 compatibility
|
89 |
+
if t is Detect and not isinstance(m.anchor_grid, list):
|
90 |
+
delattr(m, 'anchor_grid')
|
91 |
+
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
92 |
+
elif t is Conv:
|
93 |
+
m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility
|
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 |
+
if len(model) == 1:
|
98 |
+
return model[-1] # return model
|
99 |
+
print(f'Ensemble created with {weights}\n')
|
100 |
+
for k in 'names', 'nc', 'yaml':
|
101 |
+
setattr(model, k, getattr(model[0], k))
|
102 |
+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
103 |
+
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
|
104 |
+
return model # return ensemble
|