Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

yolo.py 21 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. """
  3. YOLO-specific modules.
  4. Usage:
  5. $ python models/yolo.py --cfg yolov5s.yaml
  6. """
  7. import argparse
  8. import contextlib
  9. import math
  10. import os
  11. import platform
  12. import sys
  13. from copy import deepcopy
  14. from pathlib import Path
  15. import torch
  16. import torch.nn as nn
  17. FILE = Path(__file__).resolve()
  18. ROOT = FILE.parents[1] # YOLOv5 root directory
  19. if str(ROOT) not in sys.path:
  20. sys.path.append(str(ROOT)) # add ROOT to PATH
  21. if platform.system() != "Windows":
  22. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  23. from models.common import (
  24. C3,
  25. C3SPP,
  26. C3TR,
  27. SPP,
  28. SPPF,
  29. Bottleneck,
  30. BottleneckCSP,
  31. C3Ghost,
  32. C3x,
  33. Classify,
  34. Concat,
  35. Contract,
  36. Conv,
  37. CrossConv,
  38. DetectMultiBackend,
  39. DWConv,
  40. DWConvTranspose2d,
  41. Expand,
  42. Focus,
  43. GhostBottleneck,
  44. GhostConv,
  45. Proto,
  46. )
  47. from models.experimental import MixConv2d
  48. from utils.autoanchor import check_anchor_order
  49. from utils.general import LOGGER, check_version, check_yaml, colorstr, make_divisible, print_args
  50. from utils.plots import feature_visualization
  51. from utils.torch_utils import (
  52. fuse_conv_and_bn,
  53. initialize_weights,
  54. model_info,
  55. profile,
  56. scale_img,
  57. select_device,
  58. time_sync,
  59. )
  60. try:
  61. import thop # for FLOPs computation
  62. except ImportError:
  63. thop = None
  64. class Detect(nn.Module):
  65. """YOLOv5 Detect head for processing input tensors and generating detection outputs in object detection models."""
  66. stride = None # strides computed during build
  67. dynamic = False # force grid reconstruction
  68. export = False # export mode
  69. def __init__(self, nc=80, anchors=(), ch=(), inplace=True):
  70. """Initializes YOLOv5 detection layer with specified classes, anchors, channels, and inplace operations."""
  71. super().__init__()
  72. self.nc = nc # number of classes
  73. self.no = nc + 5 # number of outputs per anchor
  74. self.nl = len(anchors) # number of detection layers
  75. self.na = len(anchors[0]) // 2 # number of anchors
  76. self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid
  77. self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid
  78. self.register_buffer("anchors", torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
  79. self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
  80. self.inplace = inplace # use inplace ops (e.g. slice assignment)
  81. def forward(self, x):
  82. """Processes input through YOLOv5 layers, altering shape for detection: `x(bs, 3, ny, nx, 85)`."""
  83. z = [] # inference output
  84. for i in range(self.nl):
  85. x[i] = self.m[i](x[i]) # conv
  86. bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
  87. x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
  88. if not self.training: # inference
  89. if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
  90. self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
  91. if isinstance(self, Segment): # (boxes + masks)
  92. xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
  93. xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy
  94. wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh
  95. y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
  96. else: # Detect (boxes only)
  97. xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
  98. xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
  99. wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
  100. y = torch.cat((xy, wh, conf), 4)
  101. z.append(y.view(bs, self.na * nx * ny, self.no))
  102. return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
  103. def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, "1.10.0")):
  104. """Generates a mesh grid for anchor boxes with optional compatibility for torch versions < 1.10."""
  105. d = self.anchors[i].device
  106. t = self.anchors[i].dtype
  107. shape = 1, self.na, ny, nx, 2 # grid shape
  108. y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
  109. yv, xv = torch.meshgrid(y, x, indexing="ij") if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility
  110. grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
  111. anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
  112. return grid, anchor_grid
  113. class Segment(Detect):
  114. """YOLOv5 Segment head for segmentation models, extending Detect with mask and prototype layers."""
  115. def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
  116. """Initializes YOLOv5 Segment head with options for mask count, protos, and channel adjustments."""
  117. super().__init__(nc, anchors, ch, inplace)
  118. self.nm = nm # number of masks
  119. self.npr = npr # number of protos
  120. self.no = 5 + nc + self.nm # number of outputs per anchor
  121. self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
  122. self.proto = Proto(ch[0], self.npr, self.nm) # protos
  123. self.detect = Detect.forward
  124. def forward(self, x):
  125. """Processes input through the network, returning detections and prototypes; adjusts output based on
  126. training/export mode.
  127. """
  128. p = self.proto(x[0])
  129. x = self.detect(self, x)
  130. return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
  131. class BaseModel(nn.Module):
  132. """YOLOv5 base model."""
  133. def forward(self, x, profile=False, visualize=False):
  134. """Executes a single-scale inference or training pass on the YOLOv5 base model, with options for profiling and
  135. visualization.
  136. """
  137. return self._forward_once(x, profile, visualize) # single-scale inference, train
  138. def _forward_once(self, x, profile=False, visualize=False):
  139. """Performs a forward pass on the YOLOv5 model, enabling profiling and feature visualization options."""
  140. y, dt = [], [] # outputs
  141. for m in self.model:
  142. if m.f != -1: # if not from previous layer
  143. 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
  144. if profile:
  145. self._profile_one_layer(m, x, dt)
  146. x = m(x) # run
  147. y.append(x if m.i in self.save else None) # save output
  148. if visualize:
  149. feature_visualization(x, m.type, m.i, save_dir=visualize)
  150. return x
  151. def _profile_one_layer(self, m, x, dt):
  152. """Profiles a single layer's performance by computing GFLOPs, execution time, and parameters."""
  153. c = m == self.model[-1] # is final layer, copy input as inplace fix
  154. o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1e9 * 2 if thop else 0 # FLOPs
  155. t = time_sync()
  156. for _ in range(10):
  157. m(x.copy() if c else x)
  158. dt.append((time_sync() - t) * 100)
  159. if m == self.model[0]:
  160. LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
  161. LOGGER.info(f"{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}")
  162. if c:
  163. LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
  164. def fuse(self):
  165. """Fuses Conv2d() and BatchNorm2d() layers in the model to improve inference speed."""
  166. LOGGER.info("Fusing layers... ")
  167. for m in self.model.modules():
  168. if isinstance(m, (Conv, DWConv)) and hasattr(m, "bn"):
  169. m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
  170. delattr(m, "bn") # remove batchnorm
  171. m.forward = m.forward_fuse # update forward
  172. self.info()
  173. return self
  174. def info(self, verbose=False, img_size=640):
  175. """Prints model information given verbosity and image size, e.g., `info(verbose=True, img_size=640)`."""
  176. model_info(self, verbose, img_size)
  177. def _apply(self, fn):
  178. """Applies transformations like to(), cpu(), cuda(), half() to model tensors excluding parameters or registered
  179. buffers.
  180. """
  181. self = super()._apply(fn)
  182. m = self.model[-1] # Detect()
  183. if isinstance(m, (Detect, Segment)):
  184. m.stride = fn(m.stride)
  185. m.grid = list(map(fn, m.grid))
  186. if isinstance(m.anchor_grid, list):
  187. m.anchor_grid = list(map(fn, m.anchor_grid))
  188. return self
  189. class DetectionModel(BaseModel):
  190. """YOLOv5 detection model class for object detection tasks, supporting custom configurations and anchors."""
  191. def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, anchors=None):
  192. """Initializes YOLOv5 model with configuration file, input channels, number of classes, and custom anchors."""
  193. super().__init__()
  194. if isinstance(cfg, dict):
  195. self.yaml = cfg # model dict
  196. else: # is *.yaml
  197. import yaml # for torch hub
  198. self.yaml_file = Path(cfg).name
  199. with open(cfg, encoding="ascii", errors="ignore") as f:
  200. self.yaml = yaml.safe_load(f) # model dict
  201. # Define model
  202. ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
  203. if nc and nc != self.yaml["nc"]:
  204. LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
  205. self.yaml["nc"] = nc # override yaml value
  206. if anchors:
  207. LOGGER.info(f"Overriding model.yaml anchors with anchors={anchors}")
  208. self.yaml["anchors"] = round(anchors) # override yaml value
  209. self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
  210. self.names = [str(i) for i in range(self.yaml["nc"])] # default names
  211. self.inplace = self.yaml.get("inplace", True)
  212. # Build strides, anchors
  213. m = self.model[-1] # Detect()
  214. if isinstance(m, (Detect, Segment)):
  215. def _forward(x):
  216. """Passes the input 'x' through the model and returns the processed output."""
  217. return self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)
  218. s = 256 # 2x min stride
  219. m.inplace = self.inplace
  220. m.stride = torch.tensor([s / x.shape[-2] for x in _forward(torch.zeros(1, ch, s, s))]) # forward
  221. check_anchor_order(m)
  222. m.anchors /= m.stride.view(-1, 1, 1)
  223. self.stride = m.stride
  224. self._initialize_biases() # only run once
  225. # Init weights, biases
  226. initialize_weights(self)
  227. self.info()
  228. LOGGER.info("")
  229. def forward(self, x, augment=False, profile=False, visualize=False):
  230. """Performs single-scale or augmented inference and may include profiling or visualization."""
  231. if augment:
  232. return self._forward_augment(x) # augmented inference, None
  233. return self._forward_once(x, profile, visualize) # single-scale inference, train
  234. def _forward_augment(self, x):
  235. """Performs augmented inference across different scales and flips, returning combined detections."""
  236. img_size = x.shape[-2:] # height, width
  237. s = [1, 0.83, 0.67] # scales
  238. f = [None, 3, None] # flips (2-ud, 3-lr)
  239. y = [] # outputs
  240. for si, fi in zip(s, f):
  241. xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
  242. yi = self._forward_once(xi)[0] # forward
  243. # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
  244. yi = self._descale_pred(yi, fi, si, img_size)
  245. y.append(yi)
  246. y = self._clip_augmented(y) # clip augmented tails
  247. return torch.cat(y, 1), None # augmented inference, train
  248. def _descale_pred(self, p, flips, scale, img_size):
  249. """De-scales predictions from augmented inference, adjusting for flips and image size."""
  250. if self.inplace:
  251. p[..., :4] /= scale # de-scale
  252. if flips == 2:
  253. p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
  254. elif flips == 3:
  255. p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
  256. else:
  257. x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
  258. if flips == 2:
  259. y = img_size[0] - y # de-flip ud
  260. elif flips == 3:
  261. x = img_size[1] - x # de-flip lr
  262. p = torch.cat((x, y, wh, p[..., 4:]), -1)
  263. return p
  264. def _clip_augmented(self, y):
  265. """Clips augmented inference tails for YOLOv5 models, affecting first and last tensors based on grid points and
  266. layer counts.
  267. """
  268. nl = self.model[-1].nl # number of detection layers (P3-P5)
  269. g = sum(4**x for x in range(nl)) # grid points
  270. e = 1 # exclude layer count
  271. i = (y[0].shape[1] // g) * sum(4**x for x in range(e)) # indices
  272. y[0] = y[0][:, :-i] # large
  273. i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
  274. y[-1] = y[-1][:, i:] # small
  275. return y
  276. def _initialize_biases(self, cf=None):
  277. """
  278. Initializes biases for YOLOv5's Detect() module, optionally using class frequencies (cf).
  279. For details see https://arxiv.org/abs/1708.02002 section 3.3.
  280. """
  281. # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
  282. m = self.model[-1] # Detect() module
  283. for mi, s in zip(m.m, m.stride): # from
  284. b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
  285. b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
  286. b.data[:, 5 : 5 + m.nc] += (
  287. math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum())
  288. ) # cls
  289. mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  290. Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility
  291. class SegmentationModel(DetectionModel):
  292. """YOLOv5 segmentation model for object detection and segmentation tasks with configurable parameters."""
  293. def __init__(self, cfg="yolov5s-seg.yaml", ch=3, nc=None, anchors=None):
  294. """Initializes a YOLOv5 segmentation model with configurable params: cfg (str) for configuration, ch (int) for channels, nc (int) for num classes, anchors (list)."""
  295. super().__init__(cfg, ch, nc, anchors)
  296. class ClassificationModel(BaseModel):
  297. """YOLOv5 classification model for image classification tasks, initialized with a config file or detection model."""
  298. def __init__(self, cfg=None, model=None, nc=1000, cutoff=10):
  299. """Initializes YOLOv5 model with config file `cfg`, input channels `ch`, number of classes `nc`, and `cuttoff`
  300. index.
  301. """
  302. super().__init__()
  303. self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
  304. def _from_detection_model(self, model, nc=1000, cutoff=10):
  305. """Creates a classification model from a YOLOv5 detection model, slicing at `cutoff` and adding a classification
  306. layer.
  307. """
  308. if isinstance(model, DetectMultiBackend):
  309. model = model.model # unwrap DetectMultiBackend
  310. model.model = model.model[:cutoff] # backbone
  311. m = model.model[-1] # last layer
  312. ch = m.conv.in_channels if hasattr(m, "conv") else m.cv1.conv.in_channels # ch into module
  313. c = Classify(ch, nc) # Classify()
  314. c.i, c.f, c.type = m.i, m.f, "models.common.Classify" # index, from, type
  315. model.model[-1] = c # replace
  316. self.model = model.model
  317. self.stride = model.stride
  318. self.save = []
  319. self.nc = nc
  320. def _from_yaml(self, cfg):
  321. """Creates a YOLOv5 classification model from a specified *.yaml configuration file."""
  322. self.model = None
  323. def parse_model(d, ch):
  324. """Parses a YOLOv5 model from a dict `d`, configuring layers based on input channels `ch` and model architecture."""
  325. LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
  326. anchors, nc, gd, gw, act, ch_mul = (
  327. d["anchors"],
  328. d["nc"],
  329. d["depth_multiple"],
  330. d["width_multiple"],
  331. d.get("activation"),
  332. d.get("channel_multiple"),
  333. )
  334. if act:
  335. Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
  336. LOGGER.info(f"{colorstr('activation:')} {act}") # print
  337. if not ch_mul:
  338. ch_mul = 8
  339. na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
  340. no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
  341. layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
  342. for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
  343. m = eval(m) if isinstance(m, str) else m # eval strings
  344. for j, a in enumerate(args):
  345. with contextlib.suppress(NameError):
  346. args[j] = eval(a) if isinstance(a, str) else a # eval strings
  347. n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
  348. if m in {
  349. Conv,
  350. GhostConv,
  351. Bottleneck,
  352. GhostBottleneck,
  353. SPP,
  354. SPPF,
  355. DWConv,
  356. MixConv2d,
  357. Focus,
  358. CrossConv,
  359. BottleneckCSP,
  360. C3,
  361. C3TR,
  362. C3SPP,
  363. C3Ghost,
  364. nn.ConvTranspose2d,
  365. DWConvTranspose2d,
  366. C3x,
  367. }:
  368. c1, c2 = ch[f], args[0]
  369. if c2 != no: # if not output
  370. c2 = make_divisible(c2 * gw, ch_mul)
  371. args = [c1, c2, *args[1:]]
  372. if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
  373. args.insert(2, n) # number of repeats
  374. n = 1
  375. elif m is nn.BatchNorm2d:
  376. args = [ch[f]]
  377. elif m is Concat:
  378. c2 = sum(ch[x] for x in f)
  379. # TODO: channel, gw, gd
  380. elif m in {Detect, Segment}:
  381. args.append([ch[x] for x in f])
  382. if isinstance(args[1], int): # number of anchors
  383. args[1] = [list(range(args[1] * 2))] * len(f)
  384. if m is Segment:
  385. args[3] = make_divisible(args[3] * gw, ch_mul)
  386. elif m is Contract:
  387. c2 = ch[f] * args[0] ** 2
  388. elif m is Expand:
  389. c2 = ch[f] // args[0] ** 2
  390. else:
  391. c2 = ch[f]
  392. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  393. t = str(m)[8:-2].replace("__main__.", "") # module type
  394. np = sum(x.numel() for x in m_.parameters()) # number params
  395. m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
  396. LOGGER.info(f"{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}") # print
  397. save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  398. layers.append(m_)
  399. if i == 0:
  400. ch = []
  401. ch.append(c2)
  402. return nn.Sequential(*layers), sorted(save)
  403. if __name__ == "__main__":
  404. parser = argparse.ArgumentParser()
  405. parser.add_argument("--cfg", type=str, default="yolov5s.yaml", help="model.yaml")
  406. parser.add_argument("--batch-size", type=int, default=1, help="total batch size for all GPUs")
  407. parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
  408. parser.add_argument("--profile", action="store_true", help="profile model speed")
  409. parser.add_argument("--line-profile", action="store_true", help="profile model speed layer by layer")
  410. parser.add_argument("--test", action="store_true", help="test all yolo*.yaml")
  411. opt = parser.parse_args()
  412. opt.cfg = check_yaml(opt.cfg) # check YAML
  413. print_args(vars(opt))
  414. device = select_device(opt.device)
  415. # Create model
  416. im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
  417. model = Model(opt.cfg).to(device)
  418. # Options
  419. if opt.line_profile: # profile layer by layer
  420. model(im, profile=True)
  421. elif opt.profile: # profile forward-backward
  422. results = profile(input=im, ops=[model], n=3)
  423. elif opt.test: # test all models
  424. for cfg in Path(ROOT / "models").rglob("yolo*.yaml"):
  425. try:
  426. _ = Model(cfg)
  427. except Exception as e:
  428. print(f"Error in {cfg}: {e}")
  429. else: # report fused model summary
  430. model.fuse()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...