Vasudevakrishna commited on
Commit
f267ae4
1 Parent(s): 982819a

S15 added.

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +3 -0
  2. app.py +76 -0
  3. data/custom_data.yaml +6 -0
  4. examples/341.jpg +0 -0
  5. examples/342.jpg +0 -0
  6. examples/343.jpg +0 -0
  7. examples/344.jpg +0 -0
  8. examples/345.jpg +0 -0
  9. examples/346.jpg +0 -0
  10. examples/347.jpg +0 -0
  11. examples/348.jpg +0 -0
  12. examples/349.jpg +0 -0
  13. examples/350.jpg +0 -0
  14. models/__init__.py +1 -0
  15. models/common.py +1200 -0
  16. models/detect/gelan-c.yaml +80 -0
  17. models/detect/gelan-e.yaml +121 -0
  18. models/detect/gelan.yaml +80 -0
  19. models/detect/yolov7-af.yaml +137 -0
  20. models/detect/yolov9-c.yaml +124 -0
  21. models/detect/yolov9-e.yaml +144 -0
  22. models/detect/yolov9.yaml +117 -0
  23. models/experimental.py +107 -0
  24. models/hub/anchors.yaml +59 -0
  25. models/hub/yolov3-spp.yaml +51 -0
  26. models/hub/yolov3-tiny.yaml +41 -0
  27. models/hub/yolov3.yaml +51 -0
  28. models/panoptic/yolov7-af-pan.yaml +137 -0
  29. models/segment/yolov7-af-seg.yaml +136 -0
  30. models/tf.py +596 -0
  31. models/yolo.py +763 -0
  32. requirements.txt +47 -0
  33. utils/__init__.py +75 -0
  34. utils/activations.py +98 -0
  35. utils/augmentations.py +395 -0
  36. utils/autoanchor.py +164 -0
  37. utils/autobatch.py +67 -0
  38. utils/callbacks.py +71 -0
  39. utils/dataloaders.py +1217 -0
  40. utils/downloads.py +103 -0
  41. utils/general.py +1135 -0
  42. utils/lion.py +67 -0
  43. utils/loggers/__init__.py +399 -0
  44. utils/loggers/clearml/__init__.py +1 -0
  45. utils/loggers/clearml/clearml_utils.py +157 -0
  46. utils/loggers/clearml/hpo.py +84 -0
  47. utils/loggers/comet/__init__.py +508 -0
  48. utils/loggers/comet/comet_utils.py +150 -0
  49. utils/loggers/comet/hpo.py +118 -0
  50. utils/loggers/comet/optimizer_config.json +209 -0
README.md CHANGED
@@ -11,3 +11,6 @@ license: mit
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
15
+ This app will detect Buffalos in the image.
16
+ Try out with different images.
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2, os
2
+ import gradio as gr
3
+ import numpy as np
4
+ import torch
5
+ from models.common import DetectMultiBackend
6
+ from utils.augmentations import letterbox
7
+ from utils.general import non_max_suppression, scale_boxes
8
+ from utils.plots import Annotator, colors, save_one_box
9
+ from utils.torch_utils import select_device
10
+
11
+ # path = r"C:\Users\H504171\U_Personal\YoloV3\data\buffalo\Test\341.jpg"
12
+ img_size = 640
13
+ stride = 32
14
+ auto = True
15
+ max_det=1000
16
+ classes = None
17
+ agnostic_nms = False
18
+ line_thickness = 3
19
+
20
+ # Load model
21
+ device = select_device('cpu')
22
+ dnn =False
23
+ data = "data/custom_data.yaml"
24
+ weights = "weights/best.pt"
25
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=False)
26
+
27
+
28
+
29
+ def inference(image, iou_thres, conf_thres):
30
+ im = letterbox(image, img_size, stride=stride, auto=auto)[0] # padded resize
31
+ im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
32
+ im = np.ascontiguousarray(im) # contiguous
33
+ im = torch.from_numpy(im).to(model.device)
34
+ im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
35
+ im /= 255 # 0 - 255 to 0.0 - 1.0
36
+ if len(im.shape) == 3:
37
+ im = im[None]
38
+ pred = model(im, augment=False, visualize=False)
39
+ pred = pred[0][1] if isinstance(pred[0], list) else pred[0]
40
+ pred = non_max_suppression(pred, conf_thres, iou_thres, None, agnostic_nms, max_det=max_det)
41
+
42
+ # Process predictions
43
+ for i, det in enumerate(pred): # per image
44
+ gn = torch.tensor(image.shape)[[1, 0, 1, 0]] # normalization gain whwh
45
+ imc = image.copy()
46
+ annotator = Annotator(image, line_width=line_thickness, example=str({0:'buffalo'}))
47
+ if len(det):
48
+ # Rescale boxes from img_size to im0 size
49
+ det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], image.shape).round()
50
+
51
+ # Print results
52
+ for c in det[:, 5].unique():
53
+ n = (det[:, 5] == c).sum() # detections per class
54
+
55
+ # Write results
56
+ for *xyxy, conf, cls in reversed(det):
57
+ c = int(cls) # integer class
58
+ label = 'buffalo'
59
+ annotator.box_label(xyxy, label, color=colors(c, True))
60
+ # Stream results
61
+ im0 = annotator.result()
62
+ return im0
63
+
64
+
65
+ title = "YOLO V9 trained on Custom Dataset"
66
+ description = "Gradio interface to show yoloV9 object detection."
67
+ examples = [[f'examples/{i}'] for i in os.listdir("examples")]
68
+ demo = gr.Interface(
69
+ inference,
70
+ inputs = [gr.Image(height=640, width = 640, label="Input Image"), gr.Slider(0, 1, value = 0.5, label="IOU Value"), gr.Slider(0, 1, value = 0.5, label="Threshold Value")],
71
+ outputs = [gr.Image(label="YoloV9 Output", height=640, width = 640)],
72
+ title = title,
73
+ description = description,
74
+ examples = examples,
75
+ )
76
+ demo.launch()
data/custom_data.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ train: data/buffalo/train/images
2
+ val: data/buffalo/val/images
3
+ test: data/buffalo/test/images
4
+
5
+ nc: 1
6
+ names: ["buffalo"]
examples/341.jpg ADDED
examples/342.jpg ADDED
examples/343.jpg ADDED
examples/344.jpg ADDED
examples/345.jpg ADDED
examples/346.jpg ADDED
examples/347.jpg ADDED
examples/348.jpg ADDED
examples/349.jpg ADDED
examples/350.jpg ADDED
models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # init
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()
requirements.txt ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # requirements
2
+ # Usage: pip install -r requirements.txt
3
+
4
+ # Base ------------------------------------------------------------------------
5
+ gitpython
6
+ ipython
7
+ matplotlib>=3.2.2
8
+ numpy>=1.18.5
9
+ opencv-python>=4.1.1
10
+ Pillow>=7.1.2
11
+ psutil
12
+ PyYAML>=5.3.1
13
+ requests>=2.23.0
14
+ scipy>=1.4.1
15
+ thop>=0.1.1
16
+ torch>=1.7.0
17
+ torchvision>=0.8.1
18
+ tqdm>=4.64.0
19
+ # protobuf<=3.20.1
20
+
21
+ # Logging ---------------------------------------------------------------------
22
+ tensorboard>=2.4.1
23
+ # clearml>=1.2.0
24
+ # comet
25
+
26
+ # Plotting --------------------------------------------------------------------
27
+ pandas>=1.1.4
28
+ seaborn>=0.11.0
29
+
30
+ # Export ----------------------------------------------------------------------
31
+ # coremltools>=6.0
32
+ # onnx>=1.9.0
33
+ # onnx-simplifier>=0.4.1
34
+ # nvidia-pyindex
35
+ # nvidia-tensorrt
36
+ # scikit-learn<=1.1.2
37
+ # tensorflow>=2.4.1
38
+ # tensorflowjs>=3.9.0
39
+ # openvino-dev
40
+
41
+ # Deploy ----------------------------------------------------------------------
42
+ # tritonclient[all]~=2.24.0
43
+
44
+ # Extras ----------------------------------------------------------------------
45
+ # mss
46
+ albumentations>=1.0.3
47
+ pycocotools>=2.0
utils/__init__.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import platform
3
+ import threading
4
+
5
+
6
+ def emojis(str=''):
7
+ # Return platform-dependent emoji-safe version of string
8
+ return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
9
+
10
+
11
+ class TryExcept(contextlib.ContextDecorator):
12
+ # YOLOv5 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager
13
+ def __init__(self, msg=''):
14
+ self.msg = msg
15
+
16
+ def __enter__(self):
17
+ pass
18
+
19
+ def __exit__(self, exc_type, value, traceback):
20
+ if value:
21
+ print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
22
+ return True
23
+
24
+
25
+ def threaded(func):
26
+ # Multi-threads a target function and returns thread. Usage: @threaded decorator
27
+ def wrapper(*args, **kwargs):
28
+ thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
29
+ thread.start()
30
+ return thread
31
+
32
+ return wrapper
33
+
34
+
35
+ def join_threads(verbose=False):
36
+ # Join all daemon threads, i.e. atexit.register(lambda: join_threads())
37
+ main_thread = threading.current_thread()
38
+ for t in threading.enumerate():
39
+ if t is not main_thread:
40
+ if verbose:
41
+ print(f'Joining thread {t.name}')
42
+ t.join()
43
+
44
+
45
+ def notebook_init(verbose=True):
46
+ # Check system software and hardware
47
+ print('Checking setup...')
48
+
49
+ import os
50
+ import shutil
51
+
52
+ from utils.general import check_font, check_requirements, is_colab
53
+ from utils.torch_utils import select_device # imports
54
+
55
+ check_font()
56
+
57
+ import psutil
58
+ from IPython import display # to display images and clear console output
59
+
60
+ if is_colab():
61
+ shutil.rmtree('/content/sample_data', ignore_errors=True) # remove colab /sample_data directory
62
+
63
+ # System info
64
+ if verbose:
65
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
66
+ ram = psutil.virtual_memory().total
67
+ total, used, free = shutil.disk_usage("/")
68
+ display.clear_output()
69
+ s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)'
70
+ else:
71
+ s = ''
72
+
73
+ select_device(newline=False)
74
+ print(emojis(f'Setup complete ✅ {s}'))
75
+ return display
utils/activations.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class SiLU(nn.Module):
7
+ # SiLU activation https://arxiv.org/pdf/1606.08415.pdf
8
+ @staticmethod
9
+ def forward(x):
10
+ return x * torch.sigmoid(x)
11
+
12
+
13
+ class Hardswish(nn.Module):
14
+ # Hard-SiLU activation
15
+ @staticmethod
16
+ def forward(x):
17
+ # return x * F.hardsigmoid(x) # for TorchScript and CoreML
18
+ return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
19
+
20
+
21
+ class Mish(nn.Module):
22
+ # Mish activation https://github.com/digantamisra98/Mish
23
+ @staticmethod
24
+ def forward(x):
25
+ return x * F.softplus(x).tanh()
26
+
27
+
28
+ class MemoryEfficientMish(nn.Module):
29
+ # Mish activation memory-efficient
30
+ class F(torch.autograd.Function):
31
+
32
+ @staticmethod
33
+ def forward(ctx, x):
34
+ ctx.save_for_backward(x)
35
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
36
+
37
+ @staticmethod
38
+ def backward(ctx, grad_output):
39
+ x = ctx.saved_tensors[0]
40
+ sx = torch.sigmoid(x)
41
+ fx = F.softplus(x).tanh()
42
+ return grad_output * (fx + x * sx * (1 - fx * fx))
43
+
44
+ def forward(self, x):
45
+ return self.F.apply(x)
46
+
47
+
48
+ class FReLU(nn.Module):
49
+ # FReLU activation https://arxiv.org/abs/2007.11824
50
+ def __init__(self, c1, k=3): # ch_in, kernel
51
+ super().__init__()
52
+ self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
53
+ self.bn = nn.BatchNorm2d(c1)
54
+
55
+ def forward(self, x):
56
+ return torch.max(x, self.bn(self.conv(x)))
57
+
58
+
59
+ class AconC(nn.Module):
60
+ r""" ACON activation (activate or not)
61
+ AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
62
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
63
+ """
64
+
65
+ def __init__(self, c1):
66
+ super().__init__()
67
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
68
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
69
+ self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
70
+
71
+ def forward(self, x):
72
+ dpx = (self.p1 - self.p2) * x
73
+ return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
74
+
75
+
76
+ class MetaAconC(nn.Module):
77
+ r""" ACON activation (activate or not)
78
+ MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
79
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
80
+ """
81
+
82
+ def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
83
+ super().__init__()
84
+ c2 = max(r, c1 // r)
85
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
86
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
87
+ self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
88
+ self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
89
+ # self.bn1 = nn.BatchNorm2d(c2)
90
+ # self.bn2 = nn.BatchNorm2d(c1)
91
+
92
+ def forward(self, x):
93
+ y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
94
+ # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
95
+ # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
96
+ beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
97
+ dpx = (self.p1 - self.p2) * x
98
+ return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
utils/augmentations.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+ import torchvision.transforms as T
8
+ import torchvision.transforms.functional as TF
9
+
10
+ from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
11
+ from utils.metrics import bbox_ioa
12
+
13
+ IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean
14
+ IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation
15
+
16
+
17
+ class Albumentations:
18
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
19
+ def __init__(self, size=640):
20
+ self.transform = None
21
+ prefix = colorstr('albumentations: ')
22
+ try:
23
+ import albumentations as A
24
+ check_version(A.__version__, '1.0.3', hard=True) # version requirement
25
+
26
+ T = [
27
+ A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),
28
+ A.Blur(p=0.01),
29
+ A.MedianBlur(p=0.01),
30
+ A.ToGray(p=0.01),
31
+ A.CLAHE(p=0.01),
32
+ A.RandomBrightnessContrast(p=0.0),
33
+ A.RandomGamma(p=0.0),
34
+ A.ImageCompression(quality_lower=75, p=0.0)] # transforms
35
+ self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
36
+
37
+ LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
38
+ except ImportError: # package not installed, skip
39
+ pass
40
+ except Exception as e:
41
+ LOGGER.info(f'{prefix}{e}')
42
+
43
+ def __call__(self, im, labels, p=1.0):
44
+ if self.transform and random.random() < p:
45
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
46
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
47
+ return im, labels
48
+
49
+
50
+ def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
51
+ # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std
52
+ return TF.normalize(x, mean, std, inplace=inplace)
53
+
54
+
55
+ def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
56
+ # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean
57
+ for i in range(3):
58
+ x[:, i] = x[:, i] * std[i] + mean[i]
59
+ return x
60
+
61
+
62
+ def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
63
+ # HSV color-space augmentation
64
+ if hgain or sgain or vgain:
65
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
66
+ hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
67
+ dtype = im.dtype # uint8
68
+
69
+ x = np.arange(0, 256, dtype=r.dtype)
70
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
71
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
72
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
73
+
74
+ im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
75
+ cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
76
+
77
+
78
+ def hist_equalize(im, clahe=True, bgr=False):
79
+ # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
80
+ yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
81
+ if clahe:
82
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
83
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
84
+ else:
85
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
86
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
87
+
88
+
89
+ def replicate(im, labels):
90
+ # Replicate labels
91
+ h, w = im.shape[:2]
92
+ boxes = labels[:, 1:].astype(int)
93
+ x1, y1, x2, y2 = boxes.T
94
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
95
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
96
+ x1b, y1b, x2b, y2b = boxes[i]
97
+ bh, bw = y2b - y1b, x2b - x1b
98
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
99
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
100
+ im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
101
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
102
+
103
+ return im, labels
104
+
105
+
106
+ def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
107
+ # Resize and pad image while meeting stride-multiple constraints
108
+ shape = im.shape[:2] # current shape [height, width]
109
+ if isinstance(new_shape, int):
110
+ new_shape = (new_shape, new_shape)
111
+
112
+ # Scale ratio (new / old)
113
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
114
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
115
+ r = min(r, 1.0)
116
+
117
+ # Compute padding
118
+ ratio = r, r # width, height ratios
119
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
120
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
121
+ if auto: # minimum rectangle
122
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
123
+ elif scaleFill: # stretch
124
+ dw, dh = 0.0, 0.0
125
+ new_unpad = (new_shape[1], new_shape[0])
126
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
127
+
128
+ dw /= 2 # divide padding into 2 sides
129
+ dh /= 2
130
+
131
+ if shape[::-1] != new_unpad: # resize
132
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
133
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
134
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
135
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
136
+ return im, ratio, (dw, dh)
137
+
138
+
139
+ def random_perspective(im,
140
+ targets=(),
141
+ segments=(),
142
+ degrees=10,
143
+ translate=.1,
144
+ scale=.1,
145
+ shear=10,
146
+ perspective=0.0,
147
+ border=(0, 0)):
148
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
149
+ # targets = [cls, xyxy]
150
+
151
+ height = im.shape[0] + border[0] * 2 # shape(h,w,c)
152
+ width = im.shape[1] + border[1] * 2
153
+
154
+ # Center
155
+ C = np.eye(3)
156
+ C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
157
+ C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
158
+
159
+ # Perspective
160
+ P = np.eye(3)
161
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
162
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
163
+
164
+ # Rotation and Scale
165
+ R = np.eye(3)
166
+ a = random.uniform(-degrees, degrees)
167
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
168
+ s = random.uniform(1 - scale, 1 + scale)
169
+ # s = 2 ** random.uniform(-scale, scale)
170
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
171
+
172
+ # Shear
173
+ S = np.eye(3)
174
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
175
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
176
+
177
+ # Translation
178
+ T = np.eye(3)
179
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
180
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
181
+
182
+ # Combined rotation matrix
183
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
184
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
185
+ if perspective:
186
+ im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
187
+ else: # affine
188
+ im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
189
+
190
+ # Visualize
191
+ # import matplotlib.pyplot as plt
192
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
193
+ # ax[0].imshow(im[:, :, ::-1]) # base
194
+ # ax[1].imshow(im2[:, :, ::-1]) # warped
195
+
196
+ # Transform label coordinates
197
+ n = len(targets)
198
+ if n:
199
+ use_segments = any(x.any() for x in segments)
200
+ new = np.zeros((n, 4))
201
+ if use_segments: # warp segments
202
+ segments = resample_segments(segments) # upsample
203
+ for i, segment in enumerate(segments):
204
+ xy = np.ones((len(segment), 3))
205
+ xy[:, :2] = segment
206
+ xy = xy @ M.T # transform
207
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
208
+
209
+ # clip
210
+ new[i] = segment2box(xy, width, height)
211
+
212
+ else: # warp boxes
213
+ xy = np.ones((n * 4, 3))
214
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
215
+ xy = xy @ M.T # transform
216
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
217
+
218
+ # create new boxes
219
+ x = xy[:, [0, 2, 4, 6]]
220
+ y = xy[:, [1, 3, 5, 7]]
221
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
222
+
223
+ # clip
224
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
225
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
226
+
227
+ # filter candidates
228
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
229
+ targets = targets[i]
230
+ targets[:, 1:5] = new[i]
231
+
232
+ return im, targets
233
+
234
+
235
+ def copy_paste(im, labels, segments, p=0.5):
236
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
237
+ n = len(segments)
238
+ if p and n:
239
+ h, w, c = im.shape # height, width, channels
240
+ im_new = np.zeros(im.shape, np.uint8)
241
+
242
+ # calculate ioa first then select indexes randomly
243
+ boxes = np.stack([w - labels[:, 3], labels[:, 2], w - labels[:, 1], labels[:, 4]], axis=-1) # (n, 4)
244
+ ioa = bbox_ioa(boxes, labels[:, 1:5]) # intersection over area
245
+ indexes = np.nonzero((ioa < 0.30).all(1))[0] # (N, )
246
+ n = len(indexes)
247
+ for j in random.sample(list(indexes), k=round(p * n)):
248
+ l, box, s = labels[j], boxes[j], segments[j]
249
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
250
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
251
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)
252
+
253
+ result = cv2.flip(im, 1) # augment segments (flip left-right)
254
+ i = cv2.flip(im_new, 1).astype(bool)
255
+ im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
256
+
257
+ return im, labels, segments
258
+
259
+
260
+ def cutout(im, labels, p=0.5):
261
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
262
+ if random.random() < p:
263
+ h, w = im.shape[:2]
264
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
265
+ for s in scales:
266
+ mask_h = random.randint(1, int(h * s)) # create random masks
267
+ mask_w = random.randint(1, int(w * s))
268
+
269
+ # box
270
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
271
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
272
+ xmax = min(w, xmin + mask_w)
273
+ ymax = min(h, ymin + mask_h)
274
+
275
+ # apply random color mask
276
+ im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
277
+
278
+ # return unobscured labels
279
+ if len(labels) and s > 0.03:
280
+ box = np.array([[xmin, ymin, xmax, ymax]], dtype=np.float32)
281
+ ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h))[0] # intersection over area
282
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
283
+
284
+ return labels
285
+
286
+
287
+ def mixup(im, labels, im2, labels2):
288
+ # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
289
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
290
+ im = (im * r + im2 * (1 - r)).astype(np.uint8)
291
+ labels = np.concatenate((labels, labels2), 0)
292
+ return im, labels
293
+
294
+
295
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
296
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
297
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
298
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
299
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
300
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
301
+
302
+
303
+ def classify_albumentations(
304
+ augment=True,
305
+ size=224,
306
+ scale=(0.08, 1.0),
307
+ ratio=(0.75, 1.0 / 0.75), # 0.75, 1.33
308
+ hflip=0.5,
309
+ vflip=0.0,
310
+ jitter=0.4,
311
+ mean=IMAGENET_MEAN,
312
+ std=IMAGENET_STD,
313
+ auto_aug=False):
314
+ # YOLOv5 classification Albumentations (optional, only used if package is installed)
315
+ prefix = colorstr('albumentations: ')
316
+ try:
317
+ import albumentations as A
318
+ from albumentations.pytorch import ToTensorV2
319
+ check_version(A.__version__, '1.0.3', hard=True) # version requirement
320
+ if augment: # Resize and crop
321
+ T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]
322
+ if auto_aug:
323
+ # TODO: implement AugMix, AutoAug & RandAug in albumentation
324
+ LOGGER.info(f'{prefix}auto augmentations are currently not supported')
325
+ else:
326
+ if hflip > 0:
327
+ T += [A.HorizontalFlip(p=hflip)]
328
+ if vflip > 0:
329
+ T += [A.VerticalFlip(p=vflip)]
330
+ if jitter > 0:
331
+ color_jitter = (float(jitter),) * 3 # repeat value for brightness, contrast, satuaration, 0 hue
332
+ T += [A.ColorJitter(*color_jitter, 0)]
333
+ else: # Use fixed crop for eval set (reproducibility)
334
+ T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
335
+ T += [A.Normalize(mean=mean, std=std), ToTensorV2()] # Normalize and convert to Tensor
336
+ LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
337
+ return A.Compose(T)
338
+
339
+ except ImportError: # package not installed, skip
340
+ LOGGER.warning(f'{prefix}⚠️ not found, install with `pip install albumentations` (recommended)')
341
+ except Exception as e:
342
+ LOGGER.info(f'{prefix}{e}')
343
+
344
+
345
+ def classify_transforms(size=224):
346
+ # Transforms to apply if albumentations not installed
347
+ assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'
348
+ # T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
349
+ return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
350
+
351
+
352
+ class LetterBox:
353
+ # YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
354
+ def __init__(self, size=(640, 640), auto=False, stride=32):
355
+ super().__init__()
356
+ self.h, self.w = (size, size) if isinstance(size, int) else size
357
+ self.auto = auto # pass max size integer, automatically solve for short side using stride
358
+ self.stride = stride # used with auto
359
+
360
+ def __call__(self, im): # im = np.array HWC
361
+ imh, imw = im.shape[:2]
362
+ r = min(self.h / imh, self.w / imw) # ratio of new/old
363
+ h, w = round(imh * r), round(imw * r) # resized image
364
+ hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w
365
+ top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
366
+ im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)
367
+ im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
368
+ return im_out
369
+
370
+
371
+ class CenterCrop:
372
+ # YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])
373
+ def __init__(self, size=640):
374
+ super().__init__()
375
+ self.h, self.w = (size, size) if isinstance(size, int) else size
376
+
377
+ def __call__(self, im): # im = np.array HWC
378
+ imh, imw = im.shape[:2]
379
+ m = min(imh, imw) # min dimension
380
+ top, left = (imh - m) // 2, (imw - m) // 2
381
+ return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
382
+
383
+
384
+ class ToTensor:
385
+ # YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
386
+ def __init__(self, half=False):
387
+ super().__init__()
388
+ self.half = half
389
+
390
+ def __call__(self, im): # im = np.array HWC in BGR order
391
+ im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
392
+ im = torch.from_numpy(im) # to torch
393
+ im = im.half() if self.half else im.float() # uint8 to fp16/32
394
+ im /= 255.0 # 0-255 to 0.0-1.0
395
+ return im
utils/autoanchor.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import numpy as np
4
+ import torch
5
+ import yaml
6
+ from tqdm import tqdm
7
+
8
+ from utils import TryExcept
9
+ from utils.general import LOGGER, TQDM_BAR_FORMAT, colorstr
10
+
11
+ PREFIX = colorstr('AutoAnchor: ')
12
+
13
+
14
+ def check_anchor_order(m):
15
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
16
+ a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer
17
+ da = a[-1] - a[0] # delta a
18
+ ds = m.stride[-1] - m.stride[0] # delta s
19
+ if da and (da.sign() != ds.sign()): # same order
20
+ LOGGER.info(f'{PREFIX}Reversing anchor order')
21
+ m.anchors[:] = m.anchors.flip(0)
22
+
23
+
24
+ @TryExcept(f'{PREFIX}ERROR')
25
+ def check_anchors(dataset, model, thr=4.0, imgsz=640):
26
+ # Check anchor fit to data, recompute if necessary
27
+ m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
28
+ shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
29
+ scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
30
+ wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
31
+
32
+ def metric(k): # compute metric
33
+ r = wh[:, None] / k[None]
34
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
35
+ best = x.max(1)[0] # best_x
36
+ aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold
37
+ bpr = (best > 1 / thr).float().mean() # best possible recall
38
+ return bpr, aat
39
+
40
+ stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides
41
+ anchors = m.anchors.clone() * stride # current anchors
42
+ bpr, aat = metric(anchors.cpu().view(-1, 2))
43
+ s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). '
44
+ if bpr > 0.98: # threshold to recompute
45
+ LOGGER.info(f'{s}Current anchors are a good fit to dataset ✅')
46
+ else:
47
+ LOGGER.info(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...')
48
+ na = m.anchors.numel() // 2 # number of anchors
49
+ anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
50
+ new_bpr = metric(anchors)[0]
51
+ if new_bpr > bpr: # replace anchors
52
+ anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
53
+ m.anchors[:] = anchors.clone().view_as(m.anchors)
54
+ check_anchor_order(m) # must be in pixel-space (not grid-space)
55
+ m.anchors /= stride
56
+ s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)'
57
+ else:
58
+ s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)'
59
+ LOGGER.info(s)
60
+
61
+
62
+ def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
63
+ """ Creates kmeans-evolved anchors from training dataset
64
+
65
+ Arguments:
66
+ dataset: path to data.yaml, or a loaded dataset
67
+ n: number of anchors
68
+ img_size: image size used for training
69
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
70
+ gen: generations to evolve anchors using genetic algorithm
71
+ verbose: print all results
72
+
73
+ Return:
74
+ k: kmeans evolved anchors
75
+
76
+ Usage:
77
+ from utils.autoanchor import *; _ = kmean_anchors()
78
+ """
79
+ from scipy.cluster.vq import kmeans
80
+
81
+ npr = np.random
82
+ thr = 1 / thr
83
+
84
+ def metric(k, wh): # compute metrics
85
+ r = wh[:, None] / k[None]
86
+ x = torch.min(r, 1 / r).min(2)[0] # ratio metric
87
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
88
+ return x, x.max(1)[0] # x, best_x
89
+
90
+ def anchor_fitness(k): # mutation fitness
91
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
92
+ return (best * (best > thr).float()).mean() # fitness
93
+
94
+ def print_results(k, verbose=True):
95
+ k = k[np.argsort(k.prod(1))] # sort small to large
96
+ x, best = metric(k, wh0)
97
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
98
+ s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \
99
+ f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \
100
+ f'past_thr={x[x > thr].mean():.3f}-mean: '
101
+ for x in k:
102
+ s += '%i,%i, ' % (round(x[0]), round(x[1]))
103
+ if verbose:
104
+ LOGGER.info(s[:-2])
105
+ return k
106
+
107
+ if isinstance(dataset, str): # *.yaml file
108
+ with open(dataset, errors='ignore') as f:
109
+ data_dict = yaml.safe_load(f) # model dict
110
+ from utils.dataloaders import LoadImagesAndLabels
111
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
112
+
113
+ # Get label wh
114
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
115
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
116
+
117
+ # Filter
118
+ i = (wh0 < 3.0).any(1).sum()
119
+ if i:
120
+ LOGGER.info(f'{PREFIX}WARNING ⚠️ Extremely small objects found: {i} of {len(wh0)} labels are <3 pixels in size')
121
+ wh = wh0[(wh0 >= 2.0).any(1)].astype(np.float32) # filter > 2 pixels
122
+ # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
123
+
124
+ # Kmeans init
125
+ try:
126
+ LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')
127
+ assert n <= len(wh) # apply overdetermined constraint
128
+ s = wh.std(0) # sigmas for whitening
129
+ k = kmeans(wh / s, n, iter=30)[0] * s # points
130
+ assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar
131
+ except Exception:
132
+ LOGGER.warning(f'{PREFIX}WARNING ⚠️ switching strategies from kmeans to random init')
133
+ k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init
134
+ wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))
135
+ k = print_results(k, verbose=False)
136
+
137
+ # Plot
138
+ # k, d = [None] * 20, [None] * 20
139
+ # for i in tqdm(range(1, 21)):
140
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
141
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
142
+ # ax = ax.ravel()
143
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
144
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
145
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
146
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
147
+ # fig.savefig('wh.png', dpi=200)
148
+
149
+ # Evolve
150
+ f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
151
+ pbar = tqdm(range(gen), bar_format=TQDM_BAR_FORMAT) # progress bar
152
+ for _ in pbar:
153
+ v = np.ones(sh)
154
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
155
+ v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
156
+ kg = (k.copy() * v).clip(min=2.0)
157
+ fg = anchor_fitness(kg)
158
+ if fg > f:
159
+ f, k = fg, kg.copy()
160
+ pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
161
+ if verbose:
162
+ print_results(k, verbose)
163
+
164
+ return print_results(k).astype(np.float32)
utils/autobatch.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+
3
+ import numpy as np
4
+ import torch
5
+
6
+ from utils.general import LOGGER, colorstr
7
+ from utils.torch_utils import profile
8
+
9
+
10
+ def check_train_batch_size(model, imgsz=640, amp=True):
11
+ # Check YOLOv5 training batch size
12
+ with torch.cuda.amp.autocast(amp):
13
+ return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
14
+
15
+
16
+ def autobatch(model, imgsz=640, fraction=0.8, batch_size=16):
17
+ # Automatically estimate best YOLOv5 batch size to use `fraction` of available CUDA memory
18
+ # Usage:
19
+ # import torch
20
+ # from utils.autobatch import autobatch
21
+ # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
22
+ # print(autobatch(model))
23
+
24
+ # Check device
25
+ prefix = colorstr('AutoBatch: ')
26
+ LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')
27
+ device = next(model.parameters()).device # get model device
28
+ if device.type == 'cpu':
29
+ LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')
30
+ return batch_size
31
+ if torch.backends.cudnn.benchmark:
32
+ LOGGER.info(f'{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}')
33
+ return batch_size
34
+
35
+ # Inspect CUDA memory
36
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
37
+ d = str(device).upper() # 'CUDA:0'
38
+ properties = torch.cuda.get_device_properties(device) # device properties
39
+ t = properties.total_memory / gb # GiB total
40
+ r = torch.cuda.memory_reserved(device) / gb # GiB reserved
41
+ a = torch.cuda.memory_allocated(device) / gb # GiB allocated
42
+ f = t - (r + a) # GiB free
43
+ LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
44
+
45
+ # Profile batch sizes
46
+ batch_sizes = [1, 2, 4, 8, 16]
47
+ try:
48
+ img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
49
+ results = profile(img, model, n=3, device=device)
50
+ except Exception as e:
51
+ LOGGER.warning(f'{prefix}{e}')
52
+
53
+ # Fit a solution
54
+ y = [x[2] for x in results if x] # memory [2]
55
+ p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit
56
+ b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
57
+ if None in results: # some sizes failed
58
+ i = results.index(None) # first fail index
59
+ if b >= batch_sizes[i]: # y intercept above failure point
60
+ b = batch_sizes[max(i - 1, 0)] # select prior safe point
61
+ if b < 1 or b > 1024: # b outside of safe range
62
+ b = batch_size
63
+ LOGGER.warning(f'{prefix}WARNING ⚠️ CUDA anomaly detected, recommend restart environment and retry command.')
64
+
65
+ fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted
66
+ LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')
67
+ return b
utils/callbacks.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+
3
+
4
+ class Callbacks:
5
+ """"
6
+ Handles all registered callbacks for YOLOv5 Hooks
7
+ """
8
+
9
+ def __init__(self):
10
+ # Define the available callbacks
11
+ self._callbacks = {
12
+ 'on_pretrain_routine_start': [],
13
+ 'on_pretrain_routine_end': [],
14
+ 'on_train_start': [],
15
+ 'on_train_epoch_start': [],
16
+ 'on_train_batch_start': [],
17
+ 'optimizer_step': [],
18
+ 'on_before_zero_grad': [],
19
+ 'on_train_batch_end': [],
20
+ 'on_train_epoch_end': [],
21
+ 'on_val_start': [],
22
+ 'on_val_batch_start': [],
23
+ 'on_val_image_end': [],
24
+ 'on_val_batch_end': [],
25
+ 'on_val_end': [],
26
+ 'on_fit_epoch_end': [], # fit = train + val
27
+ 'on_model_save': [],
28
+ 'on_train_end': [],
29
+ 'on_params_update': [],
30
+ 'teardown': [],}
31
+ self.stop_training = False # set True to interrupt training
32
+
33
+ def register_action(self, hook, name='', callback=None):
34
+ """
35
+ Register a new action to a callback hook
36
+
37
+ Args:
38
+ hook: The callback hook name to register the action to
39
+ name: The name of the action for later reference
40
+ callback: The callback to fire
41
+ """
42
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
43
+ assert callable(callback), f"callback '{callback}' is not callable"
44
+ self._callbacks[hook].append({'name': name, 'callback': callback})
45
+
46
+ def get_registered_actions(self, hook=None):
47
+ """"
48
+ Returns all the registered actions by callback hook
49
+
50
+ Args:
51
+ hook: The name of the hook to check, defaults to all
52
+ """
53
+ return self._callbacks[hook] if hook else self._callbacks
54
+
55
+ def run(self, hook, *args, thread=False, **kwargs):
56
+ """
57
+ Loop through the registered actions and fire all callbacks on main thread
58
+
59
+ Args:
60
+ hook: The name of the hook to check, defaults to all
61
+ args: Arguments to receive from YOLOv5
62
+ thread: (boolean) Run callbacks in daemon thread
63
+ kwargs: Keyword Arguments to receive from YOLOv5
64
+ """
65
+
66
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
67
+ for logger in self._callbacks[hook]:
68
+ if thread:
69
+ threading.Thread(target=logger['callback'], args=args, kwargs=kwargs, daemon=True).start()
70
+ else:
71
+ logger['callback'](*args, **kwargs)
utils/dataloaders.py ADDED
@@ -0,0 +1,1217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import glob
3
+ import hashlib
4
+ import json
5
+ import math
6
+ import os
7
+ import random
8
+ import shutil
9
+ import time
10
+ from itertools import repeat
11
+ from multiprocessing.pool import Pool, ThreadPool
12
+ from pathlib import Path
13
+ from threading import Thread
14
+ from urllib.parse import urlparse
15
+
16
+ import numpy as np
17
+ import psutil
18
+ import torch
19
+ import torch.nn.functional as F
20
+ import torchvision
21
+ import yaml
22
+ from PIL import ExifTags, Image, ImageOps
23
+ from torch.utils.data import DataLoader, Dataset, dataloader, distributed
24
+ from tqdm import tqdm
25
+
26
+ from utils.augmentations import (Albumentations, augment_hsv, classify_albumentations, classify_transforms, copy_paste,
27
+ letterbox, mixup, random_perspective)
28
+ from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, check_dataset, check_requirements,
29
+ check_yaml, clean_str, cv2, is_colab, is_kaggle, segments2boxes, unzip_file, xyn2xy,
30
+ xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
31
+ from utils.torch_utils import torch_distributed_zero_first
32
+
33
+ # Parameters
34
+ HELP_URL = 'See https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
35
+ IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm' # include image suffixes
36
+ VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes
37
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
38
+ RANK = int(os.getenv('RANK', -1))
39
+ PIN_MEMORY = str(os.getenv('PIN_MEMORY', True)).lower() == 'true' # global pin_memory for dataloaders
40
+
41
+ # Get orientation exif tag
42
+ for orientation in ExifTags.TAGS.keys():
43
+ if ExifTags.TAGS[orientation] == 'Orientation':
44
+ break
45
+
46
+
47
+ def get_hash(paths):
48
+ # Returns a single hash value of a list of paths (files or dirs)
49
+ size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
50
+ h = hashlib.md5(str(size).encode()) # hash sizes
51
+ h.update(''.join(paths).encode()) # hash paths
52
+ return h.hexdigest() # return hash
53
+
54
+
55
+ def exif_size(img):
56
+ # Returns exif-corrected PIL size
57
+ s = img.size # (width, height)
58
+ with contextlib.suppress(Exception):
59
+ rotation = dict(img._getexif().items())[orientation]
60
+ if rotation in [6, 8]: # rotation 270 or 90
61
+ s = (s[1], s[0])
62
+ return s
63
+
64
+
65
+ def exif_transpose(image):
66
+ """
67
+ Transpose a PIL image accordingly if it has an EXIF Orientation tag.
68
+ Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
69
+
70
+ :param image: The image to transpose.
71
+ :return: An image.
72
+ """
73
+ exif = image.getexif()
74
+ orientation = exif.get(0x0112, 1) # default 1
75
+ if orientation > 1:
76
+ method = {
77
+ 2: Image.FLIP_LEFT_RIGHT,
78
+ 3: Image.ROTATE_180,
79
+ 4: Image.FLIP_TOP_BOTTOM,
80
+ 5: Image.TRANSPOSE,
81
+ 6: Image.ROTATE_270,
82
+ 7: Image.TRANSVERSE,
83
+ 8: Image.ROTATE_90}.get(orientation)
84
+ if method is not None:
85
+ image = image.transpose(method)
86
+ del exif[0x0112]
87
+ image.info["exif"] = exif.tobytes()
88
+ return image
89
+
90
+
91
+ def seed_worker(worker_id):
92
+ # Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader
93
+ worker_seed = torch.initial_seed() % 2 ** 32
94
+ np.random.seed(worker_seed)
95
+ random.seed(worker_seed)
96
+
97
+
98
+ def create_dataloader(path,
99
+ imgsz,
100
+ batch_size,
101
+ stride,
102
+ single_cls=False,
103
+ hyp=None,
104
+ augment=False,
105
+ cache=False,
106
+ pad=0.0,
107
+ rect=False,
108
+ rank=-1,
109
+ workers=8,
110
+ image_weights=False,
111
+ close_mosaic=False,
112
+ quad=False,
113
+ min_items=0,
114
+ prefix='',
115
+ shuffle=False):
116
+ if rect and shuffle:
117
+ LOGGER.warning('WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False')
118
+ shuffle = False
119
+ with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
120
+ dataset = LoadImagesAndLabels(
121
+ path,
122
+ imgsz,
123
+ batch_size,
124
+ augment=augment, # augmentation
125
+ hyp=hyp, # hyperparameters
126
+ rect=rect, # rectangular batches
127
+ cache_images=cache,
128
+ single_cls=single_cls,
129
+ stride=int(stride),
130
+ pad=pad,
131
+ image_weights=image_weights,
132
+ min_items=min_items,
133
+ prefix=prefix)
134
+
135
+ batch_size = min(batch_size, len(dataset))
136
+ nd = torch.cuda.device_count() # number of CUDA devices
137
+ nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers
138
+ sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
139
+ #loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates
140
+ loader = DataLoader if image_weights or close_mosaic else InfiniteDataLoader
141
+ generator = torch.Generator()
142
+ generator.manual_seed(6148914691236517205 + RANK)
143
+ return loader(dataset,
144
+ batch_size=batch_size,
145
+ shuffle=shuffle and sampler is None,
146
+ num_workers=nw,
147
+ sampler=sampler,
148
+ pin_memory=PIN_MEMORY,
149
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn,
150
+ worker_init_fn=seed_worker,
151
+ generator=generator), dataset
152
+
153
+
154
+ class InfiniteDataLoader(dataloader.DataLoader):
155
+ """ Dataloader that reuses workers
156
+
157
+ Uses same syntax as vanilla DataLoader
158
+ """
159
+
160
+ def __init__(self, *args, **kwargs):
161
+ super().__init__(*args, **kwargs)
162
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
163
+ self.iterator = super().__iter__()
164
+
165
+ def __len__(self):
166
+ return len(self.batch_sampler.sampler)
167
+
168
+ def __iter__(self):
169
+ for _ in range(len(self)):
170
+ yield next(self.iterator)
171
+
172
+
173
+ class _RepeatSampler:
174
+ """ Sampler that repeats forever
175
+
176
+ Args:
177
+ sampler (Sampler)
178
+ """
179
+
180
+ def __init__(self, sampler):
181
+ self.sampler = sampler
182
+
183
+ def __iter__(self):
184
+ while True:
185
+ yield from iter(self.sampler)
186
+
187
+
188
+ class LoadScreenshots:
189
+ # YOLOv5 screenshot dataloader, i.e. `python detect.py --source "screen 0 100 100 512 256"`
190
+ def __init__(self, source, img_size=640, stride=32, auto=True, transforms=None):
191
+ # source = [screen_number left top width height] (pixels)
192
+ check_requirements('mss')
193
+ import mss
194
+
195
+ source, *params = source.split()
196
+ self.screen, left, top, width, height = 0, None, None, None, None # default to full screen 0
197
+ if len(params) == 1:
198
+ self.screen = int(params[0])
199
+ elif len(params) == 4:
200
+ left, top, width, height = (int(x) for x in params)
201
+ elif len(params) == 5:
202
+ self.screen, left, top, width, height = (int(x) for x in params)
203
+ self.img_size = img_size
204
+ self.stride = stride
205
+ self.transforms = transforms
206
+ self.auto = auto
207
+ self.mode = 'stream'
208
+ self.frame = 0
209
+ self.sct = mss.mss()
210
+
211
+ # Parse monitor shape
212
+ monitor = self.sct.monitors[self.screen]
213
+ self.top = monitor["top"] if top is None else (monitor["top"] + top)
214
+ self.left = monitor["left"] if left is None else (monitor["left"] + left)
215
+ self.width = width or monitor["width"]
216
+ self.height = height or monitor["height"]
217
+ self.monitor = {"left": self.left, "top": self.top, "width": self.width, "height": self.height}
218
+
219
+ def __iter__(self):
220
+ return self
221
+
222
+ def __next__(self):
223
+ # mss screen capture: get raw pixels from the screen as np array
224
+ im0 = np.array(self.sct.grab(self.monitor))[:, :, :3] # [:, :, :3] BGRA to BGR
225
+ s = f"screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: "
226
+
227
+ if self.transforms:
228
+ im = self.transforms(im0) # transforms
229
+ else:
230
+ im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0] # padded resize
231
+ im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
232
+ im = np.ascontiguousarray(im) # contiguous
233
+ self.frame += 1
234
+ return str(self.screen), im, im0, None, s # screen, img, original img, im0s, s
235
+
236
+
237
+ class LoadImages:
238
+ # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`
239
+ def __init__(self, path, img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
240
+ files = []
241
+ for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
242
+ p = str(Path(p).resolve())
243
+ if '*' in p:
244
+ files.extend(sorted(glob.glob(p, recursive=True))) # glob
245
+ elif os.path.isdir(p):
246
+ files.extend(sorted(glob.glob(os.path.join(p, '*.*')))) # dir
247
+ elif os.path.isfile(p):
248
+ files.append(p) # files
249
+ else:
250
+ raise FileNotFoundError(f'{p} does not exist')
251
+
252
+ images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
253
+ videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
254
+ ni, nv = len(images), len(videos)
255
+
256
+ self.img_size = img_size
257
+ self.stride = stride
258
+ self.files = images + videos
259
+ self.nf = ni + nv # number of files
260
+ self.video_flag = [False] * ni + [True] * nv
261
+ self.mode = 'image'
262
+ self.auto = auto
263
+ self.transforms = transforms # optional
264
+ self.vid_stride = vid_stride # video frame-rate stride
265
+ if any(videos):
266
+ self._new_video(videos[0]) # new video
267
+ else:
268
+ self.cap = None
269
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
270
+ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
271
+
272
+ def __iter__(self):
273
+ self.count = 0
274
+ return self
275
+
276
+ def __next__(self):
277
+ if self.count == self.nf:
278
+ raise StopIteration
279
+ path = self.files[self.count]
280
+
281
+ if self.video_flag[self.count]:
282
+ # Read video
283
+ self.mode = 'video'
284
+ for _ in range(self.vid_stride):
285
+ self.cap.grab()
286
+ ret_val, im0 = self.cap.retrieve()
287
+ while not ret_val:
288
+ self.count += 1
289
+ self.cap.release()
290
+ if self.count == self.nf: # last video
291
+ raise StopIteration
292
+ path = self.files[self.count]
293
+ self._new_video(path)
294
+ ret_val, im0 = self.cap.read()
295
+
296
+ self.frame += 1
297
+ # im0 = self._cv2_rotate(im0) # for use if cv2 autorotation is False
298
+ s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '
299
+
300
+ else:
301
+ # Read image
302
+ self.count += 1
303
+ im0 = cv2.imread(path) # BGR
304
+ assert im0 is not None, f'Image Not Found {path}'
305
+ s = f'image {self.count}/{self.nf} {path}: '
306
+
307
+ if self.transforms:
308
+ im = self.transforms(im0) # transforms
309
+ else:
310
+ im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0] # padded resize
311
+ im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
312
+ im = np.ascontiguousarray(im) # contiguous
313
+
314
+ return path, im, im0, self.cap, s
315
+
316
+ def _new_video(self, path):
317
+ # Create a new video capture object
318
+ self.frame = 0
319
+ self.cap = cv2.VideoCapture(path)
320
+ self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)
321
+ self.orientation = int(self.cap.get(cv2.CAP_PROP_ORIENTATION_META)) # rotation degrees
322
+ # self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0) # disable https://github.com/ultralytics/yolov5/issues/8493
323
+
324
+ def _cv2_rotate(self, im):
325
+ # Rotate a cv2 video manually
326
+ if self.orientation == 0:
327
+ return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)
328
+ elif self.orientation == 180:
329
+ return cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)
330
+ elif self.orientation == 90:
331
+ return cv2.rotate(im, cv2.ROTATE_180)
332
+ return im
333
+
334
+ def __len__(self):
335
+ return self.nf # number of files
336
+
337
+
338
+ class LoadStreams:
339
+ # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams`
340
+ def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
341
+ torch.backends.cudnn.benchmark = True # faster for fixed-size inference
342
+ self.mode = 'stream'
343
+ self.img_size = img_size
344
+ self.stride = stride
345
+ self.vid_stride = vid_stride # video frame-rate stride
346
+ sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]
347
+ n = len(sources)
348
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
349
+ self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
350
+ for i, s in enumerate(sources): # index, source
351
+ # Start thread to read frames from video stream
352
+ st = f'{i + 1}/{n}: {s}... '
353
+ if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'): # if source is YouTube video
354
+ # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/Zgi9g1ksQHc'
355
+ check_requirements(('pafy', 'youtube_dl==2020.12.2'))
356
+ import pafy
357
+ s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
358
+ s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
359
+ if s == 0:
360
+ assert not is_colab(), '--source 0 webcam unsupported on Colab. Rerun command in a local environment.'
361
+ assert not is_kaggle(), '--source 0 webcam unsupported on Kaggle. Rerun command in a local environment.'
362
+ cap = cv2.VideoCapture(s)
363
+ assert cap.isOpened(), f'{st}Failed to open {s}'
364
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
365
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
366
+ fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan
367
+ self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
368
+ self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback
369
+
370
+ _, self.imgs[i] = cap.read() # guarantee first frame
371
+ self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)
372
+ LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
373
+ self.threads[i].start()
374
+ LOGGER.info('') # newline
375
+
376
+ # check for common shapes
377
+ s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs])
378
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
379
+ self.auto = auto and self.rect
380
+ self.transforms = transforms # optional
381
+ if not self.rect:
382
+ LOGGER.warning('WARNING ⚠️ Stream shapes differ. For optimal performance supply similarly-shaped streams.')
383
+
384
+ def update(self, i, cap, stream):
385
+ # Read stream `i` frames in daemon thread
386
+ n, f = 0, self.frames[i] # frame number, frame array
387
+ while cap.isOpened() and n < f:
388
+ n += 1
389
+ cap.grab() # .read() = .grab() followed by .retrieve()
390
+ if n % self.vid_stride == 0:
391
+ success, im = cap.retrieve()
392
+ if success:
393
+ self.imgs[i] = im
394
+ else:
395
+ LOGGER.warning('WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.')
396
+ self.imgs[i] = np.zeros_like(self.imgs[i])
397
+ cap.open(stream) # re-open stream if signal was lost
398
+ time.sleep(0.0) # wait time
399
+
400
+ def __iter__(self):
401
+ self.count = -1
402
+ return self
403
+
404
+ def __next__(self):
405
+ self.count += 1
406
+ if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
407
+ cv2.destroyAllWindows()
408
+ raise StopIteration
409
+
410
+ im0 = self.imgs.copy()
411
+ if self.transforms:
412
+ im = np.stack([self.transforms(x) for x in im0]) # transforms
413
+ else:
414
+ im = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0] for x in im0]) # resize
415
+ im = im[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
416
+ im = np.ascontiguousarray(im) # contiguous
417
+
418
+ return self.sources, im, im0, None, ''
419
+
420
+ def __len__(self):
421
+ return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
422
+
423
+
424
+ def img2label_paths(img_paths):
425
+ # Define label paths as a function of image paths
426
+ sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings
427
+ return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
428
+
429
+
430
+ class LoadImagesAndLabels(Dataset):
431
+ # YOLOv5 train_loader/val_loader, loads images and labels for training and validation
432
+ cache_version = 0.6 # dataset labels *.cache version
433
+ rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
434
+
435
+ def __init__(self,
436
+ path,
437
+ img_size=640,
438
+ batch_size=16,
439
+ augment=False,
440
+ hyp=None,
441
+ rect=False,
442
+ image_weights=False,
443
+ cache_images=False,
444
+ single_cls=False,
445
+ stride=32,
446
+ pad=0.0,
447
+ min_items=0,
448
+ prefix=''):
449
+ self.img_size = img_size
450
+ self.augment = augment
451
+ self.hyp = hyp
452
+ self.image_weights = image_weights
453
+ self.rect = False if image_weights else rect
454
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
455
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
456
+ self.stride = stride
457
+ self.path = path
458
+ self.albumentations = Albumentations(size=img_size) if augment else None
459
+
460
+ try:
461
+ f = [] # image files
462
+ for p in path if isinstance(path, list) else [path]:
463
+ p = Path(p) # os-agnostic
464
+ if p.is_dir(): # dir
465
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
466
+ # f = list(p.rglob('*.*')) # pathlib
467
+ elif p.is_file(): # file
468
+ with open(p) as t:
469
+ t = t.read().strip().splitlines()
470
+ parent = str(p.parent) + os.sep
471
+ f += [x.replace('./', parent, 1) if x.startswith('./') else x for x in t] # to global path
472
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # to global path (pathlib)
473
+ else:
474
+ raise FileNotFoundError(f'{prefix}{p} does not exist')
475
+ self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)
476
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib
477
+ assert self.im_files, f'{prefix}No images found'
478
+ except Exception as e:
479
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\n{HELP_URL}') from e
480
+
481
+ # Check cache
482
+ self.label_files = img2label_paths(self.im_files) # labels
483
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
484
+ try:
485
+ cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
486
+ assert cache['version'] == self.cache_version # matches current version
487
+ assert cache['hash'] == get_hash(self.label_files + self.im_files) # identical hash
488
+ except Exception:
489
+ cache, exists = self.cache_labels(cache_path, prefix), False # run cache ops
490
+
491
+ # Display cache
492
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total
493
+ if exists and LOCAL_RANK in {-1, 0}:
494
+ d = f"Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt"
495
+ tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT) # display cache results
496
+ if cache['msgs']:
497
+ LOGGER.info('\n'.join(cache['msgs'])) # display warnings
498
+ assert nf > 0 or not augment, f'{prefix}No labels found in {cache_path}, can not start training. {HELP_URL}'
499
+
500
+ # Read cache
501
+ [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
502
+ labels, shapes, self.segments = zip(*cache.values())
503
+ nl = len(np.concatenate(labels, 0)) # number of labels
504
+ assert nl > 0 or not augment, f'{prefix}All labels empty in {cache_path}, can not start training. {HELP_URL}'
505
+ self.labels = list(labels)
506
+ self.shapes = np.array(shapes)
507
+ self.im_files = list(cache.keys()) # update
508
+ self.label_files = img2label_paths(cache.keys()) # update
509
+
510
+ # Filter images
511
+ if min_items:
512
+ include = np.array([len(x) >= min_items for x in self.labels]).nonzero()[0].astype(int)
513
+ LOGGER.info(f'{prefix}{n - len(include)}/{n} images filtered from dataset')
514
+ self.im_files = [self.im_files[i] for i in include]
515
+ self.label_files = [self.label_files[i] for i in include]
516
+ self.labels = [self.labels[i] for i in include]
517
+ self.segments = [self.segments[i] for i in include]
518
+ self.shapes = self.shapes[include] # wh
519
+
520
+ # Create indices
521
+ n = len(self.shapes) # number of images
522
+ bi = np.floor(np.arange(n) / batch_size).astype(int) # batch index
523
+ nb = bi[-1] + 1 # number of batches
524
+ self.batch = bi # batch index of image
525
+ self.n = n
526
+ self.indices = range(n)
527
+
528
+ # Update labels
529
+ include_class = [] # filter labels to include only these classes (optional)
530
+ include_class_array = np.array(include_class).reshape(1, -1)
531
+ for i, (label, segment) in enumerate(zip(self.labels, self.segments)):
532
+ if include_class:
533
+ j = (label[:, 0:1] == include_class_array).any(1)
534
+ self.labels[i] = label[j]
535
+ if segment:
536
+ self.segments[i] = segment[j]
537
+ if single_cls: # single-class training, merge all classes into 0
538
+ self.labels[i][:, 0] = 0
539
+
540
+ # Rectangular Training
541
+ if self.rect:
542
+ # Sort by aspect ratio
543
+ s = self.shapes # wh
544
+ ar = s[:, 1] / s[:, 0] # aspect ratio
545
+ irect = ar.argsort()
546
+ self.im_files = [self.im_files[i] for i in irect]
547
+ self.label_files = [self.label_files[i] for i in irect]
548
+ self.labels = [self.labels[i] for i in irect]
549
+ self.segments = [self.segments[i] for i in irect]
550
+ self.shapes = s[irect] # wh
551
+ ar = ar[irect]
552
+
553
+ # Set training image shapes
554
+ shapes = [[1, 1]] * nb
555
+ for i in range(nb):
556
+ ari = ar[bi == i]
557
+ mini, maxi = ari.min(), ari.max()
558
+ if maxi < 1:
559
+ shapes[i] = [maxi, 1]
560
+ elif mini > 1:
561
+ shapes[i] = [1, 1 / mini]
562
+
563
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(int) * stride
564
+
565
+ # Cache images into RAM/disk for faster training
566
+ if cache_images == 'ram' and not self.check_cache_ram(prefix=prefix):
567
+ cache_images = False
568
+ self.ims = [None] * n
569
+ self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]
570
+ if cache_images:
571
+ b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes
572
+ self.im_hw0, self.im_hw = [None] * n, [None] * n
573
+ fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image
574
+ results = ThreadPool(NUM_THREADS).imap(fcn, range(n))
575
+ pbar = tqdm(enumerate(results), total=n, bar_format=TQDM_BAR_FORMAT, disable=LOCAL_RANK > 0)
576
+ for i, x in pbar:
577
+ if cache_images == 'disk':
578
+ b += self.npy_files[i].stat().st_size
579
+ else: # 'ram'
580
+ self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
581
+ b += self.ims[i].nbytes
582
+ pbar.desc = f'{prefix}Caching images ({b / gb:.1f}GB {cache_images})'
583
+ pbar.close()
584
+
585
+ def check_cache_ram(self, safety_margin=0.1, prefix=''):
586
+ # Check image caching requirements vs available memory
587
+ b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes
588
+ n = min(self.n, 30) # extrapolate from 30 random images
589
+ for _ in range(n):
590
+ im = cv2.imread(random.choice(self.im_files)) # sample image
591
+ ratio = self.img_size / max(im.shape[0], im.shape[1]) # max(h, w) # ratio
592
+ b += im.nbytes * ratio ** 2
593
+ mem_required = b * self.n / n # GB required to cache dataset into RAM
594
+ mem = psutil.virtual_memory()
595
+ cache = mem_required * (1 + safety_margin) < mem.available # to cache or not to cache, that is the question
596
+ if not cache:
597
+ LOGGER.info(f"{prefix}{mem_required / gb:.1f}GB RAM required, "
598
+ f"{mem.available / gb:.1f}/{mem.total / gb:.1f}GB available, "
599
+ f"{'caching images ✅' if cache else 'not caching images ⚠️'}")
600
+ return cache
601
+
602
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
603
+ # Cache dataset labels, check images and read shapes
604
+ x = {} # dict
605
+ nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
606
+ desc = f"{prefix}Scanning {path.parent / path.stem}..."
607
+ with Pool(NUM_THREADS) as pool:
608
+ pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))),
609
+ desc=desc,
610
+ total=len(self.im_files),
611
+ bar_format=TQDM_BAR_FORMAT)
612
+ for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
613
+ nm += nm_f
614
+ nf += nf_f
615
+ ne += ne_f
616
+ nc += nc_f
617
+ if im_file:
618
+ x[im_file] = [lb, shape, segments]
619
+ if msg:
620
+ msgs.append(msg)
621
+ pbar.desc = f"{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt"
622
+
623
+ pbar.close()
624
+ if msgs:
625
+ LOGGER.info('\n'.join(msgs))
626
+ if nf == 0:
627
+ LOGGER.warning(f'{prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}')
628
+ x['hash'] = get_hash(self.label_files + self.im_files)
629
+ x['results'] = nf, nm, ne, nc, len(self.im_files)
630
+ x['msgs'] = msgs # warnings
631
+ x['version'] = self.cache_version # cache version
632
+ try:
633
+ np.save(path, x) # save cache for next time
634
+ path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
635
+ LOGGER.info(f'{prefix}New cache created: {path}')
636
+ except Exception as e:
637
+ LOGGER.warning(f'{prefix}WARNING ⚠️ Cache directory {path.parent} is not writeable: {e}') # not writeable
638
+ return x
639
+
640
+ def __len__(self):
641
+ return len(self.im_files)
642
+
643
+ # def __iter__(self):
644
+ # self.count = -1
645
+ # print('ran dataset iter')
646
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
647
+ # return self
648
+
649
+ def __getitem__(self, index):
650
+ index = self.indices[index] # linear, shuffled, or image_weights
651
+
652
+ hyp = self.hyp
653
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
654
+ if mosaic:
655
+ # Load mosaic
656
+ img, labels = self.load_mosaic(index)
657
+ shapes = None
658
+
659
+ # MixUp augmentation
660
+ if random.random() < hyp['mixup']:
661
+ img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1)))
662
+
663
+ else:
664
+ # Load image
665
+ img, (h0, w0), (h, w) = self.load_image(index)
666
+
667
+ # Letterbox
668
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
669
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
670
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
671
+
672
+ labels = self.labels[index].copy()
673
+ if labels.size: # normalized xywh to pixel xyxy format
674
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
675
+
676
+ if self.augment:
677
+ img, labels = random_perspective(img,
678
+ labels,
679
+ degrees=hyp['degrees'],
680
+ translate=hyp['translate'],
681
+ scale=hyp['scale'],
682
+ shear=hyp['shear'],
683
+ perspective=hyp['perspective'])
684
+
685
+ nl = len(labels) # number of labels
686
+ if nl:
687
+ labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)
688
+
689
+ if self.augment:
690
+ # Albumentations
691
+ img, labels = self.albumentations(img, labels)
692
+ nl = len(labels) # update after albumentations
693
+
694
+ # HSV color-space
695
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
696
+
697
+ # Flip up-down
698
+ if random.random() < hyp['flipud']:
699
+ img = np.flipud(img)
700
+ if nl:
701
+ labels[:, 2] = 1 - labels[:, 2]
702
+
703
+ # Flip left-right
704
+ if random.random() < hyp['fliplr']:
705
+ img = np.fliplr(img)
706
+ if nl:
707
+ labels[:, 1] = 1 - labels[:, 1]
708
+
709
+ # Cutouts
710
+ # labels = cutout(img, labels, p=0.5)
711
+ # nl = len(labels) # update after cutout
712
+
713
+ labels_out = torch.zeros((nl, 6))
714
+ if nl:
715
+ labels_out[:, 1:] = torch.from_numpy(labels)
716
+
717
+ # Convert
718
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
719
+ img = np.ascontiguousarray(img)
720
+
721
+ return torch.from_numpy(img), labels_out, self.im_files[index], shapes
722
+
723
+ def load_image(self, i):
724
+ # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw)
725
+ im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i],
726
+ if im is None: # not cached in RAM
727
+ if fn.exists(): # load npy
728
+ im = np.load(fn)
729
+ else: # read image
730
+ im = cv2.imread(f) # BGR
731
+ assert im is not None, f'Image Not Found {f}'
732
+ h0, w0 = im.shape[:2] # orig hw
733
+ r = self.img_size / max(h0, w0) # ratio
734
+ if r != 1: # if sizes are not equal
735
+ interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA
736
+ im = cv2.resize(im, (int(w0 * r), int(h0 * r)), interpolation=interp)
737
+ return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
738
+ return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized
739
+
740
+ def cache_images_to_disk(self, i):
741
+ # Saves an image as an *.npy file for faster loading
742
+ f = self.npy_files[i]
743
+ if not f.exists():
744
+ np.save(f.as_posix(), cv2.imread(self.im_files[i]))
745
+
746
+ def load_mosaic(self, index):
747
+ # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic
748
+ labels4, segments4 = [], []
749
+ s = self.img_size
750
+ yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
751
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
752
+ random.shuffle(indices)
753
+ for i, index in enumerate(indices):
754
+ # Load image
755
+ img, _, (h, w) = self.load_image(index)
756
+
757
+ # place img in img4
758
+ if i == 0: # top left
759
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
760
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
761
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
762
+ elif i == 1: # top right
763
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
764
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
765
+ elif i == 2: # bottom left
766
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
767
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
768
+ elif i == 3: # bottom right
769
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
770
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
771
+
772
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
773
+ padw = x1a - x1b
774
+ padh = y1a - y1b
775
+
776
+ # Labels
777
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
778
+ if labels.size:
779
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
780
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
781
+ labels4.append(labels)
782
+ segments4.extend(segments)
783
+
784
+ # Concat/clip labels
785
+ labels4 = np.concatenate(labels4, 0)
786
+ for x in (labels4[:, 1:], *segments4):
787
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
788
+ # img4, labels4 = replicate(img4, labels4) # replicate
789
+
790
+ # Augment
791
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])
792
+ img4, labels4 = random_perspective(img4,
793
+ labels4,
794
+ segments4,
795
+ degrees=self.hyp['degrees'],
796
+ translate=self.hyp['translate'],
797
+ scale=self.hyp['scale'],
798
+ shear=self.hyp['shear'],
799
+ perspective=self.hyp['perspective'],
800
+ border=self.mosaic_border) # border to remove
801
+
802
+ return img4, labels4
803
+
804
+ def load_mosaic9(self, index):
805
+ # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic
806
+ labels9, segments9 = [], []
807
+ s = self.img_size
808
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
809
+ random.shuffle(indices)
810
+ hp, wp = -1, -1 # height, width previous
811
+ for i, index in enumerate(indices):
812
+ # Load image
813
+ img, _, (h, w) = self.load_image(index)
814
+
815
+ # place img in img9
816
+ if i == 0: # center
817
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
818
+ h0, w0 = h, w
819
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
820
+ elif i == 1: # top
821
+ c = s, s - h, s + w, s
822
+ elif i == 2: # top right
823
+ c = s + wp, s - h, s + wp + w, s
824
+ elif i == 3: # right
825
+ c = s + w0, s, s + w0 + w, s + h
826
+ elif i == 4: # bottom right
827
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
828
+ elif i == 5: # bottom
829
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
830
+ elif i == 6: # bottom left
831
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
832
+ elif i == 7: # left
833
+ c = s - w, s + h0 - h, s, s + h0
834
+ elif i == 8: # top left
835
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
836
+
837
+ padx, pady = c[:2]
838
+ x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
839
+
840
+ # Labels
841
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
842
+ if labels.size:
843
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
844
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
845
+ labels9.append(labels)
846
+ segments9.extend(segments)
847
+
848
+ # Image
849
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
850
+ hp, wp = h, w # height, width previous
851
+
852
+ # Offset
853
+ yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y
854
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
855
+
856
+ # Concat/clip labels
857
+ labels9 = np.concatenate(labels9, 0)
858
+ labels9[:, [1, 3]] -= xc
859
+ labels9[:, [2, 4]] -= yc
860
+ c = np.array([xc, yc]) # centers
861
+ segments9 = [x - c for x in segments9]
862
+
863
+ for x in (labels9[:, 1:], *segments9):
864
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
865
+ # img9, labels9 = replicate(img9, labels9) # replicate
866
+
867
+ # Augment
868
+ img9, labels9, segments9 = copy_paste(img9, labels9, segments9, p=self.hyp['copy_paste'])
869
+ img9, labels9 = random_perspective(img9,
870
+ labels9,
871
+ segments9,
872
+ degrees=self.hyp['degrees'],
873
+ translate=self.hyp['translate'],
874
+ scale=self.hyp['scale'],
875
+ shear=self.hyp['shear'],
876
+ perspective=self.hyp['perspective'],
877
+ border=self.mosaic_border) # border to remove
878
+
879
+ return img9, labels9
880
+
881
+ @staticmethod
882
+ def collate_fn(batch):
883
+ im, label, path, shapes = zip(*batch) # transposed
884
+ for i, lb in enumerate(label):
885
+ lb[:, 0] = i # add target image index for build_targets()
886
+ return torch.stack(im, 0), torch.cat(label, 0), path, shapes
887
+
888
+ @staticmethod
889
+ def collate_fn4(batch):
890
+ im, label, path, shapes = zip(*batch) # transposed
891
+ n = len(shapes) // 4
892
+ im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
893
+
894
+ ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])
895
+ wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])
896
+ s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale
897
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
898
+ i *= 4
899
+ if random.random() < 0.5:
900
+ im1 = F.interpolate(im[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear',
901
+ align_corners=False)[0].type(im[i].type())
902
+ lb = label[i]
903
+ else:
904
+ im1 = torch.cat((torch.cat((im[i], im[i + 1]), 1), torch.cat((im[i + 2], im[i + 3]), 1)), 2)
905
+ lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
906
+ im4.append(im1)
907
+ label4.append(lb)
908
+
909
+ for i, lb in enumerate(label4):
910
+ lb[:, 0] = i # add target image index for build_targets()
911
+
912
+ return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4
913
+
914
+
915
+ # Ancillary functions --------------------------------------------------------------------------------------------------
916
+ def flatten_recursive(path=DATASETS_DIR / 'coco128'):
917
+ # Flatten a recursive directory by bringing all files to top level
918
+ new_path = Path(f'{str(path)}_flat')
919
+ if os.path.exists(new_path):
920
+ shutil.rmtree(new_path) # delete output folder
921
+ os.makedirs(new_path) # make new output folder
922
+ for file in tqdm(glob.glob(f'{str(Path(path))}/**/*.*', recursive=True)):
923
+ shutil.copyfile(file, new_path / Path(file).name)
924
+
925
+
926
+ def extract_boxes(path=DATASETS_DIR / 'coco128'): # from utils.dataloaders import *; extract_boxes()
927
+ # Convert detection dataset into classification dataset, with one directory per class
928
+ path = Path(path) # images dir
929
+ shutil.rmtree(path / 'classification') if (path / 'classification').is_dir() else None # remove existing
930
+ files = list(path.rglob('*.*'))
931
+ n = len(files) # number of files
932
+ for im_file in tqdm(files, total=n):
933
+ if im_file.suffix[1:] in IMG_FORMATS:
934
+ # image
935
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
936
+ h, w = im.shape[:2]
937
+
938
+ # labels
939
+ lb_file = Path(img2label_paths([str(im_file)])[0])
940
+ if Path(lb_file).exists():
941
+ with open(lb_file) as f:
942
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
943
+
944
+ for j, x in enumerate(lb):
945
+ c = int(x[0]) # class
946
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
947
+ if not f.parent.is_dir():
948
+ f.parent.mkdir(parents=True)
949
+
950
+ b = x[1:] * [w, h, w, h] # box
951
+ # b[2:] = b[2:].max() # rectangle to square
952
+ b[2:] = b[2:] * 1.2 + 3 # pad
953
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(int)
954
+
955
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
956
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
957
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
958
+
959
+
960
+ def autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
961
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
962
+ Usage: from utils.dataloaders import *; autosplit()
963
+ Arguments
964
+ path: Path to images directory
965
+ weights: Train, val, test weights (list, tuple)
966
+ annotated_only: Only use images with an annotated txt file
967
+ """
968
+ path = Path(path) # images dir
969
+ files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only
970
+ n = len(files) # number of files
971
+ random.seed(0) # for reproducibility
972
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
973
+
974
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
975
+ for x in txt:
976
+ if (path.parent / x).exists():
977
+ (path.parent / x).unlink() # remove existing
978
+
979
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
980
+ for i, img in tqdm(zip(indices, files), total=n):
981
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
982
+ with open(path.parent / txt[i], 'a') as f:
983
+ f.write(f'./{img.relative_to(path.parent).as_posix()}' + '\n') # add image to txt file
984
+
985
+
986
+ def verify_image_label(args):
987
+ # Verify one image-label pair
988
+ im_file, lb_file, prefix = args
989
+ nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments
990
+ try:
991
+ # verify images
992
+ im = Image.open(im_file)
993
+ im.verify() # PIL verify
994
+ shape = exif_size(im) # image size
995
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
996
+ assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
997
+ if im.format.lower() in ('jpg', 'jpeg'):
998
+ with open(im_file, 'rb') as f:
999
+ f.seek(-2, 2)
1000
+ if f.read() != b'\xff\xd9': # corrupt JPEG
1001
+ ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
1002
+ msg = f'{prefix}WARNING ⚠️ {im_file}: corrupt JPEG restored and saved'
1003
+
1004
+ # verify labels
1005
+ if os.path.isfile(lb_file):
1006
+ nf = 1 # label found
1007
+ with open(lb_file) as f:
1008
+ lb = [x.split() for x in f.read().strip().splitlines() if len(x)]
1009
+ if any(len(x) > 6 for x in lb): # is segment
1010
+ classes = np.array([x[0] for x in lb], dtype=np.float32)
1011
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...)
1012
+ lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
1013
+ lb = np.array(lb, dtype=np.float32)
1014
+ nl = len(lb)
1015
+ if nl:
1016
+ assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'
1017
+ assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'
1018
+ assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'
1019
+ _, i = np.unique(lb, axis=0, return_index=True)
1020
+ if len(i) < nl: # duplicate row check
1021
+ lb = lb[i] # remove duplicates
1022
+ if segments:
1023
+ segments = [segments[x] for x in i]
1024
+ msg = f'{prefix}WARNING ⚠️ {im_file}: {nl - len(i)} duplicate labels removed'
1025
+ else:
1026
+ ne = 1 # label empty
1027
+ lb = np.zeros((0, 5), dtype=np.float32)
1028
+ else:
1029
+ nm = 1 # label missing
1030
+ lb = np.zeros((0, 5), dtype=np.float32)
1031
+ return im_file, lb, shape, segments, nm, nf, ne, nc, msg
1032
+ except Exception as e:
1033
+ nc = 1
1034
+ msg = f'{prefix}WARNING ⚠️ {im_file}: ignoring corrupt image/label: {e}'
1035
+ return [None, None, None, None, nm, nf, ne, nc, msg]
1036
+
1037
+
1038
+ class HUBDatasetStats():
1039
+ """ Class for generating HUB dataset JSON and `-hub` dataset directory
1040
+
1041
+ Arguments
1042
+ path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
1043
+ autodownload: Attempt to download dataset if not found locally
1044
+
1045
+ Usage
1046
+ from utils.dataloaders import HUBDatasetStats
1047
+ stats = HUBDatasetStats('coco128.yaml', autodownload=True) # usage 1
1048
+ stats = HUBDatasetStats('path/to/coco128.zip') # usage 2
1049
+ stats.get_json(save=False)
1050
+ stats.process_images()
1051
+ """
1052
+
1053
+ def __init__(self, path='coco128.yaml', autodownload=False):
1054
+ # Initialize class
1055
+ zipped, data_dir, yaml_path = self._unzip(Path(path))
1056
+ try:
1057
+ with open(check_yaml(yaml_path), errors='ignore') as f:
1058
+ data = yaml.safe_load(f) # data dict
1059
+ if zipped:
1060
+ data['path'] = data_dir
1061
+ except Exception as e:
1062
+ raise Exception("error/HUB/dataset_stats/yaml_load") from e
1063
+
1064
+ check_dataset(data, autodownload) # download dataset if missing
1065
+ self.hub_dir = Path(data['path'] + '-hub')
1066
+ self.im_dir = self.hub_dir / 'images'
1067
+ self.im_dir.mkdir(parents=True, exist_ok=True) # makes /images
1068
+ self.stats = {'nc': data['nc'], 'names': list(data['names'].values())} # statistics dictionary
1069
+ self.data = data
1070
+
1071
+ @staticmethod
1072
+ def _find_yaml(dir):
1073
+ # Return data.yaml file
1074
+ files = list(dir.glob('*.yaml')) or list(dir.rglob('*.yaml')) # try root level first and then recursive
1075
+ assert files, f'No *.yaml file found in {dir}'
1076
+ if len(files) > 1:
1077
+ files = [f for f in files if f.stem == dir.stem] # prefer *.yaml files that match dir name
1078
+ assert files, f'Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed'
1079
+ assert len(files) == 1, f'Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}'
1080
+ return files[0]
1081
+
1082
+ def _unzip(self, path):
1083
+ # Unzip data.zip
1084
+ if not str(path).endswith('.zip'): # path is data.yaml
1085
+ return False, None, path
1086
+ assert Path(path).is_file(), f'Error unzipping {path}, file not found'
1087
+ unzip_file(path, path=path.parent)
1088
+ dir = path.with_suffix('') # dataset directory == zip name
1089
+ assert dir.is_dir(), f'Error unzipping {path}, {dir} not found. path/to/abc.zip MUST unzip to path/to/abc/'
1090
+ return True, str(dir), self._find_yaml(dir) # zipped, data_dir, yaml_path
1091
+
1092
+ def _hub_ops(self, f, max_dim=1920):
1093
+ # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing
1094
+ f_new = self.im_dir / Path(f).name # dataset-hub image filename
1095
+ try: # use PIL
1096
+ im = Image.open(f)
1097
+ r = max_dim / max(im.height, im.width) # ratio
1098
+ if r < 1.0: # image too large
1099
+ im = im.resize((int(im.width * r), int(im.height * r)))
1100
+ im.save(f_new, 'JPEG', quality=50, optimize=True) # save
1101
+ except Exception as e: # use OpenCV
1102
+ LOGGER.info(f'WARNING ⚠️ HUB ops PIL failure {f}: {e}')
1103
+ im = cv2.imread(f)
1104
+ im_height, im_width = im.shape[:2]
1105
+ r = max_dim / max(im_height, im_width) # ratio
1106
+ if r < 1.0: # image too large
1107
+ im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)
1108
+ cv2.imwrite(str(f_new), im)
1109
+
1110
+ def get_json(self, save=False, verbose=False):
1111
+ # Return dataset JSON for Ultralytics HUB
1112
+ def _round(labels):
1113
+ # Update labels to integer class and 6 decimal place floats
1114
+ return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]
1115
+
1116
+ for split in 'train', 'val', 'test':
1117
+ if self.data.get(split) is None:
1118
+ self.stats[split] = None # i.e. no test set
1119
+ continue
1120
+ dataset = LoadImagesAndLabels(self.data[split]) # load dataset
1121
+ x = np.array([
1122
+ np.bincount(label[:, 0].astype(int), minlength=self.data['nc'])
1123
+ for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics')]) # shape(128x80)
1124
+ self.stats[split] = {
1125
+ 'instance_stats': {
1126
+ 'total': int(x.sum()),
1127
+ 'per_class': x.sum(0).tolist()},
1128
+ 'image_stats': {
1129
+ 'total': dataset.n,
1130
+ 'unlabelled': int(np.all(x == 0, 1).sum()),
1131
+ 'per_class': (x > 0).sum(0).tolist()},
1132
+ 'labels': [{
1133
+ str(Path(k).name): _round(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)]}
1134
+
1135
+ # Save, print and return
1136
+ if save:
1137
+ stats_path = self.hub_dir / 'stats.json'
1138
+ print(f'Saving {stats_path.resolve()}...')
1139
+ with open(stats_path, 'w') as f:
1140
+ json.dump(self.stats, f) # save stats.json
1141
+ if verbose:
1142
+ print(json.dumps(self.stats, indent=2, sort_keys=False))
1143
+ return self.stats
1144
+
1145
+ def process_images(self):
1146
+ # Compress images for Ultralytics HUB
1147
+ for split in 'train', 'val', 'test':
1148
+ if self.data.get(split) is None:
1149
+ continue
1150
+ dataset = LoadImagesAndLabels(self.data[split]) # load dataset
1151
+ desc = f'{split} images'
1152
+ for _ in tqdm(ThreadPool(NUM_THREADS).imap(self._hub_ops, dataset.im_files), total=dataset.n, desc=desc):
1153
+ pass
1154
+ print(f'Done. All images saved to {self.im_dir}')
1155
+ return self.im_dir
1156
+
1157
+
1158
+ # Classification dataloaders -------------------------------------------------------------------------------------------
1159
+ class ClassificationDataset(torchvision.datasets.ImageFolder):
1160
+ """
1161
+ YOLOv5 Classification Dataset.
1162
+ Arguments
1163
+ root: Dataset path
1164
+ transform: torchvision transforms, used by default
1165
+ album_transform: Albumentations transforms, used if installed
1166
+ """
1167
+
1168
+ def __init__(self, root, augment, imgsz, cache=False):
1169
+ super().__init__(root=root)
1170
+ self.torch_transforms = classify_transforms(imgsz)
1171
+ self.album_transforms = classify_albumentations(augment, imgsz) if augment else None
1172
+ self.cache_ram = cache is True or cache == 'ram'
1173
+ self.cache_disk = cache == 'disk'
1174
+ self.samples = [list(x) + [Path(x[0]).with_suffix('.npy'), None] for x in self.samples] # file, index, npy, im
1175
+
1176
+ def __getitem__(self, i):
1177
+ f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
1178
+ if self.cache_ram and im is None:
1179
+ im = self.samples[i][3] = cv2.imread(f)
1180
+ elif self.cache_disk:
1181
+ if not fn.exists(): # load npy
1182
+ np.save(fn.as_posix(), cv2.imread(f))
1183
+ im = np.load(fn)
1184
+ else: # read image
1185
+ im = cv2.imread(f) # BGR
1186
+ if self.album_transforms:
1187
+ sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))["image"]
1188
+ else:
1189
+ sample = self.torch_transforms(im)
1190
+ return sample, j
1191
+
1192
+
1193
+ def create_classification_dataloader(path,
1194
+ imgsz=224,
1195
+ batch_size=16,
1196
+ augment=True,
1197
+ cache=False,
1198
+ rank=-1,
1199
+ workers=8,
1200
+ shuffle=True):
1201
+ # Returns Dataloader object to be used with YOLOv5 Classifier
1202
+ with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
1203
+ dataset = ClassificationDataset(root=path, imgsz=imgsz, augment=augment, cache=cache)
1204
+ batch_size = min(batch_size, len(dataset))
1205
+ nd = torch.cuda.device_count()
1206
+ nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])
1207
+ sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
1208
+ generator = torch.Generator()
1209
+ generator.manual_seed(6148914691236517205 + RANK)
1210
+ return InfiniteDataLoader(dataset,
1211
+ batch_size=batch_size,
1212
+ shuffle=shuffle and sampler is None,
1213
+ num_workers=nw,
1214
+ sampler=sampler,
1215
+ pin_memory=PIN_MEMORY,
1216
+ worker_init_fn=seed_worker,
1217
+ generator=generator) # or DataLoader(persistent_workers=True)
utils/downloads.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import subprocess
4
+ import urllib
5
+ from pathlib import Path
6
+
7
+ import requests
8
+ import torch
9
+
10
+
11
+ def is_url(url, check=True):
12
+ # Check if string is URL and check if URL exists
13
+ try:
14
+ url = str(url)
15
+ result = urllib.parse.urlparse(url)
16
+ assert all([result.scheme, result.netloc]) # check if is url
17
+ return (urllib.request.urlopen(url).getcode() == 200) if check else True # check if exists online
18
+ except (AssertionError, urllib.request.HTTPError):
19
+ return False
20
+
21
+
22
+ def gsutil_getsize(url=''):
23
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
24
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
25
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
26
+
27
+
28
+ def url_getsize(url='https://ultralytics.com/images/bus.jpg'):
29
+ # Return downloadable file size in bytes
30
+ response = requests.head(url, allow_redirects=True)
31
+ return int(response.headers.get('content-length', -1))
32
+
33
+
34
+ def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
35
+ # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
36
+ from utils.general import LOGGER
37
+
38
+ file = Path(file)
39
+ assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
40
+ try: # url1
41
+ LOGGER.info(f'Downloading {url} to {file}...')
42
+ torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)
43
+ assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
44
+ except Exception as e: # url2
45
+ if file.exists():
46
+ file.unlink() # remove partial downloads
47
+ LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
48
+ os.system(f"curl -# -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
49
+ finally:
50
+ if not file.exists() or file.stat().st_size < min_bytes: # check
51
+ if file.exists():
52
+ file.unlink() # remove partial downloads
53
+ LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}")
54
+ LOGGER.info('')
55
+
56
+
57
+ def attempt_download(file, repo='ultralytics/yolov5', release='v7.0'):
58
+ # Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v7.0', etc.
59
+ from utils.general import LOGGER
60
+
61
+ def github_assets(repository, version='latest'):
62
+ # Return GitHub repo tag (i.e. 'v7.0') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...])
63
+ if version != 'latest':
64
+ version = f'tags/{version}' # i.e. tags/v7.0
65
+ response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api
66
+ return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets
67
+
68
+ file = Path(str(file).strip().replace("'", ''))
69
+ if not file.exists():
70
+ # URL specified
71
+ name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
72
+ if str(file).startswith(('http:/', 'https:/')): # download
73
+ url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
74
+ file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
75
+ if Path(file).is_file():
76
+ LOGGER.info(f'Found {url} locally at {file}') # file already exists
77
+ else:
78
+ safe_download(file=file, url=url, min_bytes=1E5)
79
+ return file
80
+
81
+ # GitHub assets
82
+ assets = [f'yolov5{size}{suffix}.pt' for size in 'nsmlx' for suffix in ('', '6', '-cls', '-seg')] # default
83
+ try:
84
+ tag, assets = github_assets(repo, release)
85
+ except Exception:
86
+ try:
87
+ tag, assets = github_assets(repo) # latest release
88
+ except Exception:
89
+ try:
90
+ tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
91
+ except Exception:
92
+ tag = release
93
+
94
+ file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
95
+ if name in assets:
96
+ url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror
97
+ safe_download(
98
+ file,
99
+ url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
100
+ min_bytes=1E5,
101
+ error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}')
102
+
103
+ return str(file)
utils/general.py ADDED
@@ -0,0 +1,1135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import glob
3
+ import inspect
4
+ import logging
5
+ import logging.config
6
+ import math
7
+ import os
8
+ import platform
9
+ import random
10
+ import re
11
+ import signal
12
+ import sys
13
+ import time
14
+ import urllib
15
+ from copy import deepcopy
16
+ from datetime import datetime
17
+ from itertools import repeat
18
+ from multiprocessing.pool import ThreadPool
19
+ from pathlib import Path
20
+ from subprocess import check_output
21
+ from tarfile import is_tarfile
22
+ from typing import Optional
23
+ from zipfile import ZipFile, is_zipfile
24
+
25
+ import cv2
26
+ import IPython
27
+ import numpy as np
28
+ import pandas as pd
29
+ import pkg_resources as pkg
30
+ import torch
31
+ import torchvision
32
+ import yaml
33
+
34
+ from utils import TryExcept, emojis
35
+ from utils.downloads import gsutil_getsize
36
+ from utils.metrics import box_iou, fitness
37
+
38
+ FILE = Path(__file__).resolve()
39
+ ROOT = FILE.parents[1] # YOLO root directory
40
+ RANK = int(os.getenv('RANK', -1))
41
+
42
+ # Settings
43
+ NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads
44
+ DATASETS_DIR = Path(os.getenv('YOLOv5_DATASETS_DIR', ROOT.parent / 'datasets')) # global datasets directory
45
+ AUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode
46
+ VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode
47
+ TQDM_BAR_FORMAT = '{l_bar}{bar:10}| {n_fmt}/{total_fmt} {elapsed}' # tqdm bar format
48
+ FONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf
49
+
50
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
51
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
52
+ pd.options.display.max_columns = 10
53
+ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
54
+ os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads
55
+ os.environ['OMP_NUM_THREADS'] = '1' if platform.system() == 'darwin' else str(NUM_THREADS) # OpenMP (PyTorch and SciPy)
56
+
57
+
58
+ def is_ascii(s=''):
59
+ # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7)
60
+ s = str(s) # convert list, tuple, None, etc. to str
61
+ return len(s.encode().decode('ascii', 'ignore')) == len(s)
62
+
63
+
64
+ def is_chinese(s='人工智能'):
65
+ # Is string composed of any Chinese characters?
66
+ return bool(re.search('[\u4e00-\u9fff]', str(s)))
67
+
68
+
69
+ def is_colab():
70
+ # Is environment a Google Colab instance?
71
+ return 'google.colab' in sys.modules
72
+
73
+
74
+ def is_notebook():
75
+ # Is environment a Jupyter notebook? Verified on Colab, Jupyterlab, Kaggle, Paperspace
76
+ ipython_type = str(type(IPython.get_ipython()))
77
+ return 'colab' in ipython_type or 'zmqshell' in ipython_type
78
+
79
+
80
+ def is_kaggle():
81
+ # Is environment a Kaggle Notebook?
82
+ return os.environ.get('PWD') == '/kaggle/working' and os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'
83
+
84
+
85
+ def is_docker() -> bool:
86
+ """Check if the process runs inside a docker container."""
87
+ if Path("/.dockerenv").exists():
88
+ return True
89
+ try: # check if docker is in control groups
90
+ with open("/proc/self/cgroup") as file:
91
+ return any("docker" in line for line in file)
92
+ except OSError:
93
+ return False
94
+
95
+
96
+ def is_writeable(dir, test=False):
97
+ # Return True if directory has write permissions, test opening a file with write permissions if test=True
98
+ if not test:
99
+ return os.access(dir, os.W_OK) # possible issues on Windows
100
+ file = Path(dir) / 'tmp.txt'
101
+ try:
102
+ with open(file, 'w'): # open file with write permissions
103
+ pass
104
+ file.unlink() # remove file
105
+ return True
106
+ except OSError:
107
+ return False
108
+
109
+
110
+ LOGGING_NAME = "yolov5"
111
+
112
+
113
+ def set_logging(name=LOGGING_NAME, verbose=True):
114
+ # sets up logging for the given name
115
+ rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
116
+ level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR
117
+ logging.config.dictConfig({
118
+ "version": 1,
119
+ "disable_existing_loggers": False,
120
+ "formatters": {
121
+ name: {
122
+ "format": "%(message)s"}},
123
+ "handlers": {
124
+ name: {
125
+ "class": "logging.StreamHandler",
126
+ "formatter": name,
127
+ "level": level,}},
128
+ "loggers": {
129
+ name: {
130
+ "level": level,
131
+ "handlers": [name],
132
+ "propagate": False,}}})
133
+
134
+
135
+ set_logging(LOGGING_NAME) # run before defining LOGGER
136
+ LOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)
137
+ if platform.system() == 'Windows':
138
+ for fn in LOGGER.info, LOGGER.warning:
139
+ setattr(LOGGER, fn.__name__, lambda x: fn(emojis(x))) # emoji safe logging
140
+
141
+
142
+ def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):
143
+ # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required.
144
+ env = os.getenv(env_var)
145
+ if env:
146
+ path = Path(env) # use environment variable
147
+ else:
148
+ cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs
149
+ path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir
150
+ path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable
151
+ path.mkdir(exist_ok=True) # make if required
152
+ return path
153
+
154
+
155
+ CONFIG_DIR = user_config_dir() # Ultralytics settings dir
156
+
157
+
158
+ class Profile(contextlib.ContextDecorator):
159
+ # YOLO Profile class. Usage: @Profile() decorator or 'with Profile():' context manager
160
+ def __init__(self, t=0.0):
161
+ self.t = t
162
+ self.cuda = torch.cuda.is_available()
163
+
164
+ def __enter__(self):
165
+ self.start = self.time()
166
+ return self
167
+
168
+ def __exit__(self, type, value, traceback):
169
+ self.dt = self.time() - self.start # delta-time
170
+ self.t += self.dt # accumulate dt
171
+
172
+ def time(self):
173
+ if self.cuda:
174
+ torch.cuda.synchronize()
175
+ return time.time()
176
+
177
+
178
+ class Timeout(contextlib.ContextDecorator):
179
+ # YOLO Timeout class. Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager
180
+ def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):
181
+ self.seconds = int(seconds)
182
+ self.timeout_message = timeout_msg
183
+ self.suppress = bool(suppress_timeout_errors)
184
+
185
+ def _timeout_handler(self, signum, frame):
186
+ raise TimeoutError(self.timeout_message)
187
+
188
+ def __enter__(self):
189
+ if platform.system() != 'Windows': # not supported on Windows
190
+ signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM
191
+ signal.alarm(self.seconds) # start countdown for SIGALRM to be raised
192
+
193
+ def __exit__(self, exc_type, exc_val, exc_tb):
194
+ if platform.system() != 'Windows':
195
+ signal.alarm(0) # Cancel SIGALRM if it's scheduled
196
+ if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError
197
+ return True
198
+
199
+
200
+ class WorkingDirectory(contextlib.ContextDecorator):
201
+ # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager
202
+ def __init__(self, new_dir):
203
+ self.dir = new_dir # new dir
204
+ self.cwd = Path.cwd().resolve() # current dir
205
+
206
+ def __enter__(self):
207
+ os.chdir(self.dir)
208
+
209
+ def __exit__(self, exc_type, exc_val, exc_tb):
210
+ os.chdir(self.cwd)
211
+
212
+
213
+ def methods(instance):
214
+ # Get class/instance methods
215
+ return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]
216
+
217
+
218
+ def print_args(args: Optional[dict] = None, show_file=True, show_func=False):
219
+ # Print function arguments (optional args dict)
220
+ x = inspect.currentframe().f_back # previous frame
221
+ file, _, func, _, _ = inspect.getframeinfo(x)
222
+ if args is None: # get args automatically
223
+ args, _, _, frm = inspect.getargvalues(x)
224
+ args = {k: v for k, v in frm.items() if k in args}
225
+ try:
226
+ file = Path(file).resolve().relative_to(ROOT).with_suffix('')
227
+ except ValueError:
228
+ file = Path(file).stem
229
+ s = (f'{file}: ' if show_file else '') + (f'{func}: ' if show_func else '')
230
+ LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items()))
231
+
232
+
233
+ def init_seeds(seed=0, deterministic=False):
234
+ # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html
235
+ random.seed(seed)
236
+ np.random.seed(seed)
237
+ torch.manual_seed(seed)
238
+ torch.cuda.manual_seed(seed)
239
+ torch.cuda.manual_seed_all(seed) # for Multi-GPU, exception safe
240
+ # torch.backends.cudnn.benchmark = True # AutoBatch problem https://github.com/ultralytics/yolov5/issues/9287
241
+ if deterministic and check_version(torch.__version__, '1.12.0'): # https://github.com/ultralytics/yolov5/pull/8213
242
+ torch.use_deterministic_algorithms(True)
243
+ torch.backends.cudnn.deterministic = True
244
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'
245
+ os.environ['PYTHONHASHSEED'] = str(seed)
246
+
247
+
248
+ def intersect_dicts(da, db, exclude=()):
249
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
250
+ return {k: v for k, v in da.items() if k in db and all(x not in k for x in exclude) and v.shape == db[k].shape}
251
+
252
+
253
+ def get_default_args(func):
254
+ # Get func() default arguments
255
+ signature = inspect.signature(func)
256
+ return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
257
+
258
+
259
+ def get_latest_run(search_dir='.'):
260
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
261
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
262
+ return max(last_list, key=os.path.getctime) if last_list else ''
263
+
264
+
265
+ def file_age(path=__file__):
266
+ # Return days since last file update
267
+ dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime)) # delta
268
+ return dt.days # + dt.seconds / 86400 # fractional days
269
+
270
+
271
+ def file_date(path=__file__):
272
+ # Return human-readable file modification date, i.e. '2021-3-26'
273
+ t = datetime.fromtimestamp(Path(path).stat().st_mtime)
274
+ return f'{t.year}-{t.month}-{t.day}'
275
+
276
+
277
+ def file_size(path):
278
+ # Return file/dir size (MB)
279
+ mb = 1 << 20 # bytes to MiB (1024 ** 2)
280
+ path = Path(path)
281
+ if path.is_file():
282
+ return path.stat().st_size / mb
283
+ elif path.is_dir():
284
+ return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb
285
+ else:
286
+ return 0.0
287
+
288
+
289
+ def check_online():
290
+ # Check internet connectivity
291
+ import socket
292
+
293
+ def run_once():
294
+ # Check once
295
+ try:
296
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility
297
+ return True
298
+ except OSError:
299
+ return False
300
+
301
+ return run_once() or run_once() # check twice to increase robustness to intermittent connectivity issues
302
+
303
+
304
+ def git_describe(path=ROOT): # path must be a directory
305
+ # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
306
+ try:
307
+ assert (Path(path) / '.git').is_dir()
308
+ return check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1]
309
+ except Exception:
310
+ return ''
311
+
312
+
313
+ @TryExcept()
314
+ @WorkingDirectory(ROOT)
315
+ def check_git_status(repo='WongKinYiu/yolov9', branch='main'):
316
+ # YOLO status check, recommend 'git pull' if code is out of date
317
+ url = f'https://github.com/{repo}'
318
+ msg = f', for updates see {url}'
319
+ s = colorstr('github: ') # string
320
+ assert Path('.git').exists(), s + 'skipping check (not a git repository)' + msg
321
+ assert check_online(), s + 'skipping check (offline)' + msg
322
+
323
+ splits = re.split(pattern=r'\s', string=check_output('git remote -v', shell=True).decode())
324
+ matches = [repo in s for s in splits]
325
+ if any(matches):
326
+ remote = splits[matches.index(True) - 1]
327
+ else:
328
+ remote = 'ultralytics'
329
+ check_output(f'git remote add {remote} {url}', shell=True)
330
+ check_output(f'git fetch {remote}', shell=True, timeout=5) # git fetch
331
+ local_branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out
332
+ n = int(check_output(f'git rev-list {local_branch}..{remote}/{branch} --count', shell=True)) # commits behind
333
+ if n > 0:
334
+ pull = 'git pull' if remote == 'origin' else f'git pull {remote} {branch}'
335
+ s += f"⚠️ YOLO is out of date by {n} commit{'s' * (n > 1)}. Use `{pull}` or `git clone {url}` to update."
336
+ else:
337
+ s += f'up to date with {url} ✅'
338
+ LOGGER.info(s)
339
+
340
+
341
+ @WorkingDirectory(ROOT)
342
+ def check_git_info(path='.'):
343
+ # YOLO git info check, return {remote, branch, commit}
344
+ check_requirements('gitpython')
345
+ import git
346
+ try:
347
+ repo = git.Repo(path)
348
+ remote = repo.remotes.origin.url.replace('.git', '') # i.e. 'https://github.com/WongKinYiu/yolov9'
349
+ commit = repo.head.commit.hexsha # i.e. '3134699c73af83aac2a481435550b968d5792c0d'
350
+ try:
351
+ branch = repo.active_branch.name # i.e. 'main'
352
+ except TypeError: # not on any branch
353
+ branch = None # i.e. 'detached HEAD' state
354
+ return {'remote': remote, 'branch': branch, 'commit': commit}
355
+ except git.exc.InvalidGitRepositoryError: # path is not a git dir
356
+ return {'remote': None, 'branch': None, 'commit': None}
357
+
358
+
359
+ def check_python(minimum='3.7.0'):
360
+ # Check current python version vs. required python version
361
+ check_version(platform.python_version(), minimum, name='Python ', hard=True)
362
+
363
+
364
+ def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):
365
+ # Check version vs. required version
366
+ current, minimum = (pkg.parse_version(x) for x in (current, minimum))
367
+ result = (current == minimum) if pinned else (current >= minimum) # bool
368
+ s = f'WARNING ⚠️ {name}{minimum} is required by YOLO, but {name}{current} is currently installed' # string
369
+ if hard:
370
+ assert result, emojis(s) # assert min requirements met
371
+ if verbose and not result:
372
+ LOGGER.warning(s)
373
+ return result
374
+
375
+
376
+ @TryExcept()
377
+ def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=''):
378
+ # Check installed dependencies meet YOLO requirements (pass *.txt file or list of packages or single package str)
379
+ prefix = colorstr('red', 'bold', 'requirements:')
380
+ check_python() # check python version
381
+ if isinstance(requirements, Path): # requirements.txt file
382
+ file = requirements.resolve()
383
+ assert file.exists(), f"{prefix} {file} not found, check failed."
384
+ with file.open() as f:
385
+ requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]
386
+ elif isinstance(requirements, str):
387
+ requirements = [requirements]
388
+
389
+ s = ''
390
+ n = 0
391
+ for r in requirements:
392
+ try:
393
+ pkg.require(r)
394
+ except (pkg.VersionConflict, pkg.DistributionNotFound): # exception if requirements not met
395
+ s += f'"{r}" '
396
+ n += 1
397
+
398
+ if s and install and AUTOINSTALL: # check environment variable
399
+ LOGGER.info(f"{prefix} YOLO requirement{'s' * (n > 1)} {s}not found, attempting AutoUpdate...")
400
+ try:
401
+ # assert check_online(), "AutoUpdate skipped (offline)"
402
+ LOGGER.info(check_output(f'pip install {s} {cmds}', shell=True).decode())
403
+ source = file if 'file' in locals() else requirements
404
+ s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
405
+ f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
406
+ LOGGER.info(s)
407
+ except Exception as e:
408
+ LOGGER.warning(f'{prefix} ❌ {e}')
409
+
410
+
411
+ def check_img_size(imgsz, s=32, floor=0):
412
+ # Verify image size is a multiple of stride s in each dimension
413
+ if isinstance(imgsz, int): # integer i.e. img_size=640
414
+ new_size = max(make_divisible(imgsz, int(s)), floor)
415
+ else: # list i.e. img_size=[640, 480]
416
+ imgsz = list(imgsz) # convert to list if tuple
417
+ new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]
418
+ if new_size != imgsz:
419
+ LOGGER.warning(f'WARNING ⚠️ --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')
420
+ return new_size
421
+
422
+
423
+ def check_imshow(warn=False):
424
+ # Check if environment supports image displays
425
+ try:
426
+ assert not is_notebook()
427
+ assert not is_docker()
428
+ cv2.imshow('test', np.zeros((1, 1, 3)))
429
+ cv2.waitKey(1)
430
+ cv2.destroyAllWindows()
431
+ cv2.waitKey(1)
432
+ return True
433
+ except Exception as e:
434
+ if warn:
435
+ LOGGER.warning(f'WARNING ⚠️ Environment does not support cv2.imshow() or PIL Image.show()\n{e}')
436
+ return False
437
+
438
+
439
+ def check_suffix(file='yolo.pt', suffix=('.pt',), msg=''):
440
+ # Check file(s) for acceptable suffix
441
+ if file and suffix:
442
+ if isinstance(suffix, str):
443
+ suffix = [suffix]
444
+ for f in file if isinstance(file, (list, tuple)) else [file]:
445
+ s = Path(f).suffix.lower() # file suffix
446
+ if len(s):
447
+ assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}"
448
+
449
+
450
+ def check_yaml(file, suffix=('.yaml', '.yml')):
451
+ # Search/download YAML file (if necessary) and return path, checking suffix
452
+ return check_file(file, suffix)
453
+
454
+
455
+ def check_file(file, suffix=''):
456
+ # Search/download file (if necessary) and return path
457
+ check_suffix(file, suffix) # optional
458
+ file = str(file) # convert to str()
459
+ if os.path.isfile(file) or not file: # exists
460
+ return file
461
+ elif file.startswith(('http:/', 'https:/')): # download
462
+ url = file # warning: Pathlib turns :// -> :/
463
+ file = Path(urllib.parse.unquote(file).split('?')[0]).name # '%2F' to '/', split https://url.com/file.txt?auth
464
+ if os.path.isfile(file):
465
+ LOGGER.info(f'Found {url} locally at {file}') # file already exists
466
+ else:
467
+ LOGGER.info(f'Downloading {url} to {file}...')
468
+ torch.hub.download_url_to_file(url, file)
469
+ assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check
470
+ return file
471
+ elif file.startswith('clearml://'): # ClearML Dataset ID
472
+ assert 'clearml' in sys.modules, "ClearML is not installed, so cannot use ClearML dataset. Try running 'pip install clearml'."
473
+ return file
474
+ else: # search
475
+ files = []
476
+ for d in 'data', 'models', 'utils': # search directories
477
+ files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True)) # find file
478
+ assert len(files), f'File not found: {file}' # assert file was found
479
+ assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
480
+ return files[0] # return file
481
+
482
+
483
+ def check_font(font=FONT, progress=False):
484
+ # Download font to CONFIG_DIR if necessary
485
+ font = Path(font)
486
+ file = CONFIG_DIR / font.name
487
+ if not font.exists() and not file.exists():
488
+ url = f'https://ultralytics.com/assets/{font.name}'
489
+ LOGGER.info(f'Downloading {url} to {file}...')
490
+ torch.hub.download_url_to_file(url, str(file), progress=progress)
491
+
492
+
493
+ def check_dataset(data, autodownload=True):
494
+ # Download, check and/or unzip dataset if not found locally
495
+
496
+ # Download (optional)
497
+ extract_dir = ''
498
+ if isinstance(data, (str, Path)) and (is_zipfile(data) or is_tarfile(data)):
499
+ download(data, dir=f'{DATASETS_DIR}/{Path(data).stem}', unzip=True, delete=False, curl=False, threads=1)
500
+ data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml'))
501
+ extract_dir, autodownload = data.parent, False
502
+
503
+ # Read yaml (optional)
504
+ if isinstance(data, (str, Path)):
505
+ data = yaml_load(data) # dictionary
506
+
507
+ # Checks
508
+ for k in 'train', 'val', 'names':
509
+ assert k in data, emojis(f"data.yaml '{k}:' field missing ❌")
510
+ if isinstance(data['names'], (list, tuple)): # old array format
511
+ data['names'] = dict(enumerate(data['names'])) # convert to dict
512
+ assert all(isinstance(k, int) for k in data['names'].keys()), 'data.yaml names keys must be integers, i.e. 2: car'
513
+ data['nc'] = len(data['names'])
514
+
515
+ # Resolve paths
516
+ path = Path(extract_dir or data.get('path') or '') # optional 'path' default to '.'
517
+ if not path.is_absolute():
518
+ path = (ROOT / path).resolve()
519
+ data['path'] = path # download scripts
520
+ for k in 'train', 'val', 'test':
521
+ if data.get(k): # prepend path
522
+ if isinstance(data[k], str):
523
+ x = (path / data[k]).resolve()
524
+ if not x.exists() and data[k].startswith('../'):
525
+ x = (path / data[k][3:]).resolve()
526
+ data[k] = str(x)
527
+ else:
528
+ data[k] = [str((path / x).resolve()) for x in data[k]]
529
+
530
+ # Parse yaml
531
+ train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))
532
+ if val:
533
+ val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
534
+ if not all(x.exists() for x in val):
535
+ LOGGER.info('\nDataset not found ⚠️, missing paths %s' % [str(x) for x in val if not x.exists()])
536
+ if not s or not autodownload:
537
+ raise Exception('Dataset not found ❌')
538
+ t = time.time()
539
+ if s.startswith('http') and s.endswith('.zip'): # URL
540
+ f = Path(s).name # filename
541
+ LOGGER.info(f'Downloading {s} to {f}...')
542
+ torch.hub.download_url_to_file(s, f)
543
+ Path(DATASETS_DIR).mkdir(parents=True, exist_ok=True) # create root
544
+ unzip_file(f, path=DATASETS_DIR) # unzip
545
+ Path(f).unlink() # remove zip
546
+ r = None # success
547
+ elif s.startswith('bash '): # bash script
548
+ LOGGER.info(f'Running {s} ...')
549
+ r = os.system(s)
550
+ else: # python script
551
+ r = exec(s, {'yaml': data}) # return None
552
+ dt = f'({round(time.time() - t, 1)}s)'
553
+ s = f"success ✅ {dt}, saved to {colorstr('bold', DATASETS_DIR)}" if r in (0, None) else f"failure {dt} ❌"
554
+ LOGGER.info(f"Dataset download {s}")
555
+ check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True) # download fonts
556
+ return data # dictionary
557
+
558
+
559
+ def check_amp(model):
560
+ # Check PyTorch Automatic Mixed Precision (AMP) functionality. Return True on correct operation
561
+ from models.common import AutoShape, DetectMultiBackend
562
+
563
+ def amp_allclose(model, im):
564
+ # All close FP32 vs AMP results
565
+ m = AutoShape(model, verbose=False) # model
566
+ a = m(im).xywhn[0] # FP32 inference
567
+ m.amp = True
568
+ b = m(im).xywhn[0] # AMP inference
569
+ return a.shape == b.shape and torch.allclose(a, b, atol=0.1) # close to 10% absolute tolerance
570
+
571
+ prefix = colorstr('AMP: ')
572
+ device = next(model.parameters()).device # get model device
573
+ if device.type in ('cpu', 'mps'):
574
+ return False # AMP only used on CUDA devices
575
+ f = ROOT / 'data' / 'images' / 'bus.jpg' # image to check
576
+ im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if check_online() else np.ones((640, 640, 3))
577
+ try:
578
+ #assert amp_allclose(deepcopy(model), im) or amp_allclose(DetectMultiBackend('yolo.pt', device), im)
579
+ LOGGER.info(f'{prefix}checks passed ✅')
580
+ return True
581
+ except Exception:
582
+ help_url = 'https://github.com/ultralytics/yolov5/issues/7908'
583
+ LOGGER.warning(f'{prefix}checks failed ❌, disabling Automatic Mixed Precision. See {help_url}')
584
+ return False
585
+
586
+
587
+ def yaml_load(file='data.yaml'):
588
+ # Single-line safe yaml loading
589
+ with open(file, errors='ignore') as f:
590
+ return yaml.safe_load(f)
591
+
592
+
593
+ def yaml_save(file='data.yaml', data={}):
594
+ # Single-line safe yaml saving
595
+ with open(file, 'w') as f:
596
+ yaml.safe_dump({k: str(v) if isinstance(v, Path) else v for k, v in data.items()}, f, sort_keys=False)
597
+
598
+
599
+ def unzip_file(file, path=None, exclude=('.DS_Store', '__MACOSX')):
600
+ # Unzip a *.zip file to path/, excluding files containing strings in exclude list
601
+ if path is None:
602
+ path = Path(file).parent # default path
603
+ with ZipFile(file) as zipObj:
604
+ for f in zipObj.namelist(): # list all archived filenames in the zip
605
+ if all(x not in f for x in exclude):
606
+ zipObj.extract(f, path=path)
607
+
608
+
609
+ def url2file(url):
610
+ # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt
611
+ url = str(Path(url)).replace(':/', '://') # Pathlib turns :// -> :/
612
+ return Path(urllib.parse.unquote(url)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth
613
+
614
+
615
+ def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3):
616
+ # Multithreaded file download and unzip function, used in data.yaml for autodownload
617
+ def download_one(url, dir):
618
+ # Download 1 file
619
+ success = True
620
+ if os.path.isfile(url):
621
+ f = Path(url) # filename
622
+ else: # does not exist
623
+ f = dir / Path(url).name
624
+ LOGGER.info(f'Downloading {url} to {f}...')
625
+ for i in range(retry + 1):
626
+ if curl:
627
+ s = 'sS' if threads > 1 else '' # silent
628
+ r = os.system(
629
+ f'curl -# -{s}L "{url}" -o "{f}" --retry 9 -C -') # curl download with retry, continue
630
+ success = r == 0
631
+ else:
632
+ torch.hub.download_url_to_file(url, f, progress=threads == 1) # torch download
633
+ success = f.is_file()
634
+ if success:
635
+ break
636
+ elif i < retry:
637
+ LOGGER.warning(f'⚠️ Download failure, retrying {i + 1}/{retry} {url}...')
638
+ else:
639
+ LOGGER.warning(f'❌ Failed to download {url}...')
640
+
641
+ if unzip and success and (f.suffix == '.gz' or is_zipfile(f) or is_tarfile(f)):
642
+ LOGGER.info(f'Unzipping {f}...')
643
+ if is_zipfile(f):
644
+ unzip_file(f, dir) # unzip
645
+ elif is_tarfile(f):
646
+ os.system(f'tar xf {f} --directory {f.parent}') # unzip
647
+ elif f.suffix == '.gz':
648
+ os.system(f'tar xfz {f} --directory {f.parent}') # unzip
649
+ if delete:
650
+ f.unlink() # remove zip
651
+
652
+ dir = Path(dir)
653
+ dir.mkdir(parents=True, exist_ok=True) # make directory
654
+ if threads > 1:
655
+ pool = ThreadPool(threads)
656
+ pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multithreaded
657
+ pool.close()
658
+ pool.join()
659
+ else:
660
+ for u in [url] if isinstance(url, (str, Path)) else url:
661
+ download_one(u, dir)
662
+
663
+
664
+ def make_divisible(x, divisor):
665
+ # Returns nearest x divisible by divisor
666
+ if isinstance(divisor, torch.Tensor):
667
+ divisor = int(divisor.max()) # to int
668
+ return math.ceil(x / divisor) * divisor
669
+
670
+
671
+ def clean_str(s):
672
+ # Cleans a string by replacing special characters with underscore _
673
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
674
+
675
+
676
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
677
+ # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf
678
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
679
+
680
+
681
+ def one_flat_cycle(y1=0.0, y2=1.0, steps=100):
682
+ # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf
683
+ #return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
684
+ return lambda x: ((1 - math.cos((x - (steps // 2)) * math.pi / (steps // 2))) / 2) * (y2 - y1) + y1 if (x > (steps // 2)) else y1
685
+
686
+
687
+ def colorstr(*input):
688
+ # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
689
+ *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
690
+ colors = {
691
+ 'black': '\033[30m', # basic colors
692
+ 'red': '\033[31m',
693
+ 'green': '\033[32m',
694
+ 'yellow': '\033[33m',
695
+ 'blue': '\033[34m',
696
+ 'magenta': '\033[35m',
697
+ 'cyan': '\033[36m',
698
+ 'white': '\033[37m',
699
+ 'bright_black': '\033[90m', # bright colors
700
+ 'bright_red': '\033[91m',
701
+ 'bright_green': '\033[92m',
702
+ 'bright_yellow': '\033[93m',
703
+ 'bright_blue': '\033[94m',
704
+ 'bright_magenta': '\033[95m',
705
+ 'bright_cyan': '\033[96m',
706
+ 'bright_white': '\033[97m',
707
+ 'end': '\033[0m', # misc
708
+ 'bold': '\033[1m',
709
+ 'underline': '\033[4m'}
710
+ return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
711
+
712
+
713
+ def labels_to_class_weights(labels, nc=80):
714
+ # Get class weights (inverse frequency) from training labels
715
+ if labels[0] is None: # no labels loaded
716
+ return torch.Tensor()
717
+
718
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
719
+ classes = labels[:, 0].astype(int) # labels = [class xywh]
720
+ weights = np.bincount(classes, minlength=nc) # occurrences per class
721
+
722
+ # Prepend gridpoint count (for uCE training)
723
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
724
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
725
+
726
+ weights[weights == 0] = 1 # replace empty bins with 1
727
+ weights = 1 / weights # number of targets per class
728
+ weights /= weights.sum() # normalize
729
+ return torch.from_numpy(weights).float()
730
+
731
+
732
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
733
+ # Produces image weights based on class_weights and image contents
734
+ # Usage: index = random.choices(range(n), weights=image_weights, k=1) # weighted image sample
735
+ class_counts = np.array([np.bincount(x[:, 0].astype(int), minlength=nc) for x in labels])
736
+ return (class_weights.reshape(1, nc) * class_counts).sum(1)
737
+
738
+
739
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
740
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
741
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
742
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
743
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
744
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
745
+ return [
746
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
747
+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
748
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
749
+
750
+
751
+ def xyxy2xywh(x):
752
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
753
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
754
+ y[..., 0] = (x[..., 0] + x[..., 2]) / 2 # x center
755
+ y[..., 1] = (x[..., 1] + x[..., 3]) / 2 # y center
756
+ y[..., 2] = x[..., 2] - x[..., 0] # width
757
+ y[..., 3] = x[..., 3] - x[..., 1] # height
758
+ return y
759
+
760
+
761
+ def xywh2xyxy(x):
762
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
763
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
764
+ y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x
765
+ y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y
766
+ y[..., 2] = x[..., 0] + x[..., 2] / 2 # bottom right x
767
+ y[..., 3] = x[..., 1] + x[..., 3] / 2 # bottom right y
768
+ return y
769
+
770
+
771
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
772
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
773
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
774
+ y[..., 0] = w * (x[..., 0] - x[..., 2] / 2) + padw # top left x
775
+ y[..., 1] = h * (x[..., 1] - x[..., 3] / 2) + padh # top left y
776
+ y[..., 2] = w * (x[..., 0] + x[..., 2] / 2) + padw # bottom right x
777
+ y[..., 3] = h * (x[..., 1] + x[..., 3] / 2) + padh # bottom right y
778
+ return y
779
+
780
+
781
+ def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
782
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right
783
+ if clip:
784
+ clip_boxes(x, (h - eps, w - eps)) # warning: inplace clip
785
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
786
+ y[..., 0] = ((x[..., 0] + x[..., 2]) / 2) / w # x center
787
+ y[..., 1] = ((x[..., 1] + x[..., 3]) / 2) / h # y center
788
+ y[..., 2] = (x[..., 2] - x[..., 0]) / w # width
789
+ y[..., 3] = (x[..., 3] - x[..., 1]) / h # height
790
+ return y
791
+
792
+
793
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
794
+ # Convert normalized segments into pixel segments, shape (n,2)
795
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
796
+ y[..., 0] = w * x[..., 0] + padw # top left x
797
+ y[..., 1] = h * x[..., 1] + padh # top left y
798
+ return y
799
+
800
+
801
+ def segment2box(segment, width=640, height=640):
802
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
803
+ x, y = segment.T # segment xy
804
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
805
+ x, y, = x[inside], y[inside]
806
+ return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
807
+
808
+
809
+ def segments2boxes(segments):
810
+ # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
811
+ boxes = []
812
+ for s in segments:
813
+ x, y = s.T # segment xy
814
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
815
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
816
+
817
+
818
+ def resample_segments(segments, n=1000):
819
+ # Up-sample an (n,2) segment
820
+ for i, s in enumerate(segments):
821
+ s = np.concatenate((s, s[0:1, :]), axis=0)
822
+ x = np.linspace(0, len(s) - 1, n)
823
+ xp = np.arange(len(s))
824
+ segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
825
+ return segments
826
+
827
+
828
+ def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):
829
+ # Rescale boxes (xyxy) from img1_shape to img0_shape
830
+ if ratio_pad is None: # calculate from img0_shape
831
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
832
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
833
+ else:
834
+ gain = ratio_pad[0][0]
835
+ pad = ratio_pad[1]
836
+
837
+ boxes[:, [0, 2]] -= pad[0] # x padding
838
+ boxes[:, [1, 3]] -= pad[1] # y padding
839
+ boxes[:, :4] /= gain
840
+ clip_boxes(boxes, img0_shape)
841
+ return boxes
842
+
843
+
844
+ def scale_segments(img1_shape, segments, img0_shape, ratio_pad=None, normalize=False):
845
+ # Rescale coords (xyxy) from img1_shape to img0_shape
846
+ if ratio_pad is None: # calculate from img0_shape
847
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
848
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
849
+ else:
850
+ gain = ratio_pad[0][0]
851
+ pad = ratio_pad[1]
852
+
853
+ segments[:, 0] -= pad[0] # x padding
854
+ segments[:, 1] -= pad[1] # y padding
855
+ segments /= gain
856
+ clip_segments(segments, img0_shape)
857
+ if normalize:
858
+ segments[:, 0] /= img0_shape[1] # width
859
+ segments[:, 1] /= img0_shape[0] # height
860
+ return segments
861
+
862
+
863
+ def clip_boxes(boxes, shape):
864
+ # Clip boxes (xyxy) to image shape (height, width)
865
+ if isinstance(boxes, torch.Tensor): # faster individually
866
+ boxes[:, 0].clamp_(0, shape[1]) # x1
867
+ boxes[:, 1].clamp_(0, shape[0]) # y1
868
+ boxes[:, 2].clamp_(0, shape[1]) # x2
869
+ boxes[:, 3].clamp_(0, shape[0]) # y2
870
+ else: # np.array (faster grouped)
871
+ boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2
872
+ boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2
873
+
874
+
875
+ def clip_segments(segments, shape):
876
+ # Clip segments (xy1,xy2,...) to image shape (height, width)
877
+ if isinstance(segments, torch.Tensor): # faster individually
878
+ segments[:, 0].clamp_(0, shape[1]) # x
879
+ segments[:, 1].clamp_(0, shape[0]) # y
880
+ else: # np.array (faster grouped)
881
+ segments[:, 0] = segments[:, 0].clip(0, shape[1]) # x
882
+ segments[:, 1] = segments[:, 1].clip(0, shape[0]) # y
883
+
884
+
885
+ def non_max_suppression(
886
+ prediction,
887
+ conf_thres=0.25,
888
+ iou_thres=0.45,
889
+ classes=None,
890
+ agnostic=False,
891
+ multi_label=False,
892
+ labels=(),
893
+ max_det=300,
894
+ nm=0, # number of masks
895
+ ):
896
+ """Non-Maximum Suppression (NMS) on inference results to reject overlapping detections
897
+
898
+ Returns:
899
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
900
+ """
901
+
902
+ if isinstance(prediction, (list, tuple)): # YOLO model in validation model, output = (inference_out, loss_out)
903
+ prediction = prediction[0] # select only inference output
904
+
905
+ device = prediction.device
906
+ mps = 'mps' in device.type # Apple MPS
907
+ if mps: # MPS not fully supported yet, convert tensors to CPU before NMS
908
+ prediction = prediction.cpu()
909
+ bs = prediction.shape[0] # batch size
910
+ nc = prediction.shape[1] - nm - 4 # number of classes
911
+ mi = 4 + nc # mask start index
912
+ xc = prediction[:, 4:mi].amax(1) > conf_thres # candidates
913
+
914
+ # Checks
915
+ assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
916
+ assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
917
+
918
+ # Settings
919
+ # min_wh = 2 # (pixels) minimum box width and height
920
+ max_wh = 7680 # (pixels) maximum box width and height
921
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
922
+ time_limit = 2.5 + 0.05 * bs # seconds to quit after
923
+ redundant = True # require redundant detections
924
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
925
+ merge = False # use merge-NMS
926
+
927
+ t = time.time()
928
+ output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs
929
+ for xi, x in enumerate(prediction): # image index, image inference
930
+ # Apply constraints
931
+ # x[((x[:, 2:4] < min_wh) | (x[:, 2:4] > max_wh)).any(1), 4] = 0 # width-height
932
+ x = x.T[xc[xi]] # confidence
933
+
934
+ # Cat apriori labels if autolabelling
935
+ if labels and len(labels[xi]):
936
+ lb = labels[xi]
937
+ v = torch.zeros((len(lb), nc + nm + 5), device=x.device)
938
+ v[:, :4] = lb[:, 1:5] # box
939
+ v[range(len(lb)), lb[:, 0].long() + 4] = 1.0 # cls
940
+ x = torch.cat((x, v), 0)
941
+
942
+ # If none remain process next image
943
+ if not x.shape[0]:
944
+ continue
945
+
946
+ # Detections matrix nx6 (xyxy, conf, cls)
947
+ box, cls, mask = x.split((4, nc, nm), 1)
948
+ box = xywh2xyxy(box) # center_x, center_y, width, height) to (x1, y1, x2, y2)
949
+ if multi_label:
950
+ i, j = (cls > conf_thres).nonzero(as_tuple=False).T
951
+ x = torch.cat((box[i], x[i, 4 + j, None], j[:, None].float(), mask[i]), 1)
952
+ else: # best class only
953
+ conf, j = cls.max(1, keepdim=True)
954
+ x = torch.cat((box, conf, j.float(), mask), 1)[conf.view(-1) > conf_thres]
955
+
956
+ # Filter by class
957
+ if classes is not None:
958
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
959
+
960
+ # Apply finite constraint
961
+ # if not torch.isfinite(x).all():
962
+ # x = x[torch.isfinite(x).all(1)]
963
+
964
+ # Check shape
965
+ n = x.shape[0] # number of boxes
966
+ if not n: # no boxes
967
+ continue
968
+ elif n > max_nms: # excess boxes
969
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
970
+ else:
971
+ x = x[x[:, 4].argsort(descending=True)] # sort by confidence
972
+
973
+ # Batched NMS
974
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
975
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
976
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
977
+ if i.shape[0] > max_det: # limit detections
978
+ i = i[:max_det]
979
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
980
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
981
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
982
+ weights = iou * scores[None] # box weights
983
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
984
+ if redundant:
985
+ i = i[iou.sum(1) > 1] # require redundancy
986
+
987
+ output[xi] = x[i]
988
+ if mps:
989
+ output[xi] = output[xi].to(device)
990
+ if (time.time() - t) > time_limit:
991
+ LOGGER.warning(f'WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded')
992
+ break # time limit exceeded
993
+
994
+ return output
995
+
996
+
997
+ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
998
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
999
+ x = torch.load(f, map_location=torch.device('cpu'))
1000
+ if x.get('ema'):
1001
+ x['model'] = x['ema'] # replace model with ema
1002
+ for k in 'optimizer', 'best_fitness', 'ema', 'updates': # keys
1003
+ x[k] = None
1004
+ x['epoch'] = -1
1005
+ x['model'].half() # to FP16
1006
+ for p in x['model'].parameters():
1007
+ p.requires_grad = False
1008
+ torch.save(x, s or f)
1009
+ mb = os.path.getsize(s or f) / 1E6 # filesize
1010
+ LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB")
1011
+
1012
+
1013
+ def print_mutation(keys, results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')):
1014
+ evolve_csv = save_dir / 'evolve.csv'
1015
+ evolve_yaml = save_dir / 'hyp_evolve.yaml'
1016
+ keys = tuple(keys) + tuple(hyp.keys()) # [results + hyps]
1017
+ keys = tuple(x.strip() for x in keys)
1018
+ vals = results + tuple(hyp.values())
1019
+ n = len(keys)
1020
+
1021
+ # Download (optional)
1022
+ if bucket:
1023
+ url = f'gs://{bucket}/evolve.csv'
1024
+ if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0):
1025
+ os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local
1026
+
1027
+ # Log to evolve.csv
1028
+ s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header
1029
+ with open(evolve_csv, 'a') as f:
1030
+ f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n')
1031
+
1032
+ # Save yaml
1033
+ with open(evolve_yaml, 'w') as f:
1034
+ data = pd.read_csv(evolve_csv)
1035
+ data = data.rename(columns=lambda x: x.strip()) # strip keys
1036
+ i = np.argmax(fitness(data.values[:, :4])) #
1037
+ generations = len(data)
1038
+ f.write('# YOLO Hyperparameter Evolution Results\n' + f'# Best generation: {i}\n' +
1039
+ f'# Last generation: {generations - 1}\n' + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) +
1040
+ '\n' + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n')
1041
+ yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False)
1042
+
1043
+ # Print to screen
1044
+ LOGGER.info(prefix + f'{generations} generations finished, current result:\n' + prefix +
1045
+ ', '.join(f'{x.strip():>20s}' for x in keys) + '\n' + prefix + ', '.join(f'{x:20.5g}'
1046
+ for x in vals) + '\n\n')
1047
+
1048
+ if bucket:
1049
+ os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload
1050
+
1051
+
1052
+ def apply_classifier(x, model, img, im0):
1053
+ # Apply a second stage classifier to YOLO outputs
1054
+ # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval()
1055
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
1056
+ for i, d in enumerate(x): # per image
1057
+ if d is not None and len(d):
1058
+ d = d.clone()
1059
+
1060
+ # Reshape and pad cutouts
1061
+ b = xyxy2xywh(d[:, :4]) # boxes
1062
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
1063
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
1064
+ d[:, :4] = xywh2xyxy(b).long()
1065
+
1066
+ # Rescale boxes from img_size to im0 size
1067
+ scale_boxes(img.shape[2:], d[:, :4], im0[i].shape)
1068
+
1069
+ # Classes
1070
+ pred_cls1 = d[:, 5].long()
1071
+ ims = []
1072
+ for a in d:
1073
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
1074
+ im = cv2.resize(cutout, (224, 224)) # BGR
1075
+
1076
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
1077
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
1078
+ im /= 255 # 0 - 255 to 0.0 - 1.0
1079
+ ims.append(im)
1080
+
1081
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
1082
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
1083
+
1084
+ return x
1085
+
1086
+
1087
+ def increment_path(path, exist_ok=False, sep='', mkdir=False):
1088
+ # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
1089
+ path = Path(path) # os-agnostic
1090
+ if path.exists() and not exist_ok:
1091
+ path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
1092
+
1093
+ # Method 1
1094
+ for n in range(2, 9999):
1095
+ p = f'{path}{sep}{n}{suffix}' # increment path
1096
+ if not os.path.exists(p): #
1097
+ break
1098
+ path = Path(p)
1099
+
1100
+ # Method 2 (deprecated)
1101
+ # dirs = glob.glob(f"{path}{sep}*") # similar paths
1102
+ # matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs]
1103
+ # i = [int(m.groups()[0]) for m in matches if m] # indices
1104
+ # n = max(i) + 1 if i else 2 # increment number
1105
+ # path = Path(f"{path}{sep}{n}{suffix}") # increment path
1106
+
1107
+ if mkdir:
1108
+ path.mkdir(parents=True, exist_ok=True) # make directory
1109
+
1110
+ return path
1111
+
1112
+
1113
+ # OpenCV Chinese-friendly functions ------------------------------------------------------------------------------------
1114
+ imshow_ = cv2.imshow # copy to avoid recursion errors
1115
+
1116
+
1117
+ def imread(path, flags=cv2.IMREAD_COLOR):
1118
+ return cv2.imdecode(np.fromfile(path, np.uint8), flags)
1119
+
1120
+
1121
+ def imwrite(path, im):
1122
+ try:
1123
+ cv2.imencode(Path(path).suffix, im)[1].tofile(path)
1124
+ return True
1125
+ except Exception:
1126
+ return False
1127
+
1128
+
1129
+ def imshow(path, im):
1130
+ imshow_(path.encode('unicode_escape').decode(), im)
1131
+
1132
+
1133
+ cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow # redefine
1134
+
1135
+ # Variables ------------------------------------------------------------------------------------------------------------
utils/lion.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch implementation of the Lion optimizer."""
2
+ import torch
3
+ from torch.optim.optimizer import Optimizer
4
+
5
+
6
+ class Lion(Optimizer):
7
+ r"""Implements Lion algorithm."""
8
+
9
+ def __init__(self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0):
10
+ """Initialize the hyperparameters.
11
+ Args:
12
+ params (iterable): iterable of parameters to optimize or dicts defining
13
+ parameter groups
14
+ lr (float, optional): learning rate (default: 1e-4)
15
+ betas (Tuple[float, float], optional): coefficients used for computing
16
+ running averages of gradient and its square (default: (0.9, 0.99))
17
+ weight_decay (float, optional): weight decay coefficient (default: 0)
18
+ """
19
+
20
+ if not 0.0 <= lr:
21
+ raise ValueError('Invalid learning rate: {}'.format(lr))
22
+ if not 0.0 <= betas[0] < 1.0:
23
+ raise ValueError('Invalid beta parameter at index 0: {}'.format(betas[0]))
24
+ if not 0.0 <= betas[1] < 1.0:
25
+ raise ValueError('Invalid beta parameter at index 1: {}'.format(betas[1]))
26
+ defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay)
27
+ super().__init__(params, defaults)
28
+
29
+ @torch.no_grad()
30
+ def step(self, closure=None):
31
+ """Performs a single optimization step.
32
+ Args:
33
+ closure (callable, optional): A closure that reevaluates the model
34
+ and returns the loss.
35
+ Returns:
36
+ the loss.
37
+ """
38
+ loss = None
39
+ if closure is not None:
40
+ with torch.enable_grad():
41
+ loss = closure()
42
+
43
+ for group in self.param_groups:
44
+ for p in group['params']:
45
+ if p.grad is None:
46
+ continue
47
+
48
+ # Perform stepweight decay
49
+ p.data.mul_(1 - group['lr'] * group['weight_decay'])
50
+
51
+ grad = p.grad
52
+ state = self.state[p]
53
+ # State initialization
54
+ if len(state) == 0:
55
+ # Exponential moving average of gradient values
56
+ state['exp_avg'] = torch.zeros_like(p)
57
+
58
+ exp_avg = state['exp_avg']
59
+ beta1, beta2 = group['betas']
60
+
61
+ # Weight update
62
+ update = exp_avg * beta1 + grad * (1 - beta1)
63
+ p.add_(torch.sign(update), alpha=-group['lr'])
64
+ # Decay the momentum running average coefficient
65
+ exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2)
66
+
67
+ return loss
utils/loggers/__init__.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from pathlib import Path
4
+
5
+ import pkg_resources as pkg
6
+ import torch
7
+ from torch.utils.tensorboard import SummaryWriter
8
+
9
+ from utils.general import LOGGER, colorstr, cv2
10
+ from utils.loggers.clearml.clearml_utils import ClearmlLogger
11
+ from utils.loggers.wandb.wandb_utils import WandbLogger
12
+ from utils.plots import plot_images, plot_labels, plot_results
13
+ from utils.torch_utils import de_parallel
14
+
15
+ LOGGERS = ('csv', 'tb', 'wandb', 'clearml', 'comet') # *.csv, TensorBoard, Weights & Biases, ClearML
16
+ RANK = int(os.getenv('RANK', -1))
17
+
18
+ try:
19
+ import wandb
20
+
21
+ assert hasattr(wandb, '__version__') # verify package import not local dir
22
+ if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in {0, -1}:
23
+ try:
24
+ wandb_login_success = wandb.login(timeout=30)
25
+ except wandb.errors.UsageError: # known non-TTY terminal issue
26
+ wandb_login_success = False
27
+ if not wandb_login_success:
28
+ wandb = None
29
+ except (ImportError, AssertionError):
30
+ wandb = None
31
+
32
+ try:
33
+ import clearml
34
+
35
+ assert hasattr(clearml, '__version__') # verify package import not local dir
36
+ except (ImportError, AssertionError):
37
+ clearml = None
38
+
39
+ try:
40
+ if RANK not in [0, -1]:
41
+ comet_ml = None
42
+ else:
43
+ import comet_ml
44
+
45
+ assert hasattr(comet_ml, '__version__') # verify package import not local dir
46
+ from utils.loggers.comet import CometLogger
47
+
48
+ except (ModuleNotFoundError, ImportError, AssertionError):
49
+ comet_ml = None
50
+
51
+
52
+ class Loggers():
53
+ # YOLO Loggers class
54
+ def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
55
+ self.save_dir = save_dir
56
+ self.weights = weights
57
+ self.opt = opt
58
+ self.hyp = hyp
59
+ self.plots = not opt.noplots # plot results
60
+ self.logger = logger # for printing results to console
61
+ self.include = include
62
+ self.keys = [
63
+ 'train/box_loss',
64
+ 'train/cls_loss',
65
+ 'train/dfl_loss', # train loss
66
+ 'metrics/precision',
67
+ 'metrics/recall',
68
+ 'metrics/mAP_0.5',
69
+ 'metrics/mAP_0.5:0.95', # metrics
70
+ 'val/box_loss',
71
+ 'val/cls_loss',
72
+ 'val/dfl_loss', # val loss
73
+ 'x/lr0',
74
+ 'x/lr1',
75
+ 'x/lr2'] # params
76
+ self.best_keys = ['best/epoch', 'best/precision', 'best/recall', 'best/mAP_0.5', 'best/mAP_0.5:0.95']
77
+ for k in LOGGERS:
78
+ setattr(self, k, None) # init empty logger dictionary
79
+ self.csv = True # always log to csv
80
+
81
+ # Messages
82
+ # if not wandb:
83
+ # prefix = colorstr('Weights & Biases: ')
84
+ # s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLO 🚀 runs in Weights & Biases"
85
+ # self.logger.info(s)
86
+ if not clearml:
87
+ prefix = colorstr('ClearML: ')
88
+ s = f"{prefix}run 'pip install clearml' to automatically track, visualize and remotely train YOLO 🚀 in ClearML"
89
+ self.logger.info(s)
90
+ if not comet_ml:
91
+ prefix = colorstr('Comet: ')
92
+ s = f"{prefix}run 'pip install comet_ml' to automatically track and visualize YOLO 🚀 runs in Comet"
93
+ self.logger.info(s)
94
+ # TensorBoard
95
+ s = self.save_dir
96
+ if 'tb' in self.include and not self.opt.evolve:
97
+ prefix = colorstr('TensorBoard: ')
98
+ self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
99
+ self.tb = SummaryWriter(str(s))
100
+
101
+ # W&B
102
+ if wandb and 'wandb' in self.include:
103
+ wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')
104
+ run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None
105
+ self.opt.hyp = self.hyp # add hyperparameters
106
+ self.wandb = WandbLogger(self.opt, run_id)
107
+ # temp warn. because nested artifacts not supported after 0.12.10
108
+ # if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.11'):
109
+ # s = "YOLO temporarily requires wandb version 0.12.10 or below. Some features may not work as expected."
110
+ # self.logger.warning(s)
111
+ else:
112
+ self.wandb = None
113
+
114
+ # ClearML
115
+ if clearml and 'clearml' in self.include:
116
+ self.clearml = ClearmlLogger(self.opt, self.hyp)
117
+ else:
118
+ self.clearml = None
119
+
120
+ # Comet
121
+ if comet_ml and 'comet' in self.include:
122
+ if isinstance(self.opt.resume, str) and self.opt.resume.startswith("comet://"):
123
+ run_id = self.opt.resume.split("/")[-1]
124
+ self.comet_logger = CometLogger(self.opt, self.hyp, run_id=run_id)
125
+
126
+ else:
127
+ self.comet_logger = CometLogger(self.opt, self.hyp)
128
+
129
+ else:
130
+ self.comet_logger = None
131
+
132
+ @property
133
+ def remote_dataset(self):
134
+ # Get data_dict if custom dataset artifact link is provided
135
+ data_dict = None
136
+ if self.clearml:
137
+ data_dict = self.clearml.data_dict
138
+ if self.wandb:
139
+ data_dict = self.wandb.data_dict
140
+ if self.comet_logger:
141
+ data_dict = self.comet_logger.data_dict
142
+
143
+ return data_dict
144
+
145
+ def on_train_start(self):
146
+ if self.comet_logger:
147
+ self.comet_logger.on_train_start()
148
+
149
+ def on_pretrain_routine_start(self):
150
+ if self.comet_logger:
151
+ self.comet_logger.on_pretrain_routine_start()
152
+
153
+ def on_pretrain_routine_end(self, labels, names):
154
+ # Callback runs on pre-train routine end
155
+ if self.plots:
156
+ plot_labels(labels, names, self.save_dir)
157
+ paths = self.save_dir.glob('*labels*.jpg') # training labels
158
+ if self.wandb:
159
+ self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})
160
+ # if self.clearml:
161
+ # pass # ClearML saves these images automatically using hooks
162
+ if self.comet_logger:
163
+ self.comet_logger.on_pretrain_routine_end(paths)
164
+
165
+ def on_train_batch_end(self, model, ni, imgs, targets, paths, vals):
166
+ log_dict = dict(zip(self.keys[0:3], vals))
167
+ # Callback runs on train batch end
168
+ # ni: number integrated batches (since train start)
169
+ if self.plots:
170
+ if ni < 3:
171
+ f = self.save_dir / f'train_batch{ni}.jpg' # filename
172
+ plot_images(imgs, targets, paths, f)
173
+ if ni == 0 and self.tb and not self.opt.sync_bn:
174
+ log_tensorboard_graph(self.tb, model, imgsz=(self.opt.imgsz, self.opt.imgsz))
175
+ if ni == 10 and (self.wandb or self.clearml):
176
+ files = sorted(self.save_dir.glob('train*.jpg'))
177
+ if self.wandb:
178
+ self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
179
+ if self.clearml:
180
+ self.clearml.log_debug_samples(files, title='Mosaics')
181
+
182
+ if self.comet_logger:
183
+ self.comet_logger.on_train_batch_end(log_dict, step=ni)
184
+
185
+ def on_train_epoch_end(self, epoch):
186
+ # Callback runs on train epoch end
187
+ if self.wandb:
188
+ self.wandb.current_epoch = epoch + 1
189
+
190
+ if self.comet_logger:
191
+ self.comet_logger.on_train_epoch_end(epoch)
192
+
193
+ def on_val_start(self):
194
+ if self.comet_logger:
195
+ self.comet_logger.on_val_start()
196
+
197
+ def on_val_image_end(self, pred, predn, path, names, im):
198
+ # Callback runs on val image end
199
+ if self.wandb:
200
+ self.wandb.val_one_image(pred, predn, path, names, im)
201
+ if self.clearml:
202
+ self.clearml.log_image_with_boxes(path, pred, names, im)
203
+
204
+ def on_val_batch_end(self, batch_i, im, targets, paths, shapes, out):
205
+ if self.comet_logger:
206
+ self.comet_logger.on_val_batch_end(batch_i, im, targets, paths, shapes, out)
207
+
208
+ def on_val_end(self, nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix):
209
+ # Callback runs on val end
210
+ if self.wandb or self.clearml:
211
+ files = sorted(self.save_dir.glob('val*.jpg'))
212
+ if self.wandb:
213
+ self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})
214
+ if self.clearml:
215
+ self.clearml.log_debug_samples(files, title='Validation')
216
+
217
+ if self.comet_logger:
218
+ self.comet_logger.on_val_end(nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix)
219
+
220
+ def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
221
+ # Callback runs at the end of each fit (train+val) epoch
222
+ x = dict(zip(self.keys, vals))
223
+ if self.csv:
224
+ file = self.save_dir / 'results.csv'
225
+ n = len(x) + 1 # number of cols
226
+ s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header
227
+ with open(file, 'a') as f:
228
+ f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
229
+
230
+ if self.tb:
231
+ for k, v in x.items():
232
+ self.tb.add_scalar(k, v, epoch)
233
+ elif self.clearml: # log to ClearML if TensorBoard not used
234
+ for k, v in x.items():
235
+ title, series = k.split('/')
236
+ self.clearml.task.get_logger().report_scalar(title, series, v, epoch)
237
+
238
+ if self.wandb:
239
+ if best_fitness == fi:
240
+ best_results = [epoch] + vals[3:7]
241
+ for i, name in enumerate(self.best_keys):
242
+ self.wandb.wandb_run.summary[name] = best_results[i] # log best results in the summary
243
+ self.wandb.log(x)
244
+ self.wandb.end_epoch(best_result=best_fitness == fi)
245
+
246
+ if self.clearml:
247
+ self.clearml.current_epoch_logged_images = set() # reset epoch image limit
248
+ self.clearml.current_epoch += 1
249
+
250
+ if self.comet_logger:
251
+ self.comet_logger.on_fit_epoch_end(x, epoch=epoch)
252
+
253
+ def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
254
+ # Callback runs on model save event
255
+ if (epoch + 1) % self.opt.save_period == 0 and not final_epoch and self.opt.save_period != -1:
256
+ if self.wandb:
257
+ self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
258
+ if self.clearml:
259
+ self.clearml.task.update_output_model(model_path=str(last),
260
+ model_name='Latest Model',
261
+ auto_delete_file=False)
262
+
263
+ if self.comet_logger:
264
+ self.comet_logger.on_model_save(last, epoch, final_epoch, best_fitness, fi)
265
+
266
+ def on_train_end(self, last, best, epoch, results):
267
+ # Callback runs on training end, i.e. saving best model
268
+ if self.plots:
269
+ plot_results(file=self.save_dir / 'results.csv') # save results.png
270
+ files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]
271
+ files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter
272
+ self.logger.info(f"Results saved to {colorstr('bold', self.save_dir)}")
273
+
274
+ if self.tb and not self.clearml: # These images are already captured by ClearML by now, we don't want doubles
275
+ for f in files:
276
+ self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
277
+
278
+ if self.wandb:
279
+ self.wandb.log(dict(zip(self.keys[3:10], results)))
280
+ self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
281
+ # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
282
+ if not self.opt.evolve:
283
+ wandb.log_artifact(str(best if best.exists() else last),
284
+ type='model',
285
+ name=f'run_{self.wandb.wandb_run.id}_model',
286
+ aliases=['latest', 'best', 'stripped'])
287
+ self.wandb.finish_run()
288
+
289
+ if self.clearml and not self.opt.evolve:
290
+ self.clearml.task.update_output_model(model_path=str(best if best.exists() else last),
291
+ name='Best Model',
292
+ auto_delete_file=False)
293
+
294
+ if self.comet_logger:
295
+ final_results = dict(zip(self.keys[3:10], results))
296
+ self.comet_logger.on_train_end(files, self.save_dir, last, best, epoch, final_results)
297
+
298
+ def on_params_update(self, params: dict):
299
+ # Update hyperparams or configs of the experiment
300
+ if self.wandb:
301
+ self.wandb.wandb_run.config.update(params, allow_val_change=True)
302
+ if self.comet_logger:
303
+ self.comet_logger.on_params_update(params)
304
+
305
+
306
+ class GenericLogger:
307
+ """
308
+ YOLO General purpose logger for non-task specific logging
309
+ Usage: from utils.loggers import GenericLogger; logger = GenericLogger(...)
310
+ Arguments
311
+ opt: Run arguments
312
+ console_logger: Console logger
313
+ include: loggers to include
314
+ """
315
+
316
+ def __init__(self, opt, console_logger, include=('tb', 'wandb')):
317
+ # init default loggers
318
+ self.save_dir = Path(opt.save_dir)
319
+ self.include = include
320
+ self.console_logger = console_logger
321
+ self.csv = self.save_dir / 'results.csv' # CSV logger
322
+ if 'tb' in self.include:
323
+ prefix = colorstr('TensorBoard: ')
324
+ self.console_logger.info(
325
+ f"{prefix}Start with 'tensorboard --logdir {self.save_dir.parent}', view at http://localhost:6006/")
326
+ self.tb = SummaryWriter(str(self.save_dir))
327
+
328
+ if wandb and 'wandb' in self.include:
329
+ self.wandb = wandb.init(project=web_project_name(str(opt.project)),
330
+ name=None if opt.name == "exp" else opt.name,
331
+ config=opt)
332
+ else:
333
+ self.wandb = None
334
+
335
+ def log_metrics(self, metrics, epoch):
336
+ # Log metrics dictionary to all loggers
337
+ if self.csv:
338
+ keys, vals = list(metrics.keys()), list(metrics.values())
339
+ n = len(metrics) + 1 # number of cols
340
+ s = '' if self.csv.exists() else (('%23s,' * n % tuple(['epoch'] + keys)).rstrip(',') + '\n') # header
341
+ with open(self.csv, 'a') as f:
342
+ f.write(s + ('%23.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
343
+
344
+ if self.tb:
345
+ for k, v in metrics.items():
346
+ self.tb.add_scalar(k, v, epoch)
347
+
348
+ if self.wandb:
349
+ self.wandb.log(metrics, step=epoch)
350
+
351
+ def log_images(self, files, name='Images', epoch=0):
352
+ # Log images to all loggers
353
+ files = [Path(f) for f in (files if isinstance(files, (tuple, list)) else [files])] # to Path
354
+ files = [f for f in files if f.exists()] # filter by exists
355
+
356
+ if self.tb:
357
+ for f in files:
358
+ self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
359
+
360
+ if self.wandb:
361
+ self.wandb.log({name: [wandb.Image(str(f), caption=f.name) for f in files]}, step=epoch)
362
+
363
+ def log_graph(self, model, imgsz=(640, 640)):
364
+ # Log model graph to all loggers
365
+ if self.tb:
366
+ log_tensorboard_graph(self.tb, model, imgsz)
367
+
368
+ def log_model(self, model_path, epoch=0, metadata={}):
369
+ # Log model to all loggers
370
+ if self.wandb:
371
+ art = wandb.Artifact(name=f"run_{wandb.run.id}_model", type="model", metadata=metadata)
372
+ art.add_file(str(model_path))
373
+ wandb.log_artifact(art)
374
+
375
+ def update_params(self, params):
376
+ # Update the paramters logged
377
+ if self.wandb:
378
+ wandb.run.config.update(params, allow_val_change=True)
379
+
380
+
381
+ def log_tensorboard_graph(tb, model, imgsz=(640, 640)):
382
+ # Log model graph to TensorBoard
383
+ try:
384
+ p = next(model.parameters()) # for device, type
385
+ imgsz = (imgsz, imgsz) if isinstance(imgsz, int) else imgsz # expand
386
+ im = torch.zeros((1, 3, *imgsz)).to(p.device).type_as(p) # input image (WARNING: must be zeros, not empty)
387
+ with warnings.catch_warnings():
388
+ warnings.simplefilter('ignore') # suppress jit trace warning
389
+ tb.add_graph(torch.jit.trace(de_parallel(model), im, strict=False), [])
390
+ except Exception as e:
391
+ LOGGER.warning(f'WARNING ⚠️ TensorBoard graph visualization failure {e}')
392
+
393
+
394
+ def web_project_name(project):
395
+ # Convert local project name to web project name
396
+ if not project.startswith('runs/train'):
397
+ return project
398
+ suffix = '-Classify' if project.endswith('-cls') else '-Segment' if project.endswith('-seg') else ''
399
+ return f'YOLO{suffix}'
utils/loggers/clearml/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # init
utils/loggers/clearml/clearml_utils.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main Logger class for ClearML experiment tracking."""
2
+ import glob
3
+ import re
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import yaml
8
+
9
+ from utils.plots import Annotator, colors
10
+
11
+ try:
12
+ import clearml
13
+ from clearml import Dataset, Task
14
+
15
+ assert hasattr(clearml, '__version__') # verify package import not local dir
16
+ except (ImportError, AssertionError):
17
+ clearml = None
18
+
19
+
20
+ def construct_dataset(clearml_info_string):
21
+ """Load in a clearml dataset and fill the internal data_dict with its contents.
22
+ """
23
+ dataset_id = clearml_info_string.replace('clearml://', '')
24
+ dataset = Dataset.get(dataset_id=dataset_id)
25
+ dataset_root_path = Path(dataset.get_local_copy())
26
+
27
+ # We'll search for the yaml file definition in the dataset
28
+ yaml_filenames = list(glob.glob(str(dataset_root_path / "*.yaml")) + glob.glob(str(dataset_root_path / "*.yml")))
29
+ if len(yaml_filenames) > 1:
30
+ raise ValueError('More than one yaml file was found in the dataset root, cannot determine which one contains '
31
+ 'the dataset definition this way.')
32
+ elif len(yaml_filenames) == 0:
33
+ raise ValueError('No yaml definition found in dataset root path, check that there is a correct yaml file '
34
+ 'inside the dataset root path.')
35
+ with open(yaml_filenames[0]) as f:
36
+ dataset_definition = yaml.safe_load(f)
37
+
38
+ assert set(dataset_definition.keys()).issuperset(
39
+ {'train', 'test', 'val', 'nc', 'names'}
40
+ ), "The right keys were not found in the yaml file, make sure it at least has the following keys: ('train', 'test', 'val', 'nc', 'names')"
41
+
42
+ data_dict = dict()
43
+ data_dict['train'] = str(
44
+ (dataset_root_path / dataset_definition['train']).resolve()) if dataset_definition['train'] else None
45
+ data_dict['test'] = str(
46
+ (dataset_root_path / dataset_definition['test']).resolve()) if dataset_definition['test'] else None
47
+ data_dict['val'] = str(
48
+ (dataset_root_path / dataset_definition['val']).resolve()) if dataset_definition['val'] else None
49
+ data_dict['nc'] = dataset_definition['nc']
50
+ data_dict['names'] = dataset_definition['names']
51
+
52
+ return data_dict
53
+
54
+
55
+ class ClearmlLogger:
56
+ """Log training runs, datasets, models, and predictions to ClearML.
57
+
58
+ This logger sends information to ClearML at app.clear.ml or to your own hosted server. By default,
59
+ this information includes hyperparameters, system configuration and metrics, model metrics, code information and
60
+ basic data metrics and analyses.
61
+
62
+ By providing additional command line arguments to train.py, datasets,
63
+ models and predictions can also be logged.
64
+ """
65
+
66
+ def __init__(self, opt, hyp):
67
+ """
68
+ - Initialize ClearML Task, this object will capture the experiment
69
+ - Upload dataset version to ClearML Data if opt.upload_dataset is True
70
+
71
+ arguments:
72
+ opt (namespace) -- Commandline arguments for this run
73
+ hyp (dict) -- Hyperparameters for this run
74
+
75
+ """
76
+ self.current_epoch = 0
77
+ # Keep tracked of amount of logged images to enforce a limit
78
+ self.current_epoch_logged_images = set()
79
+ # Maximum number of images to log to clearML per epoch
80
+ self.max_imgs_to_log_per_epoch = 16
81
+ # Get the interval of epochs when bounding box images should be logged
82
+ self.bbox_interval = opt.bbox_interval
83
+ self.clearml = clearml
84
+ self.task = None
85
+ self.data_dict = None
86
+ if self.clearml:
87
+ self.task = Task.init(
88
+ project_name=opt.project if opt.project != 'runs/train' else 'YOLOv5',
89
+ task_name=opt.name if opt.name != 'exp' else 'Training',
90
+ tags=['YOLOv5'],
91
+ output_uri=True,
92
+ auto_connect_frameworks={'pytorch': False}
93
+ # We disconnect pytorch auto-detection, because we added manual model save points in the code
94
+ )
95
+ # ClearML's hooks will already grab all general parameters
96
+ # Only the hyperparameters coming from the yaml config file
97
+ # will have to be added manually!
98
+ self.task.connect(hyp, name='Hyperparameters')
99
+
100
+ # Get ClearML Dataset Version if requested
101
+ if opt.data.startswith('clearml://'):
102
+ # data_dict should have the following keys:
103
+ # names, nc (number of classes), test, train, val (all three relative paths to ../datasets)
104
+ self.data_dict = construct_dataset(opt.data)
105
+ # Set data to data_dict because wandb will crash without this information and opt is the best way
106
+ # to give it to them
107
+ opt.data = self.data_dict
108
+
109
+ def log_debug_samples(self, files, title='Debug Samples'):
110
+ """
111
+ Log files (images) as debug samples in the ClearML task.
112
+
113
+ arguments:
114
+ files (List(PosixPath)) a list of file paths in PosixPath format
115
+ title (str) A title that groups together images with the same values
116
+ """
117
+ for f in files:
118
+ if f.exists():
119
+ it = re.search(r'_batch(\d+)', f.name)
120
+ iteration = int(it.groups()[0]) if it else 0
121
+ self.task.get_logger().report_image(title=title,
122
+ series=f.name.replace(it.group(), ''),
123
+ local_path=str(f),
124
+ iteration=iteration)
125
+
126
+ def log_image_with_boxes(self, image_path, boxes, class_names, image, conf_threshold=0.25):
127
+ """
128
+ Draw the bounding boxes on a single image and report the result as a ClearML debug sample.
129
+
130
+ arguments:
131
+ image_path (PosixPath) the path the original image file
132
+ boxes (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
133
+ class_names (dict): dict containing mapping of class int to class name
134
+ image (Tensor): A torch tensor containing the actual image data
135
+ """
136
+ if len(self.current_epoch_logged_images) < self.max_imgs_to_log_per_epoch and self.current_epoch >= 0:
137
+ # Log every bbox_interval times and deduplicate for any intermittend extra eval runs
138
+ if self.current_epoch % self.bbox_interval == 0 and image_path not in self.current_epoch_logged_images:
139
+ im = np.ascontiguousarray(np.moveaxis(image.mul(255).clamp(0, 255).byte().cpu().numpy(), 0, 2))
140
+ annotator = Annotator(im=im, pil=True)
141
+ for i, (conf, class_nr, box) in enumerate(zip(boxes[:, 4], boxes[:, 5], boxes[:, :4])):
142
+ color = colors(i)
143
+
144
+ class_name = class_names[int(class_nr)]
145
+ confidence_percentage = round(float(conf) * 100, 2)
146
+ label = f"{class_name}: {confidence_percentage}%"
147
+
148
+ if conf > conf_threshold:
149
+ annotator.rectangle(box.cpu().numpy(), outline=color)
150
+ annotator.box_label(box.cpu().numpy(), label=label, color=color)
151
+
152
+ annotated_image = annotator.result()
153
+ self.task.get_logger().report_image(title='Bounding Boxes',
154
+ series=image_path.name,
155
+ iteration=self.current_epoch,
156
+ image=annotated_image)
157
+ self.current_epoch_logged_images.add(image_path)
utils/loggers/clearml/hpo.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from clearml import Task
2
+ # Connecting ClearML with the current process,
3
+ # from here on everything is logged automatically
4
+ from clearml.automation import HyperParameterOptimizer, UniformParameterRange
5
+ from clearml.automation.optuna import OptimizerOptuna
6
+
7
+ task = Task.init(project_name='Hyper-Parameter Optimization',
8
+ task_name='YOLOv5',
9
+ task_type=Task.TaskTypes.optimizer,
10
+ reuse_last_task_id=False)
11
+
12
+ # Example use case:
13
+ optimizer = HyperParameterOptimizer(
14
+ # This is the experiment we want to optimize
15
+ base_task_id='<your_template_task_id>',
16
+ # here we define the hyper-parameters to optimize
17
+ # Notice: The parameter name should exactly match what you see in the UI: <section_name>/<parameter>
18
+ # For Example, here we see in the base experiment a section Named: "General"
19
+ # under it a parameter named "batch_size", this becomes "General/batch_size"
20
+ # If you have `argparse` for example, then arguments will appear under the "Args" section,
21
+ # and you should instead pass "Args/batch_size"
22
+ hyper_parameters=[
23
+ UniformParameterRange('Hyperparameters/lr0', min_value=1e-5, max_value=1e-1),
24
+ UniformParameterRange('Hyperparameters/lrf', min_value=0.01, max_value=1.0),
25
+ UniformParameterRange('Hyperparameters/momentum', min_value=0.6, max_value=0.98),
26
+ UniformParameterRange('Hyperparameters/weight_decay', min_value=0.0, max_value=0.001),
27
+ UniformParameterRange('Hyperparameters/warmup_epochs', min_value=0.0, max_value=5.0),
28
+ UniformParameterRange('Hyperparameters/warmup_momentum', min_value=0.0, max_value=0.95),
29
+ UniformParameterRange('Hyperparameters/warmup_bias_lr', min_value=0.0, max_value=0.2),
30
+ UniformParameterRange('Hyperparameters/box', min_value=0.02, max_value=0.2),
31
+ UniformParameterRange('Hyperparameters/cls', min_value=0.2, max_value=4.0),
32
+ UniformParameterRange('Hyperparameters/cls_pw', min_value=0.5, max_value=2.0),
33
+ UniformParameterRange('Hyperparameters/obj', min_value=0.2, max_value=4.0),
34
+ UniformParameterRange('Hyperparameters/obj_pw', min_value=0.5, max_value=2.0),
35
+ UniformParameterRange('Hyperparameters/iou_t', min_value=0.1, max_value=0.7),
36
+ UniformParameterRange('Hyperparameters/anchor_t', min_value=2.0, max_value=8.0),
37
+ UniformParameterRange('Hyperparameters/fl_gamma', min_value=0.0, max_value=4.0),
38
+ UniformParameterRange('Hyperparameters/hsv_h', min_value=0.0, max_value=0.1),
39
+ UniformParameterRange('Hyperparameters/hsv_s', min_value=0.0, max_value=0.9),
40
+ UniformParameterRange('Hyperparameters/hsv_v', min_value=0.0, max_value=0.9),
41
+ UniformParameterRange('Hyperparameters/degrees', min_value=0.0, max_value=45.0),
42
+ UniformParameterRange('Hyperparameters/translate', min_value=0.0, max_value=0.9),
43
+ UniformParameterRange('Hyperparameters/scale', min_value=0.0, max_value=0.9),
44
+ UniformParameterRange('Hyperparameters/shear', min_value=0.0, max_value=10.0),
45
+ UniformParameterRange('Hyperparameters/perspective', min_value=0.0, max_value=0.001),
46
+ UniformParameterRange('Hyperparameters/flipud', min_value=0.0, max_value=1.0),
47
+ UniformParameterRange('Hyperparameters/fliplr', min_value=0.0, max_value=1.0),
48
+ UniformParameterRange('Hyperparameters/mosaic', min_value=0.0, max_value=1.0),
49
+ UniformParameterRange('Hyperparameters/mixup', min_value=0.0, max_value=1.0),
50
+ UniformParameterRange('Hyperparameters/copy_paste', min_value=0.0, max_value=1.0)],
51
+ # this is the objective metric we want to maximize/minimize
52
+ objective_metric_title='metrics',
53
+ objective_metric_series='mAP_0.5',
54
+ # now we decide if we want to maximize it or minimize it (accuracy we maximize)
55
+ objective_metric_sign='max',
56
+ # let us limit the number of concurrent experiments,
57
+ # this in turn will make sure we do dont bombard the scheduler with experiments.
58
+ # if we have an auto-scaler connected, this, by proxy, will limit the number of machine
59
+ max_number_of_concurrent_tasks=1,
60
+ # this is the optimizer class (actually doing the optimization)
61
+ # Currently, we can choose from GridSearch, RandomSearch or OptimizerBOHB (Bayesian optimization Hyper-Band)
62
+ optimizer_class=OptimizerOptuna,
63
+ # If specified only the top K performing Tasks will be kept, the others will be automatically archived
64
+ save_top_k_tasks_only=5, # 5,
65
+ compute_time_limit=None,
66
+ total_max_jobs=20,
67
+ min_iteration_per_job=None,
68
+ max_iteration_per_job=None,
69
+ )
70
+
71
+ # report every 10 seconds, this is way too often, but we are testing here
72
+ optimizer.set_report_period(10 / 60)
73
+ # You can also use the line below instead to run all the optimizer tasks locally, without using queues or agent
74
+ # an_optimizer.start_locally(job_complete_callback=job_complete_callback)
75
+ # set the time limit for the optimization process (2 hours)
76
+ optimizer.set_time_limit(in_minutes=120.0)
77
+ # Start the optimization process in the local environment
78
+ optimizer.start_locally()
79
+ # wait until process is done (notice we are controlling the optimization process in the background)
80
+ optimizer.wait()
81
+ # make sure background optimization stopped
82
+ optimizer.stop()
83
+
84
+ print('We are done, good bye')
utils/loggers/comet/__init__.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import logging
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ FILE = Path(__file__).resolve()
11
+ ROOT = FILE.parents[3] # YOLOv5 root directory
12
+ if str(ROOT) not in sys.path:
13
+ sys.path.append(str(ROOT)) # add ROOT to PATH
14
+
15
+ try:
16
+ import comet_ml
17
+
18
+ # Project Configuration
19
+ config = comet_ml.config.get_config()
20
+ COMET_PROJECT_NAME = config.get_string(os.getenv("COMET_PROJECT_NAME"), "comet.project_name", default="yolov5")
21
+ except (ModuleNotFoundError, ImportError):
22
+ comet_ml = None
23
+ COMET_PROJECT_NAME = None
24
+
25
+ import PIL
26
+ import torch
27
+ import torchvision.transforms as T
28
+ import yaml
29
+
30
+ from utils.dataloaders import img2label_paths
31
+ from utils.general import check_dataset, scale_boxes, xywh2xyxy
32
+ from utils.metrics import box_iou
33
+
34
+ COMET_PREFIX = "comet://"
35
+
36
+ COMET_MODE = os.getenv("COMET_MODE", "online")
37
+
38
+ # Model Saving Settings
39
+ COMET_MODEL_NAME = os.getenv("COMET_MODEL_NAME", "yolov5")
40
+
41
+ # Dataset Artifact Settings
42
+ COMET_UPLOAD_DATASET = os.getenv("COMET_UPLOAD_DATASET", "false").lower() == "true"
43
+
44
+ # Evaluation Settings
45
+ COMET_LOG_CONFUSION_MATRIX = os.getenv("COMET_LOG_CONFUSION_MATRIX", "true").lower() == "true"
46
+ COMET_LOG_PREDICTIONS = os.getenv("COMET_LOG_PREDICTIONS", "true").lower() == "true"
47
+ COMET_MAX_IMAGE_UPLOADS = int(os.getenv("COMET_MAX_IMAGE_UPLOADS", 100))
48
+
49
+ # Confusion Matrix Settings
50
+ CONF_THRES = float(os.getenv("CONF_THRES", 0.001))
51
+ IOU_THRES = float(os.getenv("IOU_THRES", 0.6))
52
+
53
+ # Batch Logging Settings
54
+ COMET_LOG_BATCH_METRICS = os.getenv("COMET_LOG_BATCH_METRICS", "false").lower() == "true"
55
+ COMET_BATCH_LOGGING_INTERVAL = os.getenv("COMET_BATCH_LOGGING_INTERVAL", 1)
56
+ COMET_PREDICTION_LOGGING_INTERVAL = os.getenv("COMET_PREDICTION_LOGGING_INTERVAL", 1)
57
+ COMET_LOG_PER_CLASS_METRICS = os.getenv("COMET_LOG_PER_CLASS_METRICS", "false").lower() == "true"
58
+
59
+ RANK = int(os.getenv("RANK", -1))
60
+
61
+ to_pil = T.ToPILImage()
62
+
63
+
64
+ class CometLogger:
65
+ """Log metrics, parameters, source code, models and much more
66
+ with Comet
67
+ """
68
+
69
+ def __init__(self, opt, hyp, run_id=None, job_type="Training", **experiment_kwargs) -> None:
70
+ self.job_type = job_type
71
+ self.opt = opt
72
+ self.hyp = hyp
73
+
74
+ # Comet Flags
75
+ self.comet_mode = COMET_MODE
76
+
77
+ self.save_model = opt.save_period > -1
78
+ self.model_name = COMET_MODEL_NAME
79
+
80
+ # Batch Logging Settings
81
+ self.log_batch_metrics = COMET_LOG_BATCH_METRICS
82
+ self.comet_log_batch_interval = COMET_BATCH_LOGGING_INTERVAL
83
+
84
+ # Dataset Artifact Settings
85
+ self.upload_dataset = self.opt.upload_dataset if self.opt.upload_dataset else COMET_UPLOAD_DATASET
86
+ self.resume = self.opt.resume
87
+
88
+ # Default parameters to pass to Experiment objects
89
+ self.default_experiment_kwargs = {
90
+ "log_code": False,
91
+ "log_env_gpu": True,
92
+ "log_env_cpu": True,
93
+ "project_name": COMET_PROJECT_NAME,}
94
+ self.default_experiment_kwargs.update(experiment_kwargs)
95
+ self.experiment = self._get_experiment(self.comet_mode, run_id)
96
+
97
+ self.data_dict = self.check_dataset(self.opt.data)
98
+ self.class_names = self.data_dict["names"]
99
+ self.num_classes = self.data_dict["nc"]
100
+
101
+ self.logged_images_count = 0
102
+ self.max_images = COMET_MAX_IMAGE_UPLOADS
103
+
104
+ if run_id is None:
105
+ self.experiment.log_other("Created from", "YOLOv5")
106
+ if not isinstance(self.experiment, comet_ml.OfflineExperiment):
107
+ workspace, project_name, experiment_id = self.experiment.url.split("/")[-3:]
108
+ self.experiment.log_other(
109
+ "Run Path",
110
+ f"{workspace}/{project_name}/{experiment_id}",
111
+ )
112
+ self.log_parameters(vars(opt))
113
+ self.log_parameters(self.opt.hyp)
114
+ self.log_asset_data(
115
+ self.opt.hyp,
116
+ name="hyperparameters.json",
117
+ metadata={"type": "hyp-config-file"},
118
+ )
119
+ self.log_asset(
120
+ f"{self.opt.save_dir}/opt.yaml",
121
+ metadata={"type": "opt-config-file"},
122
+ )
123
+
124
+ self.comet_log_confusion_matrix = COMET_LOG_CONFUSION_MATRIX
125
+
126
+ if hasattr(self.opt, "conf_thres"):
127
+ self.conf_thres = self.opt.conf_thres
128
+ else:
129
+ self.conf_thres = CONF_THRES
130
+ if hasattr(self.opt, "iou_thres"):
131
+ self.iou_thres = self.opt.iou_thres
132
+ else:
133
+ self.iou_thres = IOU_THRES
134
+
135
+ self.log_parameters({"val_iou_threshold": self.iou_thres, "val_conf_threshold": self.conf_thres})
136
+
137
+ self.comet_log_predictions = COMET_LOG_PREDICTIONS
138
+ if self.opt.bbox_interval == -1:
139
+ self.comet_log_prediction_interval = 1 if self.opt.epochs < 10 else self.opt.epochs // 10
140
+ else:
141
+ self.comet_log_prediction_interval = self.opt.bbox_interval
142
+
143
+ if self.comet_log_predictions:
144
+ self.metadata_dict = {}
145
+ self.logged_image_names = []
146
+
147
+ self.comet_log_per_class_metrics = COMET_LOG_PER_CLASS_METRICS
148
+
149
+ self.experiment.log_others({
150
+ "comet_mode": COMET_MODE,
151
+ "comet_max_image_uploads": COMET_MAX_IMAGE_UPLOADS,
152
+ "comet_log_per_class_metrics": COMET_LOG_PER_CLASS_METRICS,
153
+ "comet_log_batch_metrics": COMET_LOG_BATCH_METRICS,
154
+ "comet_log_confusion_matrix": COMET_LOG_CONFUSION_MATRIX,
155
+ "comet_model_name": COMET_MODEL_NAME,})
156
+
157
+ # Check if running the Experiment with the Comet Optimizer
158
+ if hasattr(self.opt, "comet_optimizer_id"):
159
+ self.experiment.log_other("optimizer_id", self.opt.comet_optimizer_id)
160
+ self.experiment.log_other("optimizer_objective", self.opt.comet_optimizer_objective)
161
+ self.experiment.log_other("optimizer_metric", self.opt.comet_optimizer_metric)
162
+ self.experiment.log_other("optimizer_parameters", json.dumps(self.hyp))
163
+
164
+ def _get_experiment(self, mode, experiment_id=None):
165
+ if mode == "offline":
166
+ if experiment_id is not None:
167
+ return comet_ml.ExistingOfflineExperiment(
168
+ previous_experiment=experiment_id,
169
+ **self.default_experiment_kwargs,
170
+ )
171
+
172
+ return comet_ml.OfflineExperiment(**self.default_experiment_kwargs,)
173
+
174
+ else:
175
+ try:
176
+ if experiment_id is not None:
177
+ return comet_ml.ExistingExperiment(
178
+ previous_experiment=experiment_id,
179
+ **self.default_experiment_kwargs,
180
+ )
181
+
182
+ return comet_ml.Experiment(**self.default_experiment_kwargs)
183
+
184
+ except ValueError:
185
+ logger.warning("COMET WARNING: "
186
+ "Comet credentials have not been set. "
187
+ "Comet will default to offline logging. "
188
+ "Please set your credentials to enable online logging.")
189
+ return self._get_experiment("offline", experiment_id)
190
+
191
+ return
192
+
193
+ def log_metrics(self, log_dict, **kwargs):
194
+ self.experiment.log_metrics(log_dict, **kwargs)
195
+
196
+ def log_parameters(self, log_dict, **kwargs):
197
+ self.experiment.log_parameters(log_dict, **kwargs)
198
+
199
+ def log_asset(self, asset_path, **kwargs):
200
+ self.experiment.log_asset(asset_path, **kwargs)
201
+
202
+ def log_asset_data(self, asset, **kwargs):
203
+ self.experiment.log_asset_data(asset, **kwargs)
204
+
205
+ def log_image(self, img, **kwargs):
206
+ self.experiment.log_image(img, **kwargs)
207
+
208
+ def log_model(self, path, opt, epoch, fitness_score, best_model=False):
209
+ if not self.save_model:
210
+ return
211
+
212
+ model_metadata = {
213
+ "fitness_score": fitness_score[-1],
214
+ "epochs_trained": epoch + 1,
215
+ "save_period": opt.save_period,
216
+ "total_epochs": opt.epochs,}
217
+
218
+ model_files = glob.glob(f"{path}/*.pt")
219
+ for model_path in model_files:
220
+ name = Path(model_path).name
221
+
222
+ self.experiment.log_model(
223
+ self.model_name,
224
+ file_or_folder=model_path,
225
+ file_name=name,
226
+ metadata=model_metadata,
227
+ overwrite=True,
228
+ )
229
+
230
+ def check_dataset(self, data_file):
231
+ with open(data_file) as f:
232
+ data_config = yaml.safe_load(f)
233
+
234
+ if data_config['path'].startswith(COMET_PREFIX):
235
+ path = data_config['path'].replace(COMET_PREFIX, "")
236
+ data_dict = self.download_dataset_artifact(path)
237
+
238
+ return data_dict
239
+
240
+ self.log_asset(self.opt.data, metadata={"type": "data-config-file"})
241
+
242
+ return check_dataset(data_file)
243
+
244
+ def log_predictions(self, image, labelsn, path, shape, predn):
245
+ if self.logged_images_count >= self.max_images:
246
+ return
247
+ detections = predn[predn[:, 4] > self.conf_thres]
248
+ iou = box_iou(labelsn[:, 1:], detections[:, :4])
249
+ mask, _ = torch.where(iou > self.iou_thres)
250
+ if len(mask) == 0:
251
+ return
252
+
253
+ filtered_detections = detections[mask]
254
+ filtered_labels = labelsn[mask]
255
+
256
+ image_id = path.split("/")[-1].split(".")[0]
257
+ image_name = f"{image_id}_curr_epoch_{self.experiment.curr_epoch}"
258
+ if image_name not in self.logged_image_names:
259
+ native_scale_image = PIL.Image.open(path)
260
+ self.log_image(native_scale_image, name=image_name)
261
+ self.logged_image_names.append(image_name)
262
+
263
+ metadata = []
264
+ for cls, *xyxy in filtered_labels.tolist():
265
+ metadata.append({
266
+ "label": f"{self.class_names[int(cls)]}-gt",
267
+ "score": 100,
268
+ "box": {
269
+ "x": xyxy[0],
270
+ "y": xyxy[1],
271
+ "x2": xyxy[2],
272
+ "y2": xyxy[3]},})
273
+ for *xyxy, conf, cls in filtered_detections.tolist():
274
+ metadata.append({
275
+ "label": f"{self.class_names[int(cls)]}",
276
+ "score": conf * 100,
277
+ "box": {
278
+ "x": xyxy[0],
279
+ "y": xyxy[1],
280
+ "x2": xyxy[2],
281
+ "y2": xyxy[3]},})
282
+
283
+ self.metadata_dict[image_name] = metadata
284
+ self.logged_images_count += 1
285
+
286
+ return
287
+
288
+ def preprocess_prediction(self, image, labels, shape, pred):
289
+ nl, _ = labels.shape[0], pred.shape[0]
290
+
291
+ # Predictions
292
+ if self.opt.single_cls:
293
+ pred[:, 5] = 0
294
+
295
+ predn = pred.clone()
296
+ scale_boxes(image.shape[1:], predn[:, :4], shape[0], shape[1])
297
+
298
+ labelsn = None
299
+ if nl:
300
+ tbox = xywh2xyxy(labels[:, 1:5]) # target boxes
301
+ scale_boxes(image.shape[1:], tbox, shape[0], shape[1]) # native-space labels
302
+ labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
303
+ scale_boxes(image.shape[1:], predn[:, :4], shape[0], shape[1]) # native-space pred
304
+
305
+ return predn, labelsn
306
+
307
+ def add_assets_to_artifact(self, artifact, path, asset_path, split):
308
+ img_paths = sorted(glob.glob(f"{asset_path}/*"))
309
+ label_paths = img2label_paths(img_paths)
310
+
311
+ for image_file, label_file in zip(img_paths, label_paths):
312
+ image_logical_path, label_logical_path = map(lambda x: os.path.relpath(x, path), [image_file, label_file])
313
+
314
+ try:
315
+ artifact.add(image_file, logical_path=image_logical_path, metadata={"split": split})
316
+ artifact.add(label_file, logical_path=label_logical_path, metadata={"split": split})
317
+ except ValueError as e:
318
+ logger.error('COMET ERROR: Error adding file to Artifact. Skipping file.')
319
+ logger.error(f"COMET ERROR: {e}")
320
+ continue
321
+
322
+ return artifact
323
+
324
+ def upload_dataset_artifact(self):
325
+ dataset_name = self.data_dict.get("dataset_name", "yolov5-dataset")
326
+ path = str((ROOT / Path(self.data_dict["path"])).resolve())
327
+
328
+ metadata = self.data_dict.copy()
329
+ for key in ["train", "val", "test"]:
330
+ split_path = metadata.get(key)
331
+ if split_path is not None:
332
+ metadata[key] = split_path.replace(path, "")
333
+
334
+ artifact = comet_ml.Artifact(name=dataset_name, artifact_type="dataset", metadata=metadata)
335
+ for key in metadata.keys():
336
+ if key in ["train", "val", "test"]:
337
+ if isinstance(self.upload_dataset, str) and (key != self.upload_dataset):
338
+ continue
339
+
340
+ asset_path = self.data_dict.get(key)
341
+ if asset_path is not None:
342
+ artifact = self.add_assets_to_artifact(artifact, path, asset_path, key)
343
+
344
+ self.experiment.log_artifact(artifact)
345
+
346
+ return
347
+
348
+ def download_dataset_artifact(self, artifact_path):
349
+ logged_artifact = self.experiment.get_artifact(artifact_path)
350
+ artifact_save_dir = str(Path(self.opt.save_dir) / logged_artifact.name)
351
+ logged_artifact.download(artifact_save_dir)
352
+
353
+ metadata = logged_artifact.metadata
354
+ data_dict = metadata.copy()
355
+ data_dict["path"] = artifact_save_dir
356
+
357
+ metadata_names = metadata.get("names")
358
+ if type(metadata_names) == dict:
359
+ data_dict["names"] = {int(k): v for k, v in metadata.get("names").items()}
360
+ elif type(metadata_names) == list:
361
+ data_dict["names"] = {int(k): v for k, v in zip(range(len(metadata_names)), metadata_names)}
362
+ else:
363
+ raise "Invalid 'names' field in dataset yaml file. Please use a list or dictionary"
364
+
365
+ data_dict = self.update_data_paths(data_dict)
366
+ return data_dict
367
+
368
+ def update_data_paths(self, data_dict):
369
+ path = data_dict.get("path", "")
370
+
371
+ for split in ["train", "val", "test"]:
372
+ if data_dict.get(split):
373
+ split_path = data_dict.get(split)
374
+ data_dict[split] = (f"{path}/{split_path}" if isinstance(split, str) else [
375
+ f"{path}/{x}" for x in split_path])
376
+
377
+ return data_dict
378
+
379
+ def on_pretrain_routine_end(self, paths):
380
+ if self.opt.resume:
381
+ return
382
+
383
+ for path in paths:
384
+ self.log_asset(str(path))
385
+
386
+ if self.upload_dataset:
387
+ if not self.resume:
388
+ self.upload_dataset_artifact()
389
+
390
+ return
391
+
392
+ def on_train_start(self):
393
+ self.log_parameters(self.hyp)
394
+
395
+ def on_train_epoch_start(self):
396
+ return
397
+
398
+ def on_train_epoch_end(self, epoch):
399
+ self.experiment.curr_epoch = epoch
400
+
401
+ return
402
+
403
+ def on_train_batch_start(self):
404
+ return
405
+
406
+ def on_train_batch_end(self, log_dict, step):
407
+ self.experiment.curr_step = step
408
+ if self.log_batch_metrics and (step % self.comet_log_batch_interval == 0):
409
+ self.log_metrics(log_dict, step=step)
410
+
411
+ return
412
+
413
+ def on_train_end(self, files, save_dir, last, best, epoch, results):
414
+ if self.comet_log_predictions:
415
+ curr_epoch = self.experiment.curr_epoch
416
+ self.experiment.log_asset_data(self.metadata_dict, "image-metadata.json", epoch=curr_epoch)
417
+
418
+ for f in files:
419
+ self.log_asset(f, metadata={"epoch": epoch})
420
+ self.log_asset(f"{save_dir}/results.csv", metadata={"epoch": epoch})
421
+
422
+ if not self.opt.evolve:
423
+ model_path = str(best if best.exists() else last)
424
+ name = Path(model_path).name
425
+ if self.save_model:
426
+ self.experiment.log_model(
427
+ self.model_name,
428
+ file_or_folder=model_path,
429
+ file_name=name,
430
+ overwrite=True,
431
+ )
432
+
433
+ # Check if running Experiment with Comet Optimizer
434
+ if hasattr(self.opt, 'comet_optimizer_id'):
435
+ metric = results.get(self.opt.comet_optimizer_metric)
436
+ self.experiment.log_other('optimizer_metric_value', metric)
437
+
438
+ self.finish_run()
439
+
440
+ def on_val_start(self):
441
+ return
442
+
443
+ def on_val_batch_start(self):
444
+ return
445
+
446
+ def on_val_batch_end(self, batch_i, images, targets, paths, shapes, outputs):
447
+ if not (self.comet_log_predictions and ((batch_i + 1) % self.comet_log_prediction_interval == 0)):
448
+ return
449
+
450
+ for si, pred in enumerate(outputs):
451
+ if len(pred) == 0:
452
+ continue
453
+
454
+ image = images[si]
455
+ labels = targets[targets[:, 0] == si, 1:]
456
+ shape = shapes[si]
457
+ path = paths[si]
458
+ predn, labelsn = self.preprocess_prediction(image, labels, shape, pred)
459
+ if labelsn is not None:
460
+ self.log_predictions(image, labelsn, path, shape, predn)
461
+
462
+ return
463
+
464
+ def on_val_end(self, nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix):
465
+ if self.comet_log_per_class_metrics:
466
+ if self.num_classes > 1:
467
+ for i, c in enumerate(ap_class):
468
+ class_name = self.class_names[c]
469
+ self.experiment.log_metrics(
470
+ {
471
+ 'mAP@.5': ap50[i],
472
+ 'mAP@.5:.95': ap[i],
473
+ 'precision': p[i],
474
+ 'recall': r[i],
475
+ 'f1': f1[i],
476
+ 'true_positives': tp[i],
477
+ 'false_positives': fp[i],
478
+ 'support': nt[c]},
479
+ prefix=class_name)
480
+
481
+ if self.comet_log_confusion_matrix:
482
+ epoch = self.experiment.curr_epoch
483
+ class_names = list(self.class_names.values())
484
+ class_names.append("background")
485
+ num_classes = len(class_names)
486
+
487
+ self.experiment.log_confusion_matrix(
488
+ matrix=confusion_matrix.matrix,
489
+ max_categories=num_classes,
490
+ labels=class_names,
491
+ epoch=epoch,
492
+ column_label='Actual Category',
493
+ row_label='Predicted Category',
494
+ file_name=f"confusion-matrix-epoch-{epoch}.json",
495
+ )
496
+
497
+ def on_fit_epoch_end(self, result, epoch):
498
+ self.log_metrics(result, epoch=epoch)
499
+
500
+ def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
501
+ if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:
502
+ self.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
503
+
504
+ def on_params_update(self, params):
505
+ self.log_parameters(params)
506
+
507
+ def finish_run(self):
508
+ self.experiment.end()
utils/loggers/comet/comet_utils.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from urllib.parse import urlparse
4
+
5
+ try:
6
+ import comet_ml
7
+ except (ModuleNotFoundError, ImportError):
8
+ comet_ml = None
9
+
10
+ import yaml
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ COMET_PREFIX = "comet://"
15
+ COMET_MODEL_NAME = os.getenv("COMET_MODEL_NAME", "yolov5")
16
+ COMET_DEFAULT_CHECKPOINT_FILENAME = os.getenv("COMET_DEFAULT_CHECKPOINT_FILENAME", "last.pt")
17
+
18
+
19
+ def download_model_checkpoint(opt, experiment):
20
+ model_dir = f"{opt.project}/{experiment.name}"
21
+ os.makedirs(model_dir, exist_ok=True)
22
+
23
+ model_name = COMET_MODEL_NAME
24
+ model_asset_list = experiment.get_model_asset_list(model_name)
25
+
26
+ if len(model_asset_list) == 0:
27
+ logger.error(f"COMET ERROR: No checkpoints found for model name : {model_name}")
28
+ return
29
+
30
+ model_asset_list = sorted(
31
+ model_asset_list,
32
+ key=lambda x: x["step"],
33
+ reverse=True,
34
+ )
35
+ logged_checkpoint_map = {asset["fileName"]: asset["assetId"] for asset in model_asset_list}
36
+
37
+ resource_url = urlparse(opt.weights)
38
+ checkpoint_filename = resource_url.query
39
+
40
+ if checkpoint_filename:
41
+ asset_id = logged_checkpoint_map.get(checkpoint_filename)
42
+ else:
43
+ asset_id = logged_checkpoint_map.get(COMET_DEFAULT_CHECKPOINT_FILENAME)
44
+ checkpoint_filename = COMET_DEFAULT_CHECKPOINT_FILENAME
45
+
46
+ if asset_id is None:
47
+ logger.error(f"COMET ERROR: Checkpoint {checkpoint_filename} not found in the given Experiment")
48
+ return
49
+
50
+ try:
51
+ logger.info(f"COMET INFO: Downloading checkpoint {checkpoint_filename}")
52
+ asset_filename = checkpoint_filename
53
+
54
+ model_binary = experiment.get_asset(asset_id, return_type="binary", stream=False)
55
+ model_download_path = f"{model_dir}/{asset_filename}"
56
+ with open(model_download_path, "wb") as f:
57
+ f.write(model_binary)
58
+
59
+ opt.weights = model_download_path
60
+
61
+ except Exception as e:
62
+ logger.warning("COMET WARNING: Unable to download checkpoint from Comet")
63
+ logger.exception(e)
64
+
65
+
66
+ def set_opt_parameters(opt, experiment):
67
+ """Update the opts Namespace with parameters
68
+ from Comet's ExistingExperiment when resuming a run
69
+
70
+ Args:
71
+ opt (argparse.Namespace): Namespace of command line options
72
+ experiment (comet_ml.APIExperiment): Comet API Experiment object
73
+ """
74
+ asset_list = experiment.get_asset_list()
75
+ resume_string = opt.resume
76
+
77
+ for asset in asset_list:
78
+ if asset["fileName"] == "opt.yaml":
79
+ asset_id = asset["assetId"]
80
+ asset_binary = experiment.get_asset(asset_id, return_type="binary", stream=False)
81
+ opt_dict = yaml.safe_load(asset_binary)
82
+ for key, value in opt_dict.items():
83
+ setattr(opt, key, value)
84
+ opt.resume = resume_string
85
+
86
+ # Save hyperparameters to YAML file
87
+ # Necessary to pass checks in training script
88
+ save_dir = f"{opt.project}/{experiment.name}"
89
+ os.makedirs(save_dir, exist_ok=True)
90
+
91
+ hyp_yaml_path = f"{save_dir}/hyp.yaml"
92
+ with open(hyp_yaml_path, "w") as f:
93
+ yaml.dump(opt.hyp, f)
94
+ opt.hyp = hyp_yaml_path
95
+
96
+
97
+ def check_comet_weights(opt):
98
+ """Downloads model weights from Comet and updates the
99
+ weights path to point to saved weights location
100
+
101
+ Args:
102
+ opt (argparse.Namespace): Command Line arguments passed
103
+ to YOLOv5 training script
104
+
105
+ Returns:
106
+ None/bool: Return True if weights are successfully downloaded
107
+ else return None
108
+ """
109
+ if comet_ml is None:
110
+ return
111
+
112
+ if isinstance(opt.weights, str):
113
+ if opt.weights.startswith(COMET_PREFIX):
114
+ api = comet_ml.API()
115
+ resource = urlparse(opt.weights)
116
+ experiment_path = f"{resource.netloc}{resource.path}"
117
+ experiment = api.get(experiment_path)
118
+ download_model_checkpoint(opt, experiment)
119
+ return True
120
+
121
+ return None
122
+
123
+
124
+ def check_comet_resume(opt):
125
+ """Restores run parameters to its original state based on the model checkpoint
126
+ and logged Experiment parameters.
127
+
128
+ Args:
129
+ opt (argparse.Namespace): Command Line arguments passed
130
+ to YOLOv5 training script
131
+
132
+ Returns:
133
+ None/bool: Return True if the run is restored successfully
134
+ else return None
135
+ """
136
+ if comet_ml is None:
137
+ return
138
+
139
+ if isinstance(opt.resume, str):
140
+ if opt.resume.startswith(COMET_PREFIX):
141
+ api = comet_ml.API()
142
+ resource = urlparse(opt.resume)
143
+ experiment_path = f"{resource.netloc}{resource.path}"
144
+ experiment = api.get(experiment_path)
145
+ set_opt_parameters(opt, experiment)
146
+ download_model_checkpoint(opt, experiment)
147
+
148
+ return True
149
+
150
+ return None
utils/loggers/comet/hpo.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import logging
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import comet_ml
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ FILE = Path(__file__).resolve()
13
+ ROOT = FILE.parents[3] # YOLOv5 root directory
14
+ if str(ROOT) not in sys.path:
15
+ sys.path.append(str(ROOT)) # add ROOT to PATH
16
+
17
+ from train import train
18
+ from utils.callbacks import Callbacks
19
+ from utils.general import increment_path
20
+ from utils.torch_utils import select_device
21
+
22
+ # Project Configuration
23
+ config = comet_ml.config.get_config()
24
+ COMET_PROJECT_NAME = config.get_string(os.getenv("COMET_PROJECT_NAME"), "comet.project_name", default="yolov5")
25
+
26
+
27
+ def get_args(known=False):
28
+ parser = argparse.ArgumentParser()
29
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path')
30
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
31
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
32
+ parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path')
33
+ parser.add_argument('--epochs', type=int, default=300, help='total training epochs')
34
+ parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch')
35
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)')
36
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
37
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
38
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
39
+ parser.add_argument('--noval', action='store_true', help='only validate final epoch')
40
+ parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
41
+ parser.add_argument('--noplots', action='store_true', help='save no plot files')
42
+ parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
43
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
44
+ parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
45
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
46
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
47
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
48
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
49
+ parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
50
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
51
+ parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
52
+ parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name')
53
+ parser.add_argument('--name', default='exp', help='save to project/name')
54
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
55
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
56
+ parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
57
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
58
+ parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
59
+ parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
60
+ parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
61
+ parser.add_argument('--seed', type=int, default=0, help='Global training seed')
62
+ parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
63
+
64
+ # Weights & Biases arguments
65
+ parser.add_argument('--entity', default=None, help='W&B: Entity')
66
+ parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='W&B: Upload data, "val" option')
67
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='W&B: Set bounding-box image logging interval')
68
+ parser.add_argument('--artifact_alias', type=str, default='latest', help='W&B: Version of dataset artifact to use')
69
+
70
+ # Comet Arguments
71
+ parser.add_argument("--comet_optimizer_config", type=str, help="Comet: Path to a Comet Optimizer Config File.")
72
+ parser.add_argument("--comet_optimizer_id", type=str, help="Comet: ID of the Comet Optimizer sweep.")
73
+ parser.add_argument("--comet_optimizer_objective", type=str, help="Comet: Set to 'minimize' or 'maximize'.")
74
+ parser.add_argument("--comet_optimizer_metric", type=str, help="Comet: Metric to Optimize.")
75
+ parser.add_argument("--comet_optimizer_workers",
76
+ type=int,
77
+ default=1,
78
+ help="Comet: Number of Parallel Workers to use with the Comet Optimizer.")
79
+
80
+ return parser.parse_known_args()[0] if known else parser.parse_args()
81
+
82
+
83
+ def run(parameters, opt):
84
+ hyp_dict = {k: v for k, v in parameters.items() if k not in ["epochs", "batch_size"]}
85
+
86
+ opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve))
87
+ opt.batch_size = parameters.get("batch_size")
88
+ opt.epochs = parameters.get("epochs")
89
+
90
+ device = select_device(opt.device, batch_size=opt.batch_size)
91
+ train(hyp_dict, opt, device, callbacks=Callbacks())
92
+
93
+
94
+ if __name__ == "__main__":
95
+ opt = get_args(known=True)
96
+
97
+ opt.weights = str(opt.weights)
98
+ opt.cfg = str(opt.cfg)
99
+ opt.data = str(opt.data)
100
+ opt.project = str(opt.project)
101
+
102
+ optimizer_id = os.getenv("COMET_OPTIMIZER_ID")
103
+ if optimizer_id is None:
104
+ with open(opt.comet_optimizer_config) as f:
105
+ optimizer_config = json.load(f)
106
+ optimizer = comet_ml.Optimizer(optimizer_config)
107
+ else:
108
+ optimizer = comet_ml.Optimizer(optimizer_id)
109
+
110
+ opt.comet_optimizer_id = optimizer.id
111
+ status = optimizer.status()
112
+
113
+ opt.comet_optimizer_objective = status["spec"]["objective"]
114
+ opt.comet_optimizer_metric = status["spec"]["metric"]
115
+
116
+ logger.info("COMET INFO: Starting Hyperparameter Sweep")
117
+ for parameter in optimizer.get_parameters():
118
+ run(parameter["parameters"], opt)
utils/loggers/comet/optimizer_config.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "algorithm": "random",
3
+ "parameters": {
4
+ "anchor_t": {
5
+ "type": "discrete",
6
+ "values": [
7
+ 2,
8
+ 8
9
+ ]
10
+ },
11
+ "batch_size": {
12
+ "type": "discrete",
13
+ "values": [
14
+ 16,
15
+ 32,
16
+ 64
17
+ ]
18
+ },
19
+ "box": {
20
+ "type": "discrete",
21
+ "values": [
22
+ 0.02,
23
+ 0.2
24
+ ]
25
+ },
26
+ "cls": {
27
+ "type": "discrete",
28
+ "values": [
29
+ 0.2
30
+ ]
31
+ },
32
+ "cls_pw": {
33
+ "type": "discrete",
34
+ "values": [
35
+ 0.5
36
+ ]
37
+ },
38
+ "copy_paste": {
39
+ "type": "discrete",
40
+ "values": [
41
+ 1
42
+ ]
43
+ },
44
+ "degrees": {
45
+ "type": "discrete",
46
+ "values": [
47
+ 0,
48
+ 45
49
+ ]
50
+ },
51
+ "epochs": {
52
+ "type": "discrete",
53
+ "values": [
54
+ 5
55
+ ]
56
+ },
57
+ "fl_gamma": {
58
+ "type": "discrete",
59
+ "values": [
60
+ 0
61
+ ]
62
+ },
63
+ "fliplr": {
64
+ "type": "discrete",
65
+ "values": [
66
+ 0
67
+ ]
68
+ },
69
+ "flipud": {
70
+ "type": "discrete",
71
+ "values": [
72
+ 0
73
+ ]
74
+ },
75
+ "hsv_h": {
76
+ "type": "discrete",
77
+ "values": [
78
+ 0
79
+ ]
80
+ },
81
+ "hsv_s": {
82
+ "type": "discrete",
83
+ "values": [
84
+ 0
85
+ ]
86
+ },
87
+ "hsv_v": {
88
+ "type": "discrete",
89
+ "values": [
90
+ 0
91
+ ]
92
+ },
93
+ "iou_t": {
94
+ "type": "discrete",
95
+ "values": [
96
+ 0.7
97
+ ]
98
+ },
99
+ "lr0": {
100
+ "type": "discrete",
101
+ "values": [
102
+ 1e-05,
103
+ 0.1
104
+ ]
105
+ },
106
+ "lrf": {
107
+ "type": "discrete",
108
+ "values": [
109
+ 0.01,
110
+ 1
111
+ ]
112
+ },
113
+ "mixup": {
114
+ "type": "discrete",
115
+ "values": [
116
+ 1
117
+ ]
118
+ },
119
+ "momentum": {
120
+ "type": "discrete",
121
+ "values": [
122
+ 0.6
123
+ ]
124
+ },
125
+ "mosaic": {
126
+ "type": "discrete",
127
+ "values": [
128
+ 0
129
+ ]
130
+ },
131
+ "obj": {
132
+ "type": "discrete",
133
+ "values": [
134
+ 0.2
135
+ ]
136
+ },
137
+ "obj_pw": {
138
+ "type": "discrete",
139
+ "values": [
140
+ 0.5
141
+ ]
142
+ },
143
+ "optimizer": {
144
+ "type": "categorical",
145
+ "values": [
146
+ "SGD",
147
+ "Adam",
148
+ "AdamW"
149
+ ]
150
+ },
151
+ "perspective": {
152
+ "type": "discrete",
153
+ "values": [
154
+ 0
155
+ ]
156
+ },
157
+ "scale": {
158
+ "type": "discrete",
159
+ "values": [
160
+ 0
161
+ ]
162
+ },
163
+ "shear": {
164
+ "type": "discrete",
165
+ "values": [
166
+ 0
167
+ ]
168
+ },
169
+ "translate": {
170
+ "type": "discrete",
171
+ "values": [
172
+ 0
173
+ ]
174
+ },
175
+ "warmup_bias_lr": {
176
+ "type": "discrete",
177
+ "values": [
178
+ 0,
179
+ 0.2
180
+ ]
181
+ },
182
+ "warmup_epochs": {
183
+ "type": "discrete",
184
+ "values": [
185
+ 5
186
+ ]
187
+ },
188
+ "warmup_momentum": {
189
+ "type": "discrete",
190
+ "values": [
191
+ 0,
192
+ 0.95
193
+ ]
194
+ },
195
+ "weight_decay": {
196
+ "type": "discrete",
197
+ "values": [
198
+ 0,
199
+ 0.001
200
+ ]
201
+ }
202
+ },
203
+ "spec": {
204
+ "maxCombo": 0,
205
+ "metric": "metrics/mAP_0.5",
206
+ "objective": "maximize"
207
+ },
208
+ "trials": 1
209
+ }