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/yolo.py
Views: 475
1
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
"""
3
YOLO-specific modules
4
5
Usage:
6
$ python path/to/models/yolo.py --cfg yolov5s.yaml
7
"""
8
9
import argparse
10
import sys
11
from copy import deepcopy
12
from pathlib import Path
13
14
FILE = Path(__file__).resolve()
15
ROOT = FILE.parents[1] # YOLOv5 root directory
16
if str(ROOT) not in sys.path:
17
sys.path.append(str(ROOT)) # add ROOT to PATH
18
# ROOT = ROOT.relative_to(Path.cwd()) # relative
19
20
from models.common import *
21
from models.experimental import *
22
from utils.autoanchor import check_anchor_order
23
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
24
from utils.plots import feature_visualization
25
from utils.torch_utils import fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device, time_sync
26
27
try:
28
import thop # for FLOPs computation
29
except ImportError:
30
thop = None
31
32
33
class Detect(nn.Module):
34
stride = None # strides computed during build
35
onnx_dynamic = False # ONNX export parameter
36
37
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
38
super().__init__()
39
self.nc = nc # number of classes
40
self.no = nc + 5 + 180 # number of outputs per anchor
41
self.nl = len(anchors) # number of detection layers
42
self.na = len(anchors[0]) // 2 # number of anchors
43
self.grid = [torch.zeros(1)] * self.nl # init grid
44
self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid
45
self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
46
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
47
self.inplace = inplace # use in-place ops (e.g. slice assignment)
48
49
def forward(self, x):
50
"""
51
Args:
52
x (list[P3_in,...]): torch.Size(b, c_i, h_i, w_i)
53
54
Return:
55
if train:
56
x (list[P3_out,...]): torch.Size(b, self.na, h_i, w_i, self.no), self.na means the number of anchors scales
57
else:
58
inference (tensor): (b, n_all_anchors, self.no)
59
x (list[P3_in,...]): torch.Size(b, c_i, h_i, w_i)
60
"""
61
z = [] # inference output
62
for i in range(self.nl):
63
x[i] = self.m[i](x[i]) # conv
64
bs, _, ny, nx = x[i].shape # x[i](bs,self.no * self.na,20,20) to x[i](bs,self.na,20,20,self.no)
65
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
66
67
if not self.training: # inference
68
if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
69
self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
70
71
y = x[i].sigmoid() # (tensor): (b, self.na, h, w, self.no)
72
if self.inplace:
73
y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
74
y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
75
else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
76
xy = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
77
wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
78
y = torch.cat((xy, wh, y[..., 4:]), -1)
79
z.append(y.view(bs, -1, self.no)) # z (list[P3_pred]): Torch.Size(b, n_anchors, self.no)
80
81
return x if self.training else (torch.cat(z, 1), x)
82
83
def _make_grid(self, nx=20, ny=20, i=0):
84
d = self.anchors[i].device
85
if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
86
yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)], indexing='ij')
87
else:
88
yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)])
89
grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float()
90
anchor_grid = (self.anchors[i].clone() * self.stride[i]) \
91
.view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float()
92
return grid, anchor_grid
93
94
95
class Model(nn.Module):
96
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
97
super().__init__()
98
if isinstance(cfg, dict):
99
self.yaml = cfg # model dict
100
else: # is *.yaml
101
import yaml # for torch hub
102
self.yaml_file = Path(cfg).name
103
with open(cfg, encoding='ascii', errors='ignore') as f:
104
self.yaml = yaml.safe_load(f) # model dict
105
106
# Define model
107
ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
108
if nc and nc != self.yaml['nc']:
109
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
110
self.yaml['nc'] = nc # override yaml value
111
if anchors:
112
LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
113
self.yaml['anchors'] = round(anchors) # override yaml value
114
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
115
self.names = [str(i) for i in range(self.yaml['nc'])] # default names
116
self.inplace = self.yaml.get('inplace', True)
117
118
# Build strides, anchors
119
m = self.model[-1] # Detect()
120
if isinstance(m, Detect):
121
s = 256 # 2x min stride
122
m.inplace = self.inplace
123
m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
124
m.anchors /= m.stride.view(-1, 1, 1) # featuremap pixel
125
check_anchor_order(m)
126
self.stride = m.stride
127
self._initialize_biases() # only run once
128
129
# Init weights, biases
130
initialize_weights(self)
131
self.info()
132
LOGGER.info('')
133
134
def forward(self, x, augment=False, profile=False, visualize=False):
135
"""
136
Args:
137
x (tensor): (b, 3, height, width), RGB
138
139
Return:
140
if not augment:
141
x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales
142
else:
143
144
"""
145
if augment:
146
return self._forward_augment(x) # augmented inference, None
147
return self._forward_once(x, profile, visualize) # single-scale inference, train
148
149
def _forward_augment(self, x):
150
img_size = x.shape[-2:] # height, width
151
s = [1, 0.83, 0.67] # scales
152
f = [None, 3, None] # flips (2-ud, 3-lr)
153
y = [] # outputs
154
for si, fi in zip(s, f):
155
xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
156
yi = self._forward_once(xi)[0] # forward
157
# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
158
yi = self._descale_pred(yi, fi, si, img_size)
159
y.append(yi)
160
y = self._clip_augmented(y) # clip augmented tails
161
return torch.cat(y, 1), None # augmented inference, train
162
163
def _forward_once(self, x, profile=False, visualize=False):
164
"""
165
Args:
166
x (tensor): (b, 3, height, width), RGB
167
168
Return:
169
x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales
170
"""
171
y, dt = [], [] # outputs
172
for m in self.model:
173
if m.f != -1: # if not from previous layer
174
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
175
if profile:
176
self._profile_one_layer(m, x, dt)
177
x = m(x) # run
178
y.append(x if m.i in self.save else None) # save output
179
if visualize:
180
feature_visualization(x, m.type, m.i, save_dir=visualize)
181
return x
182
183
def _descale_pred(self, p, flips, scale, img_size):
184
# de-scale predictions following augmented inference (inverse operation)
185
if self.inplace:
186
p[..., :4] /= scale # de-scale
187
if flips == 2:
188
p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
189
elif flips == 3:
190
p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
191
else:
192
x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
193
if flips == 2:
194
y = img_size[0] - y # de-flip ud
195
elif flips == 3:
196
x = img_size[1] - x # de-flip lr
197
p = torch.cat((x, y, wh, p[..., 4:]), -1)
198
return p
199
200
def _clip_augmented(self, y):
201
# Clip YOLOv5 augmented inference tails
202
nl = self.model[-1].nl # number of detection layers (P3-P5)
203
g = sum(4 ** x for x in range(nl)) # grid points
204
e = 1 # exclude layer count
205
i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
206
y[0] = y[0][:, :-i] # large
207
i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
208
y[-1] = y[-1][:, i:] # small
209
return y
210
211
def _profile_one_layer(self, m, x, dt):
212
c = isinstance(m, Detect) # is final layer, copy input as inplace fix
213
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
214
t = time_sync()
215
for _ in range(10):
216
m(x.copy() if c else x)
217
dt.append((time_sync() - t) * 100)
218
if m == self.model[0]:
219
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
220
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
221
if c:
222
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
223
224
def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
225
# https://arxiv.org/abs/1708.02002 section 3.3
226
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
227
m = self.model[-1] # Detect() module
228
for mi, s in zip(m.m, m.stride): # from
229
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
230
b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
231
b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
232
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
233
234
def _print_biases(self):
235
m = self.model[-1] # Detect() module
236
for mi in m.m: # from
237
b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
238
LOGGER.info(
239
('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
240
241
# def _print_weights(self):
242
# for m in self.model.modules():
243
# if type(m) is Bottleneck:
244
# LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
245
246
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
247
LOGGER.info('Fusing layers... ')
248
for m in self.model.modules():
249
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
250
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
251
delattr(m, 'bn') # remove batchnorm
252
m.forward = m.forward_fuse # update forward
253
self.info()
254
return self
255
256
def info(self, verbose=False, img_size=640): # print model information
257
model_info(self, verbose, img_size)
258
259
def _apply(self, fn):
260
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
261
self = super()._apply(fn)
262
m = self.model[-1] # Detect()
263
if isinstance(m, Detect):
264
m.stride = fn(m.stride)
265
m.grid = list(map(fn, m.grid))
266
if isinstance(m.anchor_grid, list):
267
m.anchor_grid = list(map(fn, m.anchor_grid))
268
return self
269
270
271
def parse_model(d, ch): # model_dict, input_channels(3)
272
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
273
anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
274
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
275
# no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
276
no = na * (nc + 185) # number of outputs = anchors * (classes + 185)
277
278
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
279
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
280
m = eval(m) if isinstance(m, str) else m # eval strings
281
for j, a in enumerate(args):
282
try:
283
args[j] = eval(a) if isinstance(a, str) else a # eval strings
284
except NameError:
285
pass
286
287
n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
288
if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
289
BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
290
c1, c2 = ch[f], args[0]
291
if c2 != no: # if not output
292
c2 = make_divisible(c2 * gw, 8)
293
294
args = [c1, c2, *args[1:]]
295
if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
296
args.insert(2, n) # number of repeats
297
n = 1
298
elif m is nn.BatchNorm2d:
299
args = [ch[f]]
300
elif m is Concat:
301
c2 = sum(ch[x] for x in f)
302
elif m is Detect:
303
args.append([ch[x] for x in f])
304
if isinstance(args[1], int): # number of anchors
305
args[1] = [list(range(args[1] * 2))] * len(f)
306
elif m is Contract:
307
c2 = ch[f] * args[0] ** 2
308
elif m is Expand:
309
c2 = ch[f] // args[0] ** 2
310
else:
311
c2 = ch[f]
312
313
m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
314
t = str(m)[8:-2].replace('__main__.', '') # module type
315
np = sum(x.numel() for x in m_.parameters()) # number params
316
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
317
LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
318
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
319
layers.append(m_)
320
if i == 0:
321
ch = []
322
ch.append(c2)
323
return nn.Sequential(*layers), sorted(save)
324
325
326
if __name__ == '__main__':
327
parser = argparse.ArgumentParser()
328
parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
329
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
330
parser.add_argument('--profile', action='store_true', help='profile model speed')
331
parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')
332
opt = parser.parse_args()
333
opt.cfg = check_yaml(opt.cfg) # check YAML
334
print_args(FILE.stem, opt)
335
device = select_device(opt.device)
336
337
# Create model
338
model = Model(opt.cfg).to(device)
339
model.train()
340
341
# Profile
342
if opt.profile:
343
img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
344
y = model(img, profile=True)
345
346
# Test all models
347
if opt.test:
348
for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
349
try:
350
_ = Model(cfg)
351
except Exception as e:
352
print(f'Error in {cfg}: {e}')
353
354
# Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
355
# from torch.utils.tensorboard import SummaryWriter
356
# tb_writer = SummaryWriter('.')
357
# LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
358
# tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
359
360