ibrim commited on
Commit
85b913f
1 Parent(s): b40f326

Upload 82 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. utils/__init__.py +75 -0
  2. utils/__pycache__/__init__.cpython-38.pyc +0 -0
  3. utils/__pycache__/augmentations.cpython-38.pyc +0 -0
  4. utils/__pycache__/autoanchor.cpython-38.pyc +0 -0
  5. utils/__pycache__/autobatch.cpython-38.pyc +0 -0
  6. utils/__pycache__/callbacks.cpython-38.pyc +0 -0
  7. utils/__pycache__/dataloaders.cpython-38.pyc +0 -0
  8. utils/__pycache__/downloads.cpython-38.pyc +0 -0
  9. utils/__pycache__/general.cpython-38.pyc +0 -0
  10. utils/__pycache__/lion.cpython-38.pyc +0 -0
  11. utils/__pycache__/loss_tal.cpython-38.pyc +0 -0
  12. utils/__pycache__/metrics.cpython-38.pyc +0 -0
  13. utils/__pycache__/plots.cpython-38.pyc +0 -0
  14. utils/__pycache__/torch_utils.cpython-38.pyc +0 -0
  15. utils/activations.py +98 -0
  16. utils/augmentations.py +395 -0
  17. utils/autoanchor.py +164 -0
  18. utils/autobatch.py +67 -0
  19. utils/callbacks.py +71 -0
  20. utils/dataloaders.py +1217 -0
  21. utils/downloads.py +103 -0
  22. utils/general.py +1135 -0
  23. utils/lion.py +67 -0
  24. utils/loggers/__init__.py +399 -0
  25. utils/loggers/__pycache__/__init__.cpython-38.pyc +0 -0
  26. utils/loggers/clearml/__init__.py +1 -0
  27. utils/loggers/clearml/__pycache__/__init__.cpython-38.pyc +0 -0
  28. utils/loggers/clearml/__pycache__/clearml_utils.cpython-38.pyc +0 -0
  29. utils/loggers/clearml/clearml_utils.py +157 -0
  30. utils/loggers/clearml/hpo.py +84 -0
  31. utils/loggers/comet/__init__.py +508 -0
  32. utils/loggers/comet/__pycache__/__init__.cpython-38.pyc +0 -0
  33. utils/loggers/comet/__pycache__/comet_utils.cpython-38.pyc +0 -0
  34. utils/loggers/comet/comet_utils.py +150 -0
  35. utils/loggers/comet/hpo.py +118 -0
  36. utils/loggers/comet/optimizer_config.json +209 -0
  37. utils/loggers/wandb/__init__.py +1 -0
  38. utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc +0 -0
  39. utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc +0 -0
  40. utils/loggers/wandb/log_dataset.py +27 -0
  41. utils/loggers/wandb/sweep.py +41 -0
  42. utils/loggers/wandb/sweep.yaml +143 -0
  43. utils/loggers/wandb/wandb_utils.py +589 -0
  44. utils/loss.py +363 -0
  45. utils/loss_tal.py +215 -0
  46. utils/loss_tal_dual.py +385 -0
  47. utils/loss_tal_triple.py +282 -0
  48. utils/metrics.py +397 -0
  49. utils/panoptic/__init__.py +1 -0
  50. utils/panoptic/augmentations.py +183 -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/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (2.52 kB). View file
 
utils/__pycache__/augmentations.cpython-38.pyc ADDED
Binary file (13.8 kB). View file
 
utils/__pycache__/autoanchor.cpython-38.pyc ADDED
Binary file (6.47 kB). View file
 
utils/__pycache__/autobatch.cpython-38.pyc ADDED
Binary file (2.51 kB). View file
 
utils/__pycache__/callbacks.cpython-38.pyc ADDED
Binary file (2.62 kB). View file
 
utils/__pycache__/dataloaders.cpython-38.pyc ADDED
Binary file (43.1 kB). View file
 
utils/__pycache__/downloads.cpython-38.pyc ADDED
Binary file (3.94 kB). View file
 
utils/__pycache__/general.cpython-38.pyc ADDED
Binary file (39.2 kB). View file
 
utils/__pycache__/lion.cpython-38.pyc ADDED
Binary file (2.35 kB). View file
 
utils/__pycache__/loss_tal.cpython-38.pyc ADDED
Binary file (7.16 kB). View file
 
utils/__pycache__/metrics.cpython-38.pyc ADDED
Binary file (12.7 kB). View file
 
utils/__pycache__/plots.cpython-38.pyc ADDED
Binary file (21.6 kB). View file
 
utils/__pycache__/torch_utils.cpython-38.pyc ADDED
Binary file (18.3 kB). View file
 
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/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (13.6 kB). View file
 
utils/loggers/clearml/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # init
utils/loggers/clearml/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (180 Bytes). View file
 
utils/loggers/clearml/__pycache__/clearml_utils.cpython-38.pyc ADDED
Binary file (5.61 kB). View file
 
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/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (14.8 kB). View file
 
utils/loggers/comet/__pycache__/comet_utils.cpython-38.pyc ADDED
Binary file (4.21 kB). View file
 
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
+ }
utils/loggers/wandb/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # init
utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (178 Bytes). View file
 
utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc ADDED
Binary file (19.7 kB). View file
 
utils/loggers/wandb/log_dataset.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from wandb_utils import WandbLogger
4
+
5
+ from utils.general import LOGGER
6
+
7
+ WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
8
+
9
+
10
+ def create_dataset_artifact(opt):
11
+ logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused
12
+ if not logger.wandb:
13
+ LOGGER.info("install wandb using `pip install wandb` to log the dataset")
14
+
15
+
16
+ if __name__ == '__main__':
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
19
+ parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
20
+ parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')
21
+ parser.add_argument('--entity', default=None, help='W&B entity')
22
+ parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run')
23
+
24
+ opt = parser.parse_args()
25
+ opt.resume = False # Explicitly disallow resume check for dataset upload job
26
+
27
+ create_dataset_artifact(opt)
utils/loggers/wandb/sweep.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import wandb
5
+
6
+ FILE = Path(__file__).resolve()
7
+ ROOT = FILE.parents[3] # YOLOv5 root directory
8
+ if str(ROOT) not in sys.path:
9
+ sys.path.append(str(ROOT)) # add ROOT to PATH
10
+
11
+ from train import parse_opt, train
12
+ from utils.callbacks import Callbacks
13
+ from utils.general import increment_path
14
+ from utils.torch_utils import select_device
15
+
16
+
17
+ def sweep():
18
+ wandb.init()
19
+ # Get hyp dict from sweep agent. Copy because train() modifies parameters which confused wandb.
20
+ hyp_dict = vars(wandb.config).get("_items").copy()
21
+
22
+ # Workaround: get necessary opt args
23
+ opt = parse_opt(known=True)
24
+ opt.batch_size = hyp_dict.get("batch_size")
25
+ opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve))
26
+ opt.epochs = hyp_dict.get("epochs")
27
+ opt.nosave = True
28
+ opt.data = hyp_dict.get("data")
29
+ opt.weights = str(opt.weights)
30
+ opt.cfg = str(opt.cfg)
31
+ opt.data = str(opt.data)
32
+ opt.hyp = str(opt.hyp)
33
+ opt.project = str(opt.project)
34
+ device = select_device(opt.device, batch_size=opt.batch_size)
35
+
36
+ # train
37
+ train(hyp_dict, opt, device, callbacks=Callbacks())
38
+
39
+
40
+ if __name__ == "__main__":
41
+ sweep()
utils/loggers/wandb/sweep.yaml ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hyperparameters for training
2
+ # To set range-
3
+ # Provide min and max values as:
4
+ # parameter:
5
+ #
6
+ # min: scalar
7
+ # max: scalar
8
+ # OR
9
+ #
10
+ # Set a specific list of search space-
11
+ # parameter:
12
+ # values: [scalar1, scalar2, scalar3...]
13
+ #
14
+ # You can use grid, bayesian and hyperopt search strategy
15
+ # For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration
16
+
17
+ program: utils/loggers/wandb/sweep.py
18
+ method: random
19
+ metric:
20
+ name: metrics/mAP_0.5
21
+ goal: maximize
22
+
23
+ parameters:
24
+ # hyperparameters: set either min, max range or values list
25
+ data:
26
+ value: "data/coco128.yaml"
27
+ batch_size:
28
+ values: [64]
29
+ epochs:
30
+ values: [10]
31
+
32
+ lr0:
33
+ distribution: uniform
34
+ min: 1e-5
35
+ max: 1e-1
36
+ lrf:
37
+ distribution: uniform
38
+ min: 0.01
39
+ max: 1.0
40
+ momentum:
41
+ distribution: uniform
42
+ min: 0.6
43
+ max: 0.98
44
+ weight_decay:
45
+ distribution: uniform
46
+ min: 0.0
47
+ max: 0.001
48
+ warmup_epochs:
49
+ distribution: uniform
50
+ min: 0.0
51
+ max: 5.0
52
+ warmup_momentum:
53
+ distribution: uniform
54
+ min: 0.0
55
+ max: 0.95
56
+ warmup_bias_lr:
57
+ distribution: uniform
58
+ min: 0.0
59
+ max: 0.2
60
+ box:
61
+ distribution: uniform
62
+ min: 0.02
63
+ max: 0.2
64
+ cls:
65
+ distribution: uniform
66
+ min: 0.2
67
+ max: 4.0
68
+ cls_pw:
69
+ distribution: uniform
70
+ min: 0.5
71
+ max: 2.0
72
+ obj:
73
+ distribution: uniform
74
+ min: 0.2
75
+ max: 4.0
76
+ obj_pw:
77
+ distribution: uniform
78
+ min: 0.5
79
+ max: 2.0
80
+ iou_t:
81
+ distribution: uniform
82
+ min: 0.1
83
+ max: 0.7
84
+ anchor_t:
85
+ distribution: uniform
86
+ min: 2.0
87
+ max: 8.0
88
+ fl_gamma:
89
+ distribution: uniform
90
+ min: 0.0
91
+ max: 4.0
92
+ hsv_h:
93
+ distribution: uniform
94
+ min: 0.0
95
+ max: 0.1
96
+ hsv_s:
97
+ distribution: uniform
98
+ min: 0.0
99
+ max: 0.9
100
+ hsv_v:
101
+ distribution: uniform
102
+ min: 0.0
103
+ max: 0.9
104
+ degrees:
105
+ distribution: uniform
106
+ min: 0.0
107
+ max: 45.0
108
+ translate:
109
+ distribution: uniform
110
+ min: 0.0
111
+ max: 0.9
112
+ scale:
113
+ distribution: uniform
114
+ min: 0.0
115
+ max: 0.9
116
+ shear:
117
+ distribution: uniform
118
+ min: 0.0
119
+ max: 10.0
120
+ perspective:
121
+ distribution: uniform
122
+ min: 0.0
123
+ max: 0.001
124
+ flipud:
125
+ distribution: uniform
126
+ min: 0.0
127
+ max: 1.0
128
+ fliplr:
129
+ distribution: uniform
130
+ min: 0.0
131
+ max: 1.0
132
+ mosaic:
133
+ distribution: uniform
134
+ min: 0.0
135
+ max: 1.0
136
+ mixup:
137
+ distribution: uniform
138
+ min: 0.0
139
+ max: 1.0
140
+ copy_paste:
141
+ distribution: uniform
142
+ min: 0.0
143
+ max: 1.0
utils/loggers/wandb/wandb_utils.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities and tools for tracking runs with Weights & Biases."""
2
+
3
+ import logging
4
+ import os
5
+ import sys
6
+ from contextlib import contextmanager
7
+ from pathlib import Path
8
+ from typing import Dict
9
+
10
+ import yaml
11
+ from tqdm import tqdm
12
+
13
+ FILE = Path(__file__).resolve()
14
+ ROOT = FILE.parents[3] # YOLOv5 root directory
15
+ if str(ROOT) not in sys.path:
16
+ sys.path.append(str(ROOT)) # add ROOT to PATH
17
+
18
+ from utils.dataloaders import LoadImagesAndLabels, img2label_paths
19
+ from utils.general import LOGGER, check_dataset, check_file
20
+
21
+ try:
22
+ import wandb
23
+
24
+ assert hasattr(wandb, '__version__') # verify package import not local dir
25
+ except (ImportError, AssertionError):
26
+ wandb = None
27
+
28
+ RANK = int(os.getenv('RANK', -1))
29
+ WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
30
+
31
+
32
+ def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
33
+ return from_string[len(prefix):]
34
+
35
+
36
+ def check_wandb_config_file(data_config_file):
37
+ wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
38
+ if Path(wandb_config).is_file():
39
+ return wandb_config
40
+ return data_config_file
41
+
42
+
43
+ def check_wandb_dataset(data_file):
44
+ is_trainset_wandb_artifact = False
45
+ is_valset_wandb_artifact = False
46
+ if isinstance(data_file, dict):
47
+ # In that case another dataset manager has already processed it and we don't have to
48
+ return data_file
49
+ if check_file(data_file) and data_file.endswith('.yaml'):
50
+ with open(data_file, errors='ignore') as f:
51
+ data_dict = yaml.safe_load(f)
52
+ is_trainset_wandb_artifact = isinstance(data_dict['train'],
53
+ str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX)
54
+ is_valset_wandb_artifact = isinstance(data_dict['val'],
55
+ str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX)
56
+ if is_trainset_wandb_artifact or is_valset_wandb_artifact:
57
+ return data_dict
58
+ else:
59
+ return check_dataset(data_file)
60
+
61
+
62
+ def get_run_info(run_path):
63
+ run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
64
+ run_id = run_path.stem
65
+ project = run_path.parent.stem
66
+ entity = run_path.parent.parent.stem
67
+ model_artifact_name = 'run_' + run_id + '_model'
68
+ return entity, project, run_id, model_artifact_name
69
+
70
+
71
+ def check_wandb_resume(opt):
72
+ process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None
73
+ if isinstance(opt.resume, str):
74
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
75
+ if RANK not in [-1, 0]: # For resuming DDP runs
76
+ entity, project, run_id, model_artifact_name = get_run_info(opt.resume)
77
+ api = wandb.Api()
78
+ artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest')
79
+ modeldir = artifact.download()
80
+ opt.weights = str(Path(modeldir) / "last.pt")
81
+ return True
82
+ return None
83
+
84
+
85
+ def process_wandb_config_ddp_mode(opt):
86
+ with open(check_file(opt.data), errors='ignore') as f:
87
+ data_dict = yaml.safe_load(f) # data dict
88
+ train_dir, val_dir = None, None
89
+ if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
90
+ api = wandb.Api()
91
+ train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
92
+ train_dir = train_artifact.download()
93
+ train_path = Path(train_dir) / 'data/images/'
94
+ data_dict['train'] = str(train_path)
95
+
96
+ if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
97
+ api = wandb.Api()
98
+ val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
99
+ val_dir = val_artifact.download()
100
+ val_path = Path(val_dir) / 'data/images/'
101
+ data_dict['val'] = str(val_path)
102
+ if train_dir or val_dir:
103
+ ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
104
+ with open(ddp_data_path, 'w') as f:
105
+ yaml.safe_dump(data_dict, f)
106
+ opt.data = ddp_data_path
107
+
108
+
109
+ class WandbLogger():
110
+ """Log training runs, datasets, models, and predictions to Weights & Biases.
111
+
112
+ This logger sends information to W&B at wandb.ai. By default, this information
113
+ includes hyperparameters, system configuration and metrics, model metrics,
114
+ and basic data metrics and analyses.
115
+
116
+ By providing additional command line arguments to train.py, datasets,
117
+ models and predictions can also be logged.
118
+
119
+ For more on how this logger is used, see the Weights & Biases documentation:
120
+ https://docs.wandb.com/guides/integrations/yolov5
121
+ """
122
+
123
+ def __init__(self, opt, run_id=None, job_type='Training'):
124
+ """
125
+ - Initialize WandbLogger instance
126
+ - Upload dataset if opt.upload_dataset is True
127
+ - Setup training processes if job_type is 'Training'
128
+
129
+ arguments:
130
+ opt (namespace) -- Commandline arguments for this run
131
+ run_id (str) -- Run ID of W&B run to be resumed
132
+ job_type (str) -- To set the job_type for this run
133
+
134
+ """
135
+ # Temporary-fix
136
+ if opt.upload_dataset:
137
+ opt.upload_dataset = False
138
+ # LOGGER.info("Uploading Dataset functionality is not being supported temporarily due to a bug.")
139
+
140
+ # Pre-training routine --
141
+ self.job_type = job_type
142
+ self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run
143
+ self.val_artifact, self.train_artifact = None, None
144
+ self.train_artifact_path, self.val_artifact_path = None, None
145
+ self.result_artifact = None
146
+ self.val_table, self.result_table = None, None
147
+ self.bbox_media_panel_images = []
148
+ self.val_table_path_map = None
149
+ self.max_imgs_to_log = 16
150
+ self.wandb_artifact_data_dict = None
151
+ self.data_dict = None
152
+ # It's more elegant to stick to 1 wandb.init call,
153
+ # but useful config data is overwritten in the WandbLogger's wandb.init call
154
+ if isinstance(opt.resume, str): # checks resume from artifact
155
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
156
+ entity, project, run_id, model_artifact_name = get_run_info(opt.resume)
157
+ model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
158
+ assert wandb, 'install wandb to resume wandb runs'
159
+ # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
160
+ self.wandb_run = wandb.init(id=run_id,
161
+ project=project,
162
+ entity=entity,
163
+ resume='allow',
164
+ allow_val_change=True)
165
+ opt.resume = model_artifact_name
166
+ elif self.wandb:
167
+ self.wandb_run = wandb.init(config=opt,
168
+ resume="allow",
169
+ project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
170
+ entity=opt.entity,
171
+ name=opt.name if opt.name != 'exp' else None,
172
+ job_type=job_type,
173
+ id=run_id,
174
+ allow_val_change=True) if not wandb.run else wandb.run
175
+ if self.wandb_run:
176
+ if self.job_type == 'Training':
177
+ if opt.upload_dataset:
178
+ if not opt.resume:
179
+ self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt)
180
+
181
+ if isinstance(opt.data, dict):
182
+ # This means another dataset manager has already processed the dataset info (e.g. ClearML)
183
+ # and they will have stored the already processed dict in opt.data
184
+ self.data_dict = opt.data
185
+ elif opt.resume:
186
+ # resume from artifact
187
+ if isinstance(opt.resume, str) and opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
188
+ self.data_dict = dict(self.wandb_run.config.data_dict)
189
+ else: # local resume
190
+ self.data_dict = check_wandb_dataset(opt.data)
191
+ else:
192
+ self.data_dict = check_wandb_dataset(opt.data)
193
+ self.wandb_artifact_data_dict = self.wandb_artifact_data_dict or self.data_dict
194
+
195
+ # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming.
196
+ self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict}, allow_val_change=True)
197
+ self.setup_training(opt)
198
+
199
+ if self.job_type == 'Dataset Creation':
200
+ self.wandb_run.config.update({"upload_dataset": True})
201
+ self.data_dict = self.check_and_upload_dataset(opt)
202
+
203
+ def check_and_upload_dataset(self, opt):
204
+ """
205
+ Check if the dataset format is compatible and upload it as W&B artifact
206
+
207
+ arguments:
208
+ opt (namespace)-- Commandline arguments for current run
209
+
210
+ returns:
211
+ Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links.
212
+ """
213
+ assert wandb, 'Install wandb to upload dataset'
214
+ config_path = self.log_dataset_artifact(opt.data, opt.single_cls,
215
+ 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)
216
+ with open(config_path, errors='ignore') as f:
217
+ wandb_data_dict = yaml.safe_load(f)
218
+ return wandb_data_dict
219
+
220
+ def setup_training(self, opt):
221
+ """
222
+ Setup the necessary processes for training YOLO models:
223
+ - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX
224
+ - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded
225
+ - Setup log_dict, initialize bbox_interval
226
+
227
+ arguments:
228
+ opt (namespace) -- commandline arguments for this run
229
+
230
+ """
231
+ self.log_dict, self.current_epoch = {}, 0
232
+ self.bbox_interval = opt.bbox_interval
233
+ if isinstance(opt.resume, str):
234
+ modeldir, _ = self.download_model_artifact(opt)
235
+ if modeldir:
236
+ self.weights = Path(modeldir) / "last.pt"
237
+ config = self.wandb_run.config
238
+ opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp, opt.imgsz = str(
239
+ self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs,\
240
+ config.hyp, config.imgsz
241
+ data_dict = self.data_dict
242
+ if self.val_artifact is None: # If --upload_dataset is set, use the existing artifact, don't download
243
+ self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(
244
+ data_dict.get('train'), opt.artifact_alias)
245
+ self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(
246
+ data_dict.get('val'), opt.artifact_alias)
247
+
248
+ if self.train_artifact_path is not None:
249
+ train_path = Path(self.train_artifact_path) / 'data/images/'
250
+ data_dict['train'] = str(train_path)
251
+ if self.val_artifact_path is not None:
252
+ val_path = Path(self.val_artifact_path) / 'data/images/'
253
+ data_dict['val'] = str(val_path)
254
+
255
+ if self.val_artifact is not None:
256
+ self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
257
+ columns = ["epoch", "id", "ground truth", "prediction"]
258
+ columns.extend(self.data_dict['names'])
259
+ self.result_table = wandb.Table(columns)
260
+ self.val_table = self.val_artifact.get("val")
261
+ if self.val_table_path_map is None:
262
+ self.map_val_table_path()
263
+ if opt.bbox_interval == -1:
264
+ self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
265
+ if opt.evolve or opt.noplots:
266
+ self.bbox_interval = opt.bbox_interval = opt.epochs + 1 # disable bbox_interval
267
+ train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None
268
+ # Update the the data_dict to point to local artifacts dir
269
+ if train_from_artifact:
270
+ self.data_dict = data_dict
271
+
272
+ def download_dataset_artifact(self, path, alias):
273
+ """
274
+ download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX
275
+
276
+ arguments:
277
+ path -- path of the dataset to be used for training
278
+ alias (str)-- alias of the artifact to be download/used for training
279
+
280
+ returns:
281
+ (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset
282
+ is found otherwise returns (None, None)
283
+ """
284
+ if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
285
+ artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
286
+ dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/"))
287
+ assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
288
+ datadir = dataset_artifact.download()
289
+ return datadir, dataset_artifact
290
+ return None, None
291
+
292
+ def download_model_artifact(self, opt):
293
+ """
294
+ download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX
295
+
296
+ arguments:
297
+ opt (namespace) -- Commandline arguments for this run
298
+ """
299
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
300
+ model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
301
+ assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
302
+ modeldir = model_artifact.download()
303
+ # epochs_trained = model_artifact.metadata.get('epochs_trained')
304
+ total_epochs = model_artifact.metadata.get('total_epochs')
305
+ is_finished = total_epochs is None
306
+ assert not is_finished, 'training is finished, can only resume incomplete runs.'
307
+ return modeldir, model_artifact
308
+ return None, None
309
+
310
+ def log_model(self, path, opt, epoch, fitness_score, best_model=False):
311
+ """
312
+ Log the model checkpoint as W&B artifact
313
+
314
+ arguments:
315
+ path (Path) -- Path of directory containing the checkpoints
316
+ opt (namespace) -- Command line arguments for this run
317
+ epoch (int) -- Current epoch number
318
+ fitness_score (float) -- fitness score for current epoch
319
+ best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.
320
+ """
321
+ model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model',
322
+ type='model',
323
+ metadata={
324
+ 'original_url': str(path),
325
+ 'epochs_trained': epoch + 1,
326
+ 'save period': opt.save_period,
327
+ 'project': opt.project,
328
+ 'total_epochs': opt.epochs,
329
+ 'fitness_score': fitness_score})
330
+ model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
331
+ wandb.log_artifact(model_artifact,
332
+ aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
333
+ LOGGER.info(f"Saving model artifact on epoch {epoch + 1}")
334
+
335
+ def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
336
+ """
337
+ Log the dataset as W&B artifact and return the new data file with W&B links
338
+
339
+ arguments:
340
+ data_file (str) -- the .yaml file with information about the dataset like - path, classes etc.
341
+ single_class (boolean) -- train multi-class data as single-class
342
+ project (str) -- project name. Used to construct the artifact path
343
+ overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new
344
+ file with _wandb postfix. Eg -> data_wandb.yaml
345
+
346
+ returns:
347
+ the new .yaml file with artifact links. it can be used to start training directly from artifacts
348
+ """
349
+ upload_dataset = self.wandb_run.config.upload_dataset
350
+ log_val_only = isinstance(upload_dataset, str) and upload_dataset == 'val'
351
+ self.data_dict = check_dataset(data_file) # parse and check
352
+ data = dict(self.data_dict)
353
+ nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
354
+ names = {k: v for k, v in enumerate(names)} # to index dictionary
355
+
356
+ # log train set
357
+ if not log_val_only:
358
+ self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(data['train'], rect=True, batch_size=1),
359
+ names,
360
+ name='train') if data.get('train') else None
361
+ if data.get('train'):
362
+ data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
363
+
364
+ self.val_artifact = self.create_dataset_table(
365
+ LoadImagesAndLabels(data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None
366
+ if data.get('val'):
367
+ data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
368
+
369
+ path = Path(data_file)
370
+ # create a _wandb.yaml file with artifacts links if both train and test set are logged
371
+ if not log_val_only:
372
+ path = (path.stem if overwrite_config else path.stem + '_wandb') + '.yaml' # updated data.yaml path
373
+ path = ROOT / 'data' / path
374
+ data.pop('download', None)
375
+ data.pop('path', None)
376
+ with open(path, 'w') as f:
377
+ yaml.safe_dump(data, f)
378
+ LOGGER.info(f"Created dataset config file {path}")
379
+
380
+ if self.job_type == 'Training': # builds correct artifact pipeline graph
381
+ if not log_val_only:
382
+ self.wandb_run.log_artifact(
383
+ self.train_artifact) # calling use_artifact downloads the dataset. NOT NEEDED!
384
+ self.wandb_run.use_artifact(self.val_artifact)
385
+ self.val_artifact.wait()
386
+ self.val_table = self.val_artifact.get('val')
387
+ self.map_val_table_path()
388
+ else:
389
+ self.wandb_run.log_artifact(self.train_artifact)
390
+ self.wandb_run.log_artifact(self.val_artifact)
391
+ return path
392
+
393
+ def map_val_table_path(self):
394
+ """
395
+ Map the validation dataset Table like name of file -> it's id in the W&B Table.
396
+ Useful for - referencing artifacts for evaluation.
397
+ """
398
+ self.val_table_path_map = {}
399
+ LOGGER.info("Mapping dataset")
400
+ for i, data in enumerate(tqdm(self.val_table.data)):
401
+ self.val_table_path_map[data[3]] = data[0]
402
+
403
+ def create_dataset_table(self, dataset: LoadImagesAndLabels, class_to_id: Dict[int, str], name: str = 'dataset'):
404
+ """
405
+ Create and return W&B artifact containing W&B Table of the dataset.
406
+
407
+ arguments:
408
+ dataset -- instance of LoadImagesAndLabels class used to iterate over the data to build Table
409
+ class_to_id -- hash map that maps class ids to labels
410
+ name -- name of the artifact
411
+
412
+ returns:
413
+ dataset artifact to be logged or used
414
+ """
415
+ # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
416
+ artifact = wandb.Artifact(name=name, type="dataset")
417
+ img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
418
+ img_files = tqdm(dataset.im_files) if not img_files else img_files
419
+ for img_file in img_files:
420
+ if Path(img_file).is_dir():
421
+ artifact.add_dir(img_file, name='data/images')
422
+ labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
423
+ artifact.add_dir(labels_path, name='data/labels')
424
+ else:
425
+ artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
426
+ label_file = Path(img2label_paths([img_file])[0])
427
+ artifact.add_file(str(label_file), name='data/labels/' +
428
+ label_file.name) if label_file.exists() else None
429
+ table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
430
+ class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
431
+ for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
432
+ box_data, img_classes = [], {}
433
+ for cls, *xywh in labels[:, 1:].tolist():
434
+ cls = int(cls)
435
+ box_data.append({
436
+ "position": {
437
+ "middle": [xywh[0], xywh[1]],
438
+ "width": xywh[2],
439
+ "height": xywh[3]},
440
+ "class_id": cls,
441
+ "box_caption": "%s" % (class_to_id[cls])})
442
+ img_classes[cls] = class_to_id[cls]
443
+ boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
444
+ table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()),
445
+ Path(paths).name)
446
+ artifact.add(table, name)
447
+ return artifact
448
+
449
+ def log_training_progress(self, predn, path, names):
450
+ """
451
+ Build evaluation Table. Uses reference from validation dataset table.
452
+
453
+ arguments:
454
+ predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class]
455
+ path (str): local path of the current evaluation image
456
+ names (dict(int, str)): hash map that maps class ids to labels
457
+ """
458
+ class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
459
+ box_data = []
460
+ avg_conf_per_class = [0] * len(self.data_dict['names'])
461
+ pred_class_count = {}
462
+ for *xyxy, conf, cls in predn.tolist():
463
+ if conf >= 0.25:
464
+ cls = int(cls)
465
+ box_data.append({
466
+ "position": {
467
+ "minX": xyxy[0],
468
+ "minY": xyxy[1],
469
+ "maxX": xyxy[2],
470
+ "maxY": xyxy[3]},
471
+ "class_id": cls,
472
+ "box_caption": f"{names[cls]} {conf:.3f}",
473
+ "scores": {
474
+ "class_score": conf},
475
+ "domain": "pixel"})
476
+ avg_conf_per_class[cls] += conf
477
+
478
+ if cls in pred_class_count:
479
+ pred_class_count[cls] += 1
480
+ else:
481
+ pred_class_count[cls] = 1
482
+
483
+ for pred_class in pred_class_count.keys():
484
+ avg_conf_per_class[pred_class] = avg_conf_per_class[pred_class] / pred_class_count[pred_class]
485
+
486
+ boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
487
+ id = self.val_table_path_map[Path(path).name]
488
+ self.result_table.add_data(self.current_epoch, id, self.val_table.data[id][1],
489
+ wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
490
+ *avg_conf_per_class)
491
+
492
+ def val_one_image(self, pred, predn, path, names, im):
493
+ """
494
+ Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel
495
+
496
+ arguments:
497
+ pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
498
+ predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class]
499
+ path (str): local path of the current evaluation image
500
+ """
501
+ if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact
502
+ self.log_training_progress(predn, path, names)
503
+
504
+ if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0:
505
+ if self.current_epoch % self.bbox_interval == 0:
506
+ box_data = [{
507
+ "position": {
508
+ "minX": xyxy[0],
509
+ "minY": xyxy[1],
510
+ "maxX": xyxy[2],
511
+ "maxY": xyxy[3]},
512
+ "class_id": int(cls),
513
+ "box_caption": f"{names[int(cls)]} {conf:.3f}",
514
+ "scores": {
515
+ "class_score": conf},
516
+ "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
517
+ boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
518
+ self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name))
519
+
520
+ def log(self, log_dict):
521
+ """
522
+ save the metrics to the logging dictionary
523
+
524
+ arguments:
525
+ log_dict (Dict) -- metrics/media to be logged in current step
526
+ """
527
+ if self.wandb_run:
528
+ for key, value in log_dict.items():
529
+ self.log_dict[key] = value
530
+
531
+ def end_epoch(self, best_result=False):
532
+ """
533
+ commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.
534
+
535
+ arguments:
536
+ best_result (boolean): Boolean representing if the result of this evaluation is best or not
537
+ """
538
+ if self.wandb_run:
539
+ with all_logging_disabled():
540
+ if self.bbox_media_panel_images:
541
+ self.log_dict["BoundingBoxDebugger"] = self.bbox_media_panel_images
542
+ try:
543
+ wandb.log(self.log_dict)
544
+ except BaseException as e:
545
+ LOGGER.info(
546
+ f"An error occurred in wandb logger. The training will proceed without interruption. More info\n{e}"
547
+ )
548
+ self.wandb_run.finish()
549
+ self.wandb_run = None
550
+
551
+ self.log_dict = {}
552
+ self.bbox_media_panel_images = []
553
+ if self.result_artifact:
554
+ self.result_artifact.add(self.result_table, 'result')
555
+ wandb.log_artifact(self.result_artifact,
556
+ aliases=[
557
+ 'latest', 'last', 'epoch ' + str(self.current_epoch),
558
+ ('best' if best_result else '')])
559
+
560
+ wandb.log({"evaluation": self.result_table})
561
+ columns = ["epoch", "id", "ground truth", "prediction"]
562
+ columns.extend(self.data_dict['names'])
563
+ self.result_table = wandb.Table(columns)
564
+ self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
565
+
566
+ def finish_run(self):
567
+ """
568
+ Log metrics if any and finish the current W&B run
569
+ """
570
+ if self.wandb_run:
571
+ if self.log_dict:
572
+ with all_logging_disabled():
573
+ wandb.log(self.log_dict)
574
+ wandb.run.finish()
575
+
576
+
577
+ @contextmanager
578
+ def all_logging_disabled(highest_level=logging.CRITICAL):
579
+ """ source - https://gist.github.com/simon-weber/7853144
580
+ A context manager that will prevent any logging messages triggered during the body from being processed.
581
+ :param highest_level: the maximum logging level in use.
582
+ This would only need to be changed if a custom level greater than CRITICAL is defined.
583
+ """
584
+ previous_level = logging.root.manager.disable
585
+ logging.disable(highest_level)
586
+ try:
587
+ yield
588
+ finally:
589
+ logging.disable(previous_level)
utils/loss.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from utils.metrics import bbox_iou
6
+ from utils.torch_utils import de_parallel
7
+
8
+
9
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
10
+ # return positive, negative label smoothing BCE targets
11
+ return 1.0 - 0.5 * eps, 0.5 * eps
12
+
13
+
14
+ class BCEBlurWithLogitsLoss(nn.Module):
15
+ # BCEwithLogitLoss() with reduced missing label effects.
16
+ def __init__(self, alpha=0.05):
17
+ super().__init__()
18
+ self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
19
+ self.alpha = alpha
20
+
21
+ def forward(self, pred, true):
22
+ loss = self.loss_fcn(pred, true)
23
+ pred = torch.sigmoid(pred) # prob from logits
24
+ dx = pred - true # reduce only missing label effects
25
+ # dx = (pred - true).abs() # reduce missing label and false label effects
26
+ alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
27
+ loss *= alpha_factor
28
+ return loss.mean()
29
+
30
+
31
+ class FocalLoss(nn.Module):
32
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
33
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
34
+ super().__init__()
35
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
36
+ self.gamma = gamma
37
+ self.alpha = alpha
38
+ self.reduction = loss_fcn.reduction
39
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
40
+
41
+ def forward(self, pred, true):
42
+ loss = self.loss_fcn(pred, true)
43
+ # p_t = torch.exp(-loss)
44
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
45
+
46
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
47
+ pred_prob = torch.sigmoid(pred) # prob from logits
48
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
49
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
50
+ modulating_factor = (1.0 - p_t) ** self.gamma
51
+ loss *= alpha_factor * modulating_factor
52
+
53
+ if self.reduction == 'mean':
54
+ return loss.mean()
55
+ elif self.reduction == 'sum':
56
+ return loss.sum()
57
+ else: # 'none'
58
+ return loss
59
+
60
+
61
+ class QFocalLoss(nn.Module):
62
+ # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
63
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
64
+ super().__init__()
65
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
66
+ self.gamma = gamma
67
+ self.alpha = alpha
68
+ self.reduction = loss_fcn.reduction
69
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
70
+
71
+ def forward(self, pred, true):
72
+ loss = self.loss_fcn(pred, true)
73
+
74
+ pred_prob = torch.sigmoid(pred) # prob from logits
75
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
76
+ modulating_factor = torch.abs(true - pred_prob) ** self.gamma
77
+ loss *= alpha_factor * modulating_factor
78
+
79
+ if self.reduction == 'mean':
80
+ return loss.mean()
81
+ elif self.reduction == 'sum':
82
+ return loss.sum()
83
+ else: # 'none'
84
+ return loss
85
+
86
+
87
+ class ComputeLoss:
88
+ sort_obj_iou = False
89
+
90
+ # Compute losses
91
+ def __init__(self, model, autobalance=False):
92
+ device = next(model.parameters()).device # get model device
93
+ h = model.hyp # hyperparameters
94
+
95
+ # Define criteria
96
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
97
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
98
+
99
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
100
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
101
+
102
+ # Focal loss
103
+ g = h['fl_gamma'] # focal loss gamma
104
+ if g > 0:
105
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
106
+
107
+ m = de_parallel(model).model[-1] # Detect() module
108
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
109
+ self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
110
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
111
+ self.nc = m.nc # number of classes
112
+ self.nl = m.nl # number of layers
113
+ self.anchors = m.anchors
114
+ self.device = device
115
+
116
+ def __call__(self, p, targets): # predictions, targets
117
+ bs = p[0].shape[0] # batch size
118
+ loss = torch.zeros(3, device=self.device) # [box, obj, cls] losses
119
+ tcls, tbox, indices = self.build_targets(p, targets) # targets
120
+
121
+ # Losses
122
+ for i, pi in enumerate(p): # layer index, layer predictions
123
+ b, gj, gi = indices[i] # image, anchor, gridy, gridx
124
+ tobj = torch.zeros((pi.shape[0], pi.shape[2], pi.shape[3]), dtype=pi.dtype, device=self.device) # tgt obj
125
+
126
+ n_labels = b.shape[0] # number of labels
127
+ if n_labels:
128
+ # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0
129
+ pxy, pwh, _, pcls = pi[b, :, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions
130
+
131
+ # Regression
132
+ # pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
133
+ # pwh = (0.0 + (pwh - 1.09861).sigmoid() * 4) * anchors[i]
134
+ # pwh = (0.33333 + (pwh - 1.09861).sigmoid() * 2.66667) * anchors[i]
135
+ # pwh = (0.25 + (pwh - 1.38629).sigmoid() * 3.75) * anchors[i]
136
+ # pwh = (0.20 + (pwh - 1.60944).sigmoid() * 4.8) * anchors[i]
137
+ # pwh = (0.16667 + (pwh - 1.79175).sigmoid() * 5.83333) * anchors[i]
138
+ pxy = pxy.sigmoid() * 1.6 - 0.3
139
+ pwh = (0.2 + pwh.sigmoid() * 4.8) * self.anchors[i]
140
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
141
+ iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
142
+ loss[0] += (1.0 - iou).mean() # box loss
143
+
144
+ # Objectness
145
+ iou = iou.detach().clamp(0).type(tobj.dtype)
146
+ if self.sort_obj_iou:
147
+ j = iou.argsort()
148
+ b, gj, gi, iou = b[j], gj[j], gi[j], iou[j]
149
+ if self.gr < 1:
150
+ iou = (1.0 - self.gr) + self.gr * iou
151
+ tobj[b, gj, gi] = iou # iou ratio
152
+
153
+ # Classification
154
+ if self.nc > 1: # cls loss (only if multiple classes)
155
+ t = torch.full_like(pcls, self.cn, device=self.device) # targets
156
+ t[range(n_labels), tcls[i]] = self.cp
157
+ loss[2] += self.BCEcls(pcls, t) # cls loss
158
+
159
+ obji = self.BCEobj(pi[:, 4], tobj)
160
+ loss[1] += obji * self.balance[i] # obj loss
161
+ if self.autobalance:
162
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
163
+
164
+ if self.autobalance:
165
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
166
+ loss[0] *= self.hyp['box']
167
+ loss[1] *= self.hyp['obj']
168
+ loss[2] *= self.hyp['cls']
169
+ return loss.sum() * bs, loss.detach() # [box, obj, cls] losses
170
+
171
+ def build_targets(self, p, targets):
172
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
173
+ nt = targets.shape[0] # number of anchors, targets
174
+ tcls, tbox, indices = [], [], []
175
+ gain = torch.ones(6, device=self.device) # normalized to gridspace gain
176
+
177
+ g = 0.3 # bias
178
+ off = torch.tensor(
179
+ [
180
+ [0, 0],
181
+ [1, 0],
182
+ [0, 1],
183
+ [-1, 0],
184
+ [0, -1], # j,k,l,m
185
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
186
+ ],
187
+ device=self.device).float() * g # offsets
188
+
189
+ for i in range(self.nl):
190
+ shape = p[i].shape
191
+ gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
192
+
193
+ # Match targets to anchors
194
+ t = targets * gain # shape(3,n,7)
195
+ if nt:
196
+ # Matches
197
+ r = t[..., 4:6] / self.anchors[i] # wh ratio
198
+ j = torch.max(r, 1 / r).max(1)[0] < self.hyp['anchor_t'] # compare
199
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
200
+ t = t[j] # filter
201
+
202
+ # Offsets
203
+ gxy = t[:, 2:4] # grid xy
204
+ gxi = gain[[2, 3]] - gxy # inverse
205
+ j, k = ((gxy % 1 < g) & (gxy > 1)).T
206
+ l, m = ((gxi % 1 < g) & (gxi > 1)).T
207
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
208
+ t = t.repeat((5, 1, 1))[j]
209
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
210
+ else:
211
+ t = targets[0]
212
+ offsets = 0
213
+
214
+ # Define
215
+ bc, gxy, gwh = t.chunk(3, 1) # (image, class), grid xy, grid wh
216
+ b, c = bc.long().T # image, class
217
+ gij = (gxy - offsets).long()
218
+ gi, gj = gij.T # grid indices
219
+
220
+ # Append
221
+ indices.append((b, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, grid_y, grid_x indices
222
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
223
+ tcls.append(c) # class
224
+
225
+ return tcls, tbox, indices
226
+
227
+
228
+ class ComputeLoss_NEW:
229
+ sort_obj_iou = False
230
+
231
+ # Compute losses
232
+ def __init__(self, model, autobalance=False):
233
+ device = next(model.parameters()).device # get model device
234
+ h = model.hyp # hyperparameters
235
+
236
+ # Define criteria
237
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
238
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
239
+
240
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
241
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
242
+
243
+ # Focal loss
244
+ g = h['fl_gamma'] # focal loss gamma
245
+ if g > 0:
246
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
247
+
248
+ m = de_parallel(model).model[-1] # Detect() module
249
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
250
+ self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
251
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
252
+ self.nc = m.nc # number of classes
253
+ self.nl = m.nl # number of layers
254
+ self.anchors = m.anchors
255
+ self.device = device
256
+ self.BCE_base = nn.BCEWithLogitsLoss(reduction='none')
257
+
258
+ def __call__(self, p, targets): # predictions, targets
259
+ tcls, tbox, indices = self.build_targets(p, targets) # targets
260
+ bs = p[0].shape[0] # batch size
261
+ n_labels = targets.shape[0] # number of labels
262
+ loss = torch.zeros(3, device=self.device) # [box, obj, cls] losses
263
+
264
+ # Compute all losses
265
+ all_loss = []
266
+ for i, pi in enumerate(p): # layer index, layer predictions
267
+ b, gj, gi = indices[i] # image, anchor, gridy, gridx
268
+ if n_labels:
269
+ pxy, pwh, pobj, pcls = pi[b, :, gj, gi].split((2, 2, 1, self.nc), 2) # target-subset of predictions
270
+
271
+ # Regression
272
+ pbox = torch.cat((pxy.sigmoid() * 1.6 - 0.3, (0.2 + pwh.sigmoid() * 4.8) * self.anchors[i]), 2)
273
+ iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(predicted_box, target_box)
274
+ obj_target = iou.detach().clamp(0).type(pi.dtype) # objectness targets
275
+
276
+ all_loss.append([(1.0 - iou) * self.hyp['box'],
277
+ self.BCE_base(pobj.squeeze(), torch.ones_like(obj_target)) * self.hyp['obj'],
278
+ self.BCE_base(pcls, F.one_hot(tcls[i], self.nc).float()).mean(2) * self.hyp['cls'],
279
+ obj_target,
280
+ tbox[i][..., 2] > 0.0]) # valid
281
+
282
+ # Lowest 3 losses per label
283
+ n_assign = 4 # top n matches
284
+ cat_loss = [torch.cat(x, 1) for x in zip(*all_loss)]
285
+ ij = torch.zeros_like(cat_loss[0]).bool() # top 3 mask
286
+ sum_loss = cat_loss[0] + cat_loss[2]
287
+ for col in torch.argsort(sum_loss, dim=1).T[:n_assign]:
288
+ # ij[range(n_labels), col] = True
289
+ ij[range(n_labels), col] = cat_loss[4][range(n_labels), col]
290
+ loss[0] = cat_loss[0][ij].mean() * self.nl # box loss
291
+ loss[2] = cat_loss[2][ij].mean() * self.nl # cls loss
292
+
293
+ # Obj loss
294
+ for i, (h, pi) in enumerate(zip(ij.chunk(self.nl, 1), p)): # layer index, layer predictions
295
+ b, gj, gi = indices[i] # image, anchor, gridy, gridx
296
+ tobj = torch.zeros((pi.shape[0], pi.shape[2], pi.shape[3]), dtype=pi.dtype, device=self.device) # obj
297
+ if n_labels: # if any labels
298
+ tobj[b[h], gj[h], gi[h]] = all_loss[i][3][h]
299
+ loss[1] += self.BCEobj(pi[:, 4], tobj) * (self.balance[i] * self.hyp['obj'])
300
+
301
+ return loss.sum() * bs, loss.detach() # [box, obj, cls] losses
302
+
303
+ def build_targets(self, p, targets):
304
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
305
+ nt = targets.shape[0] # number of anchors, targets
306
+ tcls, tbox, indices = [], [], []
307
+ gain = torch.ones(6, device=self.device) # normalized to gridspace gain
308
+
309
+ g = 0.3 # bias
310
+ off = torch.tensor(
311
+ [
312
+ [0, 0],
313
+ [1, 0],
314
+ [0, 1],
315
+ [-1, 0],
316
+ [0, -1], # j,k,l,m
317
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
318
+ ],
319
+ device=self.device).float() # offsets
320
+
321
+ for i in range(self.nl):
322
+ shape = p[i].shape
323
+ gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
324
+
325
+ # Match targets to anchors
326
+ t = targets * gain # shape(3,n,7)
327
+ if nt:
328
+ # # Matches
329
+ r = t[..., 4:6] / self.anchors[i] # wh ratio
330
+ a = torch.max(r, 1 / r).max(1)[0] < self.hyp['anchor_t'] # compare
331
+ # a = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
332
+ # t = t[a] # filter
333
+
334
+ # # Offsets
335
+ gxy = t[:, 2:4] # grid xy
336
+ gxi = gain[[2, 3]] - gxy # inverse
337
+ j, k = ((gxy % 1 < g) & (gxy > 1)).T
338
+ l, m = ((gxi % 1 < g) & (gxi > 1)).T
339
+ j = torch.stack((torch.ones_like(j), j, k, l, m)) & a
340
+ t = t.repeat((5, 1, 1))
341
+ offsets = torch.zeros_like(gxy)[None] + off[:, None]
342
+ t[..., 4:6][~j] = 0.0 # move unsuitable targets far away
343
+ else:
344
+ t = targets[0]
345
+ offsets = 0
346
+
347
+ # Define
348
+ bc, gxy, gwh = t.chunk(3, 2) # (image, class), grid xy, grid wh
349
+ b, c = bc.long().transpose(0, 2).contiguous() # image, class
350
+ gij = (gxy - offsets).long()
351
+ gi, gj = gij.transpose(0, 2).contiguous() # grid indices
352
+
353
+ # Append
354
+ indices.append((b, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, grid_y, grid_x indices
355
+ tbox.append(torch.cat((gxy - gij, gwh), 2).permute(1, 0, 2).contiguous()) # box
356
+ tcls.append(c) # class
357
+
358
+ # # Unique
359
+ # n1 = torch.cat((b.view(-1, 1), tbox[i].view(-1, 4)), 1).shape[0]
360
+ # n2 = tbox[i].view(-1, 4).unique(dim=0).shape[0]
361
+ # print(f'targets-unique {n1}-{n2} diff={n1-n2}')
362
+
363
+ return tcls, tbox, indices
utils/loss_tal.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from utils.general import xywh2xyxy
8
+ from utils.metrics import bbox_iou
9
+ from utils.tal.anchor_generator import dist2bbox, make_anchors, bbox2dist
10
+ from utils.tal.assigner import TaskAlignedAssigner
11
+ from utils.torch_utils import de_parallel
12
+
13
+
14
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
15
+ # return positive, negative label smoothing BCE targets
16
+ return 1.0 - 0.5 * eps, 0.5 * eps
17
+
18
+
19
+ class VarifocalLoss(nn.Module):
20
+ # Varifocal loss by Zhang et al. https://arxiv.org/abs/2008.13367
21
+ def __init__(self):
22
+ super().__init__()
23
+
24
+ def forward(self, pred_score, gt_score, label, alpha=0.75, gamma=2.0):
25
+ weight = alpha * pred_score.sigmoid().pow(gamma) * (1 - label) + gt_score * label
26
+ with torch.cuda.amp.autocast(enabled=False):
27
+ loss = (F.binary_cross_entropy_with_logits(pred_score.float(), gt_score.float(),
28
+ reduction="none") * weight).sum()
29
+ return loss
30
+
31
+
32
+ class FocalLoss(nn.Module):
33
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
34
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
35
+ super().__init__()
36
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
37
+ self.gamma = gamma
38
+ self.alpha = alpha
39
+ self.reduction = loss_fcn.reduction
40
+ self.loss_fcn.reduction = "none" # required to apply FL to each element
41
+
42
+ def forward(self, pred, true):
43
+ loss = self.loss_fcn(pred, true)
44
+ # p_t = torch.exp(-loss)
45
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
46
+
47
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
48
+ pred_prob = torch.sigmoid(pred) # prob from logits
49
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
50
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
51
+ modulating_factor = (1.0 - p_t) ** self.gamma
52
+ loss *= alpha_factor * modulating_factor
53
+
54
+ if self.reduction == "mean":
55
+ return loss.mean()
56
+ elif self.reduction == "sum":
57
+ return loss.sum()
58
+ else: # 'none'
59
+ return loss
60
+
61
+
62
+ class BboxLoss(nn.Module):
63
+ def __init__(self, reg_max, use_dfl=False):
64
+ super().__init__()
65
+ self.reg_max = reg_max
66
+ self.use_dfl = use_dfl
67
+
68
+ def forward(self, pred_dist, pred_bboxes, anchor_points, target_bboxes, target_scores, target_scores_sum, fg_mask):
69
+ # iou loss
70
+ bbox_mask = fg_mask.unsqueeze(-1).repeat([1, 1, 4]) # (b, h*w, 4)
71
+ pred_bboxes_pos = torch.masked_select(pred_bboxes, bbox_mask).view(-1, 4)
72
+ target_bboxes_pos = torch.masked_select(target_bboxes, bbox_mask).view(-1, 4)
73
+ bbox_weight = torch.masked_select(target_scores.sum(-1), fg_mask).unsqueeze(-1)
74
+
75
+ iou = bbox_iou(pred_bboxes_pos, target_bboxes_pos, xywh=False, CIoU=True)
76
+ loss_iou = 1.0 - iou
77
+
78
+ loss_iou *= bbox_weight
79
+ loss_iou = loss_iou.sum() / target_scores_sum
80
+
81
+ # dfl loss
82
+ if self.use_dfl:
83
+ dist_mask = fg_mask.unsqueeze(-1).repeat([1, 1, (self.reg_max + 1) * 4])
84
+ pred_dist_pos = torch.masked_select(pred_dist, dist_mask).view(-1, 4, self.reg_max + 1)
85
+ target_ltrb = bbox2dist(anchor_points, target_bboxes, self.reg_max)
86
+ target_ltrb_pos = torch.masked_select(target_ltrb, bbox_mask).view(-1, 4)
87
+ loss_dfl = self._df_loss(pred_dist_pos, target_ltrb_pos) * bbox_weight
88
+ loss_dfl = loss_dfl.sum() / target_scores_sum
89
+ else:
90
+ loss_dfl = torch.tensor(0.0).to(pred_dist.device)
91
+
92
+ return loss_iou, loss_dfl, iou
93
+
94
+ def _df_loss(self, pred_dist, target):
95
+ target_left = target.to(torch.long)
96
+ target_right = target_left + 1
97
+ weight_left = target_right.to(torch.float) - target
98
+ weight_right = 1 - weight_left
99
+ loss_left = F.cross_entropy(pred_dist.view(-1, self.reg_max + 1), target_left.view(-1), reduction="none").view(
100
+ target_left.shape) * weight_left
101
+ loss_right = F.cross_entropy(pred_dist.view(-1, self.reg_max + 1), target_right.view(-1),
102
+ reduction="none").view(target_left.shape) * weight_right
103
+ return (loss_left + loss_right).mean(-1, keepdim=True)
104
+
105
+
106
+ class ComputeLoss:
107
+ # Compute losses
108
+ def __init__(self, model, use_dfl=True):
109
+ device = next(model.parameters()).device # get model device
110
+ h = model.hyp # hyperparameters
111
+
112
+ # Define criteria
113
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device), reduction='none')
114
+
115
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
116
+ self.cp, self.cn = smooth_BCE(eps=h.get("label_smoothing", 0.0)) # positive, negative BCE targets
117
+
118
+ # Focal loss
119
+ g = h["fl_gamma"] # focal loss gamma
120
+ if g > 0:
121
+ BCEcls = FocalLoss(BCEcls, g)
122
+
123
+ m = de_parallel(model).model[-1] # Detect() module
124
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
125
+ self.BCEcls = BCEcls
126
+ self.hyp = h
127
+ self.stride = m.stride # model strides
128
+ self.nc = m.nc # number of classes
129
+ self.nl = m.nl # number of layers
130
+ self.no = m.no
131
+ self.reg_max = m.reg_max
132
+ self.device = device
133
+
134
+ self.assigner = TaskAlignedAssigner(topk=int(os.getenv('YOLOM', 10)),
135
+ num_classes=self.nc,
136
+ alpha=float(os.getenv('YOLOA', 0.5)),
137
+ beta=float(os.getenv('YOLOB', 6.0)))
138
+ self.bbox_loss = BboxLoss(m.reg_max - 1, use_dfl=use_dfl).to(device)
139
+ self.proj = torch.arange(m.reg_max).float().to(device) # / 120.0
140
+ self.use_dfl = use_dfl
141
+
142
+ def preprocess(self, targets, batch_size, scale_tensor):
143
+ if targets.shape[0] == 0:
144
+ out = torch.zeros(batch_size, 0, 5, device=self.device)
145
+ else:
146
+ i = targets[:, 0] # image index
147
+ _, counts = i.unique(return_counts=True)
148
+ out = torch.zeros(batch_size, counts.max(), 5, device=self.device)
149
+ for j in range(batch_size):
150
+ matches = i == j
151
+ n = matches.sum()
152
+ if n:
153
+ out[j, :n] = targets[matches, 1:]
154
+ out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))
155
+ return out
156
+
157
+ def bbox_decode(self, anchor_points, pred_dist):
158
+ if self.use_dfl:
159
+ b, a, c = pred_dist.shape # batch, anchors, channels
160
+ pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
161
+ # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))
162
+ # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)
163
+ return dist2bbox(pred_dist, anchor_points, xywh=False)
164
+
165
+ def __call__(self, p, targets, img=None, epoch=0):
166
+ loss = torch.zeros(3, device=self.device) # box, cls, dfl
167
+ feats = p[1] if isinstance(p, tuple) else p
168
+ pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(
169
+ (self.reg_max * 4, self.nc), 1)
170
+ pred_scores = pred_scores.permute(0, 2, 1).contiguous()
171
+ pred_distri = pred_distri.permute(0, 2, 1).contiguous()
172
+
173
+ dtype = pred_scores.dtype
174
+ batch_size, grid_size = pred_scores.shape[:2]
175
+ imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0] # image size (h,w)
176
+ anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)
177
+
178
+ # targets
179
+ targets = self.preprocess(targets, batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])
180
+ gt_labels, gt_bboxes = targets.split((1, 4), 2) # cls, xyxy
181
+ mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)
182
+
183
+ # pboxes
184
+ pred_bboxes = self.bbox_decode(anchor_points, pred_distri) # xyxy, (b, h*w, 4)
185
+
186
+ target_labels, target_bboxes, target_scores, fg_mask = self.assigner(
187
+ pred_scores.detach().sigmoid(),
188
+ (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),
189
+ anchor_points * stride_tensor,
190
+ gt_labels,
191
+ gt_bboxes,
192
+ mask_gt)
193
+
194
+ target_bboxes /= stride_tensor
195
+ target_scores_sum = max(target_scores.sum(), 1)
196
+
197
+ # cls loss
198
+ # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum # VFL way
199
+ loss[1] = self.BCEcls(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum # BCE
200
+
201
+ # bbox loss
202
+ if fg_mask.sum():
203
+ loss[0], loss[2], iou = self.bbox_loss(pred_distri,
204
+ pred_bboxes,
205
+ anchor_points,
206
+ target_bboxes,
207
+ target_scores,
208
+ target_scores_sum,
209
+ fg_mask)
210
+
211
+ loss[0] *= 7.5 # box gain
212
+ loss[1] *= 0.5 # cls gain
213
+ loss[2] *= 1.5 # dfl gain
214
+
215
+ return loss.sum() * batch_size, loss.detach() # loss(box, cls, dfl)
utils/loss_tal_dual.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from utils.general import xywh2xyxy
8
+ from utils.metrics import bbox_iou
9
+ from utils.tal.anchor_generator import dist2bbox, make_anchors, bbox2dist
10
+ from utils.tal.assigner import TaskAlignedAssigner
11
+ from utils.torch_utils import de_parallel
12
+
13
+
14
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
15
+ # return positive, negative label smoothing BCE targets
16
+ return 1.0 - 0.5 * eps, 0.5 * eps
17
+
18
+
19
+ class VarifocalLoss(nn.Module):
20
+ # Varifocal loss by Zhang et al. https://arxiv.org/abs/2008.13367
21
+ def __init__(self):
22
+ super().__init__()
23
+
24
+ def forward(self, pred_score, gt_score, label, alpha=0.75, gamma=2.0):
25
+ weight = alpha * pred_score.sigmoid().pow(gamma) * (1 - label) + gt_score * label
26
+ with torch.cuda.amp.autocast(enabled=False):
27
+ loss = (F.binary_cross_entropy_with_logits(pred_score.float(), gt_score.float(),
28
+ reduction="none") * weight).sum()
29
+ return loss
30
+
31
+
32
+ class FocalLoss(nn.Module):
33
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
34
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
35
+ super().__init__()
36
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
37
+ self.gamma = gamma
38
+ self.alpha = alpha
39
+ self.reduction = loss_fcn.reduction
40
+ self.loss_fcn.reduction = "none" # required to apply FL to each element
41
+
42
+ def forward(self, pred, true):
43
+ loss = self.loss_fcn(pred, true)
44
+ # p_t = torch.exp(-loss)
45
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
46
+
47
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
48
+ pred_prob = torch.sigmoid(pred) # prob from logits
49
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
50
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
51
+ modulating_factor = (1.0 - p_t) ** self.gamma
52
+ loss *= alpha_factor * modulating_factor
53
+
54
+ if self.reduction == "mean":
55
+ return loss.mean()
56
+ elif self.reduction == "sum":
57
+ return loss.sum()
58
+ else: # 'none'
59
+ return loss
60
+
61
+
62
+ class BboxLoss(nn.Module):
63
+ def __init__(self, reg_max, use_dfl=False):
64
+ super().__init__()
65
+ self.reg_max = reg_max
66
+ self.use_dfl = use_dfl
67
+
68
+ def forward(self, pred_dist, pred_bboxes, anchor_points, target_bboxes, target_scores, target_scores_sum, fg_mask):
69
+ # iou loss
70
+ bbox_mask = fg_mask.unsqueeze(-1).repeat([1, 1, 4]) # (b, h*w, 4)
71
+ pred_bboxes_pos = torch.masked_select(pred_bboxes, bbox_mask).view(-1, 4)
72
+ target_bboxes_pos = torch.masked_select(target_bboxes, bbox_mask).view(-1, 4)
73
+ bbox_weight = torch.masked_select(target_scores.sum(-1), fg_mask).unsqueeze(-1)
74
+
75
+ iou = bbox_iou(pred_bboxes_pos, target_bboxes_pos, xywh=False, CIoU=True)
76
+ loss_iou = 1.0 - iou
77
+
78
+ loss_iou *= bbox_weight
79
+ loss_iou = loss_iou.sum() / target_scores_sum
80
+
81
+ # dfl loss
82
+ if self.use_dfl:
83
+ dist_mask = fg_mask.unsqueeze(-1).repeat([1, 1, (self.reg_max + 1) * 4])
84
+ pred_dist_pos = torch.masked_select(pred_dist, dist_mask).view(-1, 4, self.reg_max + 1)
85
+ target_ltrb = bbox2dist(anchor_points, target_bboxes, self.reg_max)
86
+ target_ltrb_pos = torch.masked_select(target_ltrb, bbox_mask).view(-1, 4)
87
+ loss_dfl = self._df_loss(pred_dist_pos, target_ltrb_pos) * bbox_weight
88
+ loss_dfl = loss_dfl.sum() / target_scores_sum
89
+ else:
90
+ loss_dfl = torch.tensor(0.0).to(pred_dist.device)
91
+
92
+ return loss_iou, loss_dfl, iou
93
+
94
+ def _df_loss(self, pred_dist, target):
95
+ target_left = target.to(torch.long)
96
+ target_right = target_left + 1
97
+ weight_left = target_right.to(torch.float) - target
98
+ weight_right = 1 - weight_left
99
+ loss_left = F.cross_entropy(pred_dist.view(-1, self.reg_max + 1), target_left.view(-1), reduction="none").view(
100
+ target_left.shape) * weight_left
101
+ loss_right = F.cross_entropy(pred_dist.view(-1, self.reg_max + 1), target_right.view(-1),
102
+ reduction="none").view(target_left.shape) * weight_right
103
+ return (loss_left + loss_right).mean(-1, keepdim=True)
104
+
105
+
106
+ class ComputeLoss:
107
+ # Compute losses
108
+ def __init__(self, model, use_dfl=True):
109
+ device = next(model.parameters()).device # get model device
110
+ h = model.hyp # hyperparameters
111
+
112
+ # Define criteria
113
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device), reduction='none')
114
+
115
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
116
+ self.cp, self.cn = smooth_BCE(eps=h.get("label_smoothing", 0.0)) # positive, negative BCE targets
117
+
118
+ # Focal loss
119
+ g = h["fl_gamma"] # focal loss gamma
120
+ if g > 0:
121
+ BCEcls = FocalLoss(BCEcls, g)
122
+
123
+ m = de_parallel(model).model[-1] # Detect() module
124
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
125
+ self.BCEcls = BCEcls
126
+ self.hyp = h
127
+ self.stride = m.stride # model strides
128
+ self.nc = m.nc # number of classes
129
+ self.nl = m.nl # number of layers
130
+ self.no = m.no
131
+ self.reg_max = m.reg_max
132
+ self.device = device
133
+
134
+ self.assigner = TaskAlignedAssigner(topk=int(os.getenv('YOLOM', 10)),
135
+ num_classes=self.nc,
136
+ alpha=float(os.getenv('YOLOA', 0.5)),
137
+ beta=float(os.getenv('YOLOB', 6.0)))
138
+ self.assigner2 = TaskAlignedAssigner(topk=int(os.getenv('YOLOM', 10)),
139
+ num_classes=self.nc,
140
+ alpha=float(os.getenv('YOLOA', 0.5)),
141
+ beta=float(os.getenv('YOLOB', 6.0)))
142
+ self.bbox_loss = BboxLoss(m.reg_max - 1, use_dfl=use_dfl).to(device)
143
+ self.bbox_loss2 = BboxLoss(m.reg_max - 1, use_dfl=use_dfl).to(device)
144
+ self.proj = torch.arange(m.reg_max).float().to(device) # / 120.0
145
+ self.use_dfl = use_dfl
146
+
147
+ def preprocess(self, targets, batch_size, scale_tensor):
148
+ if targets.shape[0] == 0:
149
+ out = torch.zeros(batch_size, 0, 5, device=self.device)
150
+ else:
151
+ i = targets[:, 0] # image index
152
+ _, counts = i.unique(return_counts=True)
153
+ out = torch.zeros(batch_size, counts.max(), 5, device=self.device)
154
+ for j in range(batch_size):
155
+ matches = i == j
156
+ n = matches.sum()
157
+ if n:
158
+ out[j, :n] = targets[matches, 1:]
159
+ out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))
160
+ return out
161
+
162
+ def bbox_decode(self, anchor_points, pred_dist):
163
+ if self.use_dfl:
164
+ b, a, c = pred_dist.shape # batch, anchors, channels
165
+ pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
166
+ # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))
167
+ # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)
168
+ return dist2bbox(pred_dist, anchor_points, xywh=False)
169
+
170
+ def __call__(self, p, targets, img=None, epoch=0):
171
+ loss = torch.zeros(3, device=self.device) # box, cls, dfl
172
+ feats = p[1][0] if isinstance(p, tuple) else p[0]
173
+ feats2 = p[1][1] if isinstance(p, tuple) else p[1]
174
+
175
+ pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(
176
+ (self.reg_max * 4, self.nc), 1)
177
+ pred_scores = pred_scores.permute(0, 2, 1).contiguous()
178
+ pred_distri = pred_distri.permute(0, 2, 1).contiguous()
179
+
180
+ pred_distri2, pred_scores2 = torch.cat([xi.view(feats2[0].shape[0], self.no, -1) for xi in feats2], 2).split(
181
+ (self.reg_max * 4, self.nc), 1)
182
+ pred_scores2 = pred_scores2.permute(0, 2, 1).contiguous()
183
+ pred_distri2 = pred_distri2.permute(0, 2, 1).contiguous()
184
+
185
+ dtype = pred_scores.dtype
186
+ batch_size, grid_size = pred_scores.shape[:2]
187
+ imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0] # image size (h,w)
188
+ anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)
189
+
190
+ # targets
191
+ targets = self.preprocess(targets, batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])
192
+ gt_labels, gt_bboxes = targets.split((1, 4), 2) # cls, xyxy
193
+ mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)
194
+
195
+ # pboxes
196
+ pred_bboxes = self.bbox_decode(anchor_points, pred_distri) # xyxy, (b, h*w, 4)
197
+ pred_bboxes2 = self.bbox_decode(anchor_points, pred_distri2) # xyxy, (b, h*w, 4)
198
+
199
+ target_labels, target_bboxes, target_scores, fg_mask = self.assigner(
200
+ pred_scores.detach().sigmoid(),
201
+ (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),
202
+ anchor_points * stride_tensor,
203
+ gt_labels,
204
+ gt_bboxes,
205
+ mask_gt)
206
+ target_labels2, target_bboxes2, target_scores2, fg_mask2 = self.assigner2(
207
+ pred_scores2.detach().sigmoid(),
208
+ (pred_bboxes2.detach() * stride_tensor).type(gt_bboxes.dtype),
209
+ anchor_points * stride_tensor,
210
+ gt_labels,
211
+ gt_bboxes,
212
+ mask_gt)
213
+
214
+ target_bboxes /= stride_tensor
215
+ target_scores_sum = max(target_scores.sum(), 1)
216
+ target_bboxes2 /= stride_tensor
217
+ target_scores_sum2 = max(target_scores2.sum(), 1)
218
+
219
+ # cls loss
220
+ # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum # VFL way
221
+ loss[1] = self.BCEcls(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum # BCE
222
+ loss[1] *= 0.25
223
+ loss[1] += self.BCEcls(pred_scores2, target_scores2.to(dtype)).sum() / target_scores_sum2 # BCE
224
+
225
+ # bbox loss
226
+ if fg_mask.sum():
227
+ loss[0], loss[2], iou = self.bbox_loss(pred_distri,
228
+ pred_bboxes,
229
+ anchor_points,
230
+ target_bboxes,
231
+ target_scores,
232
+ target_scores_sum,
233
+ fg_mask)
234
+ loss[0] *= 0.25
235
+ loss[2] *= 0.25
236
+ if fg_mask2.sum():
237
+ loss0_, loss2_, iou2 = self.bbox_loss2(pred_distri2,
238
+ pred_bboxes2,
239
+ anchor_points,
240
+ target_bboxes2,
241
+ target_scores2,
242
+ target_scores_sum2,
243
+ fg_mask2)
244
+ loss[0] += loss0_
245
+ loss[2] += loss2_
246
+
247
+ loss[0] *= 7.5 # box gain
248
+ loss[1] *= 0.5 # cls gain
249
+ loss[2] *= 1.5 # dfl gain
250
+
251
+ return loss.sum() * batch_size, loss.detach() # loss(box, cls, dfl)
252
+
253
+
254
+ class ComputeLossLH:
255
+ # Compute losses
256
+ def __init__(self, model, use_dfl=True):
257
+ device = next(model.parameters()).device # get model device
258
+ h = model.hyp # hyperparameters
259
+
260
+ # Define criteria
261
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device), reduction='none')
262
+
263
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
264
+ self.cp, self.cn = smooth_BCE(eps=h.get("label_smoothing", 0.0)) # positive, negative BCE targets
265
+
266
+ # Focal loss
267
+ g = h["fl_gamma"] # focal loss gamma
268
+ if g > 0:
269
+ BCEcls = FocalLoss(BCEcls, g)
270
+
271
+ m = de_parallel(model).model[-1] # Detect() module
272
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
273
+ self.BCEcls = BCEcls
274
+ self.hyp = h
275
+ self.stride = m.stride # model strides
276
+ self.nc = m.nc # number of classes
277
+ self.nl = m.nl # number of layers
278
+ self.no = m.no
279
+ self.reg_max = m.reg_max
280
+ self.device = device
281
+
282
+ self.assigner = TaskAlignedAssigner(topk=int(os.getenv('YOLOM', 10)),
283
+ num_classes=self.nc,
284
+ alpha=float(os.getenv('YOLOA', 0.5)),
285
+ beta=float(os.getenv('YOLOB', 6.0)))
286
+ self.bbox_loss = BboxLoss(m.reg_max - 1, use_dfl=use_dfl).to(device)
287
+ self.proj = torch.arange(m.reg_max).float().to(device) # / 120.0
288
+ self.use_dfl = use_dfl
289
+
290
+ def preprocess(self, targets, batch_size, scale_tensor):
291
+ if targets.shape[0] == 0:
292
+ out = torch.zeros(batch_size, 0, 5, device=self.device)
293
+ else:
294
+ i = targets[:, 0] # image index
295
+ _, counts = i.unique(return_counts=True)
296
+ out = torch.zeros(batch_size, counts.max(), 5, device=self.device)
297
+ for j in range(batch_size):
298
+ matches = i == j
299
+ n = matches.sum()
300
+ if n:
301
+ out[j, :n] = targets[matches, 1:]
302
+ out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))
303
+ return out
304
+
305
+ def bbox_decode(self, anchor_points, pred_dist):
306
+ if self.use_dfl:
307
+ b, a, c = pred_dist.shape # batch, anchors, channels
308
+ pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
309
+ # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))
310
+ # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)
311
+ return dist2bbox(pred_dist, anchor_points, xywh=False)
312
+
313
+ def __call__(self, p, targets, img=None, epoch=0):
314
+ loss = torch.zeros(3, device=self.device) # box, cls, dfl
315
+ feats = p[1][0] if isinstance(p, tuple) else p[0]
316
+ feats2 = p[1][1] if isinstance(p, tuple) else p[1]
317
+
318
+ pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(
319
+ (self.reg_max * 4, self.nc), 1)
320
+ pred_scores = pred_scores.permute(0, 2, 1).contiguous()
321
+ pred_distri = pred_distri.permute(0, 2, 1).contiguous()
322
+
323
+ pred_distri2, pred_scores2 = torch.cat([xi.view(feats2[0].shape[0], self.no, -1) for xi in feats2], 2).split(
324
+ (self.reg_max * 4, self.nc), 1)
325
+ pred_scores2 = pred_scores2.permute(0, 2, 1).contiguous()
326
+ pred_distri2 = pred_distri2.permute(0, 2, 1).contiguous()
327
+
328
+ dtype = pred_scores.dtype
329
+ batch_size, grid_size = pred_scores.shape[:2]
330
+ imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0] # image size (h,w)
331
+ anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)
332
+
333
+ # targets
334
+ targets = self.preprocess(targets, batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])
335
+ gt_labels, gt_bboxes = targets.split((1, 4), 2) # cls, xyxy
336
+ mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)
337
+
338
+ # pboxes
339
+ pred_bboxes = self.bbox_decode(anchor_points, pred_distri) # xyxy, (b, h*w, 4)
340
+ pred_bboxes2 = self.bbox_decode(anchor_points, pred_distri2) # xyxy, (b, h*w, 4)
341
+
342
+ target_labels, target_bboxes, target_scores, fg_mask = self.assigner(
343
+ pred_scores2.detach().sigmoid(),
344
+ (pred_bboxes2.detach() * stride_tensor).type(gt_bboxes.dtype),
345
+ anchor_points * stride_tensor,
346
+ gt_labels,
347
+ gt_bboxes,
348
+ mask_gt)
349
+
350
+ target_bboxes /= stride_tensor
351
+ target_scores_sum = target_scores.sum()
352
+
353
+ # cls loss
354
+ # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum # VFL way
355
+ loss[1] = self.BCEcls(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum # BCE
356
+ loss[1] *= 0.25
357
+ loss[1] += self.BCEcls(pred_scores2, target_scores.to(dtype)).sum() / target_scores_sum # BCE
358
+
359
+ # bbox loss
360
+ if fg_mask.sum():
361
+ loss[0], loss[2], iou = self.bbox_loss(pred_distri,
362
+ pred_bboxes,
363
+ anchor_points,
364
+ target_bboxes,
365
+ target_scores,
366
+ target_scores_sum,
367
+ fg_mask)
368
+ loss[0] *= 0.25
369
+ loss[2] *= 0.25
370
+ if fg_mask.sum():
371
+ loss0_, loss2_, iou2 = self.bbox_loss(pred_distri2,
372
+ pred_bboxes2,
373
+ anchor_points,
374
+ target_bboxes,
375
+ target_scores,
376
+ target_scores_sum,
377
+ fg_mask)
378
+ loss[0] += loss0_
379
+ loss[2] += loss2_
380
+
381
+ loss[0] *= 7.5 # box gain
382
+ loss[1] *= 0.5 # cls gain
383
+ loss[2] *= 1.5 # dfl gain
384
+
385
+ return loss.sum() * batch_size, loss.detach() # loss(box, cls, dfl)
utils/loss_tal_triple.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from utils.general import xywh2xyxy
8
+ from utils.metrics import bbox_iou
9
+ from utils.tal.anchor_generator import dist2bbox, make_anchors, bbox2dist
10
+ from utils.tal.assigner import TaskAlignedAssigner
11
+ from utils.torch_utils import de_parallel
12
+
13
+
14
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
15
+ # return positive, negative label smoothing BCE targets
16
+ return 1.0 - 0.5 * eps, 0.5 * eps
17
+
18
+
19
+ class VarifocalLoss(nn.Module):
20
+ # Varifocal loss by Zhang et al. https://arxiv.org/abs/2008.13367
21
+ def __init__(self):
22
+ super().__init__()
23
+
24
+ def forward(self, pred_score, gt_score, label, alpha=0.75, gamma=2.0):
25
+ weight = alpha * pred_score.sigmoid().pow(gamma) * (1 - label) + gt_score * label
26
+ with torch.cuda.amp.autocast(enabled=False):
27
+ loss = (F.binary_cross_entropy_with_logits(pred_score.float(), gt_score.float(),
28
+ reduction="none") * weight).sum()
29
+ return loss
30
+
31
+
32
+ class FocalLoss(nn.Module):
33
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
34
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
35
+ super().__init__()
36
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
37
+ self.gamma = gamma
38
+ self.alpha = alpha
39
+ self.reduction = loss_fcn.reduction
40
+ self.loss_fcn.reduction = "none" # required to apply FL to each element
41
+
42
+ def forward(self, pred, true):
43
+ loss = self.loss_fcn(pred, true)
44
+ # p_t = torch.exp(-loss)
45
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
46
+
47
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
48
+ pred_prob = torch.sigmoid(pred) # prob from logits
49
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
50
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
51
+ modulating_factor = (1.0 - p_t) ** self.gamma
52
+ loss *= alpha_factor * modulating_factor
53
+
54
+ if self.reduction == "mean":
55
+ return loss.mean()
56
+ elif self.reduction == "sum":
57
+ return loss.sum()
58
+ else: # 'none'
59
+ return loss
60
+
61
+
62
+ class BboxLoss(nn.Module):
63
+ def __init__(self, reg_max, use_dfl=False):
64
+ super().__init__()
65
+ self.reg_max = reg_max
66
+ self.use_dfl = use_dfl
67
+
68
+ def forward(self, pred_dist, pred_bboxes, anchor_points, target_bboxes, target_scores, target_scores_sum, fg_mask):
69
+ # iou loss
70
+ bbox_mask = fg_mask.unsqueeze(-1).repeat([1, 1, 4]) # (b, h*w, 4)
71
+ pred_bboxes_pos = torch.masked_select(pred_bboxes, bbox_mask).view(-1, 4)
72
+ target_bboxes_pos = torch.masked_select(target_bboxes, bbox_mask).view(-1, 4)
73
+ bbox_weight = torch.masked_select(target_scores.sum(-1), fg_mask).unsqueeze(-1)
74
+
75
+ iou = bbox_iou(pred_bboxes_pos, target_bboxes_pos, xywh=False, CIoU=True)
76
+ loss_iou = 1.0 - iou
77
+
78
+ loss_iou *= bbox_weight
79
+ loss_iou = loss_iou.sum() / target_scores_sum
80
+
81
+ # dfl loss
82
+ if self.use_dfl:
83
+ dist_mask = fg_mask.unsqueeze(-1).repeat([1, 1, (self.reg_max + 1) * 4])
84
+ pred_dist_pos = torch.masked_select(pred_dist, dist_mask).view(-1, 4, self.reg_max + 1)
85
+ target_ltrb = bbox2dist(anchor_points, target_bboxes, self.reg_max)
86
+ target_ltrb_pos = torch.masked_select(target_ltrb, bbox_mask).view(-1, 4)
87
+ loss_dfl = self._df_loss(pred_dist_pos, target_ltrb_pos) * bbox_weight
88
+ loss_dfl = loss_dfl.sum() / target_scores_sum
89
+ else:
90
+ loss_dfl = torch.tensor(0.0).to(pred_dist.device)
91
+
92
+ return loss_iou, loss_dfl, iou
93
+
94
+ def _df_loss(self, pred_dist, target):
95
+ target_left = target.to(torch.long)
96
+ target_right = target_left + 1
97
+ weight_left = target_right.to(torch.float) - target
98
+ weight_right = 1 - weight_left
99
+ loss_left = F.cross_entropy(pred_dist.view(-1, self.reg_max + 1), target_left.view(-1), reduction="none").view(
100
+ target_left.shape) * weight_left
101
+ loss_right = F.cross_entropy(pred_dist.view(-1, self.reg_max + 1), target_right.view(-1),
102
+ reduction="none").view(target_left.shape) * weight_right
103
+ return (loss_left + loss_right).mean(-1, keepdim=True)
104
+
105
+
106
+ class ComputeLoss:
107
+ # Compute losses
108
+ def __init__(self, model, use_dfl=True):
109
+ device = next(model.parameters()).device # get model device
110
+ h = model.hyp # hyperparameters
111
+
112
+ # Define criteria
113
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device), reduction='none')
114
+
115
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
116
+ self.cp, self.cn = smooth_BCE(eps=h.get("label_smoothing", 0.0)) # positive, negative BCE targets
117
+
118
+ # Focal loss
119
+ g = h["fl_gamma"] # focal loss gamma
120
+ if g > 0:
121
+ BCEcls = FocalLoss(BCEcls, g)
122
+
123
+ m = de_parallel(model).model[-1] # Detect() module
124
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
125
+ self.BCEcls = BCEcls
126
+ self.hyp = h
127
+ self.stride = m.stride # model strides
128
+ self.nc = m.nc # number of classes
129
+ self.nl = m.nl # number of layers
130
+ self.no = m.no
131
+ self.reg_max = m.reg_max
132
+ self.device = device
133
+
134
+ self.assigner = TaskAlignedAssigner(topk=int(os.getenv('YOLOM', 10)),
135
+ num_classes=self.nc,
136
+ alpha=float(os.getenv('YOLOA', 0.5)),
137
+ beta=float(os.getenv('YOLOB', 6.0)))
138
+ self.assigner2 = TaskAlignedAssigner(topk=int(os.getenv('YOLOM', 10)),
139
+ num_classes=self.nc,
140
+ alpha=float(os.getenv('YOLOA', 0.5)),
141
+ beta=float(os.getenv('YOLOB', 6.0)))
142
+ self.assigner3 = TaskAlignedAssigner(topk=int(os.getenv('YOLOM', 10)),
143
+ num_classes=self.nc,
144
+ alpha=float(os.getenv('YOLOA', 0.5)),
145
+ beta=float(os.getenv('YOLOB', 6.0)))
146
+ self.bbox_loss = BboxLoss(m.reg_max - 1, use_dfl=use_dfl).to(device)
147
+ self.bbox_loss2 = BboxLoss(m.reg_max - 1, use_dfl=use_dfl).to(device)
148
+ self.bbox_loss3 = BboxLoss(m.reg_max - 1, use_dfl=use_dfl).to(device)
149
+ self.proj = torch.arange(m.reg_max).float().to(device) # / 120.0
150
+ self.use_dfl = use_dfl
151
+
152
+ def preprocess(self, targets, batch_size, scale_tensor):
153
+ if targets.shape[0] == 0:
154
+ out = torch.zeros(batch_size, 0, 5, device=self.device)
155
+ else:
156
+ i = targets[:, 0] # image index
157
+ _, counts = i.unique(return_counts=True)
158
+ out = torch.zeros(batch_size, counts.max(), 5, device=self.device)
159
+ for j in range(batch_size):
160
+ matches = i == j
161
+ n = matches.sum()
162
+ if n:
163
+ out[j, :n] = targets[matches, 1:]
164
+ out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))
165
+ return out
166
+
167
+ def bbox_decode(self, anchor_points, pred_dist):
168
+ if self.use_dfl:
169
+ b, a, c = pred_dist.shape # batch, anchors, channels
170
+ pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))
171
+ # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))
172
+ # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)
173
+ return dist2bbox(pred_dist, anchor_points, xywh=False)
174
+
175
+ def __call__(self, p, targets, img=None, epoch=0):
176
+ loss = torch.zeros(3, device=self.device) # box, cls, dfl
177
+ feats = p[1][0] if isinstance(p, tuple) else p[0]
178
+ feats2 = p[1][1] if isinstance(p, tuple) else p[1]
179
+ feats3 = p[1][2] if isinstance(p, tuple) else p[2]
180
+
181
+ pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(
182
+ (self.reg_max * 4, self.nc), 1)
183
+ pred_scores = pred_scores.permute(0, 2, 1).contiguous()
184
+ pred_distri = pred_distri.permute(0, 2, 1).contiguous()
185
+
186
+ pred_distri2, pred_scores2 = torch.cat([xi.view(feats2[0].shape[0], self.no, -1) for xi in feats2], 2).split(
187
+ (self.reg_max * 4, self.nc), 1)
188
+ pred_scores2 = pred_scores2.permute(0, 2, 1).contiguous()
189
+ pred_distri2 = pred_distri2.permute(0, 2, 1).contiguous()
190
+
191
+ pred_distri3, pred_scores3 = torch.cat([xi.view(feats3[0].shape[0], self.no, -1) for xi in feats3], 2).split(
192
+ (self.reg_max * 4, self.nc), 1)
193
+ pred_scores3 = pred_scores3.permute(0, 2, 1).contiguous()
194
+ pred_distri3 = pred_distri3.permute(0, 2, 1).contiguous()
195
+
196
+ dtype = pred_scores.dtype
197
+ batch_size, grid_size = pred_scores.shape[:2]
198
+ imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0] # image size (h,w)
199
+ anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)
200
+
201
+ # targets
202
+ targets = self.preprocess(targets, batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])
203
+ gt_labels, gt_bboxes = targets.split((1, 4), 2) # cls, xyxy
204
+ mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)
205
+
206
+ # pboxes
207
+ pred_bboxes = self.bbox_decode(anchor_points, pred_distri) # xyxy, (b, h*w, 4)
208
+ pred_bboxes2 = self.bbox_decode(anchor_points, pred_distri2) # xyxy, (b, h*w, 4)
209
+ pred_bboxes3 = self.bbox_decode(anchor_points, pred_distri3) # xyxy, (b, h*w, 4)
210
+
211
+ target_labels, target_bboxes, target_scores, fg_mask = self.assigner(
212
+ pred_scores.detach().sigmoid(),
213
+ (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),
214
+ anchor_points * stride_tensor,
215
+ gt_labels,
216
+ gt_bboxes,
217
+ mask_gt)
218
+ target_labels2, target_bboxes2, target_scores2, fg_mask2 = self.assigner2(
219
+ pred_scores2.detach().sigmoid(),
220
+ (pred_bboxes2.detach() * stride_tensor).type(gt_bboxes.dtype),
221
+ anchor_points * stride_tensor,
222
+ gt_labels,
223
+ gt_bboxes,
224
+ mask_gt)
225
+ target_labels3, target_bboxes3, target_scores3, fg_mask3 = self.assigner3(
226
+ pred_scores3.detach().sigmoid(),
227
+ (pred_bboxes3.detach() * stride_tensor).type(gt_bboxes.dtype),
228
+ anchor_points * stride_tensor,
229
+ gt_labels,
230
+ gt_bboxes,
231
+ mask_gt)
232
+
233
+ target_bboxes /= stride_tensor
234
+ target_scores_sum = max(target_scores.sum(), 1)
235
+ target_bboxes2 /= stride_tensor
236
+ target_scores_sum2 = max(target_scores2.sum(), 1)
237
+ target_bboxes3 /= stride_tensor
238
+ target_scores_sum3 = max(target_scores3.sum(), 1)
239
+
240
+ # cls loss
241
+ # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum # VFL way
242
+ loss[1] = 0.25 * self.BCEcls(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum # BCE
243
+ loss[1] += 0.25 * self.BCEcls(pred_scores2, target_scores2.to(dtype)).sum() / target_scores_sum2 # BCE
244
+ loss[1] += self.BCEcls(pred_scores3, target_scores3.to(dtype)).sum() / target_scores_sum3 # BCE
245
+
246
+ # bbox loss
247
+ if fg_mask.sum():
248
+ loss[0], loss[2], iou = self.bbox_loss(pred_distri,
249
+ pred_bboxes,
250
+ anchor_points,
251
+ target_bboxes,
252
+ target_scores,
253
+ target_scores_sum,
254
+ fg_mask)
255
+ loss[0] *= 0.25
256
+ loss[2] *= 0.25
257
+ if fg_mask2.sum():
258
+ loss0_, loss2_, iou2 = self.bbox_loss2(pred_distri2,
259
+ pred_bboxes2,
260
+ anchor_points,
261
+ target_bboxes2,
262
+ target_scores2,
263
+ target_scores_sum2,
264
+ fg_mask2)
265
+ loss[0] += 0.25 * loss0_
266
+ loss[2] += 0.25 * loss2_
267
+ if fg_mask3.sum():
268
+ loss0__, loss2__, iou3 = self.bbox_loss3(pred_distri3,
269
+ pred_bboxes3,
270
+ anchor_points,
271
+ target_bboxes3,
272
+ target_scores3,
273
+ target_scores_sum3,
274
+ fg_mask3)
275
+ loss[0] += loss0__
276
+ loss[2] += loss2__
277
+
278
+ loss[0] *= 7.5 # box gain
279
+ loss[1] *= 0.5 # cls gain
280
+ loss[2] *= 1.5 # dfl gain
281
+
282
+ return loss.sum() * batch_size, loss.detach() # loss(box, cls, dfl)
utils/metrics.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ from pathlib import Path
4
+
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import torch
8
+
9
+ from utils import TryExcept, threaded
10
+
11
+
12
+ def fitness(x):
13
+ # Model fitness as a weighted combination of metrics
14
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
15
+ return (x[:, :4] * w).sum(1)
16
+
17
+
18
+ def smooth(y, f=0.05):
19
+ # Box filter of fraction f
20
+ nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
21
+ p = np.ones(nf // 2) # ones padding
22
+ yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
23
+ return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed
24
+
25
+
26
+ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16, prefix=""):
27
+ """ Compute the average precision, given the recall and precision curves.
28
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
29
+ # Arguments
30
+ tp: True positives (nparray, nx1 or nx10).
31
+ conf: Objectness value from 0-1 (nparray).
32
+ pred_cls: Predicted object classes (nparray).
33
+ target_cls: True object classes (nparray).
34
+ plot: Plot precision-recall curve at mAP@0.5
35
+ save_dir: Plot save directory
36
+ # Returns
37
+ The average precision as computed in py-faster-rcnn.
38
+ """
39
+
40
+ # Sort by objectness
41
+ i = np.argsort(-conf)
42
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
43
+
44
+ # Find unique classes
45
+ unique_classes, nt = np.unique(target_cls, return_counts=True)
46
+ nc = unique_classes.shape[0] # number of classes, number of detections
47
+
48
+ # Create Precision-Recall curve and compute AP for each class
49
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
50
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
51
+ for ci, c in enumerate(unique_classes):
52
+ i = pred_cls == c
53
+ n_l = nt[ci] # number of labels
54
+ n_p = i.sum() # number of predictions
55
+ if n_p == 0 or n_l == 0:
56
+ continue
57
+
58
+ # Accumulate FPs and TPs
59
+ fpc = (1 - tp[i]).cumsum(0)
60
+ tpc = tp[i].cumsum(0)
61
+
62
+ # Recall
63
+ recall = tpc / (n_l + eps) # recall curve
64
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
65
+
66
+ # Precision
67
+ precision = tpc / (tpc + fpc) # precision curve
68
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
69
+
70
+ # AP from recall-precision curve
71
+ for j in range(tp.shape[1]):
72
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
73
+ if plot and j == 0:
74
+ py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
75
+
76
+ # Compute F1 (harmonic mean of precision and recall)
77
+ f1 = 2 * p * r / (p + r + eps)
78
+ names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
79
+ names = dict(enumerate(names)) # to dict
80
+ if plot:
81
+ plot_pr_curve(px, py, ap, Path(save_dir) / f'{prefix}PR_curve.png', names)
82
+ plot_mc_curve(px, f1, Path(save_dir) / f'{prefix}F1_curve.png', names, ylabel='F1')
83
+ plot_mc_curve(px, p, Path(save_dir) / f'{prefix}P_curve.png', names, ylabel='Precision')
84
+ plot_mc_curve(px, r, Path(save_dir) / f'{prefix}R_curve.png', names, ylabel='Recall')
85
+
86
+ i = smooth(f1.mean(0), 0.1).argmax() # max F1 index
87
+ p, r, f1 = p[:, i], r[:, i], f1[:, i]
88
+ tp = (r * nt).round() # true positives
89
+ fp = (tp / (p + eps) - tp).round() # false positives
90
+ return tp, fp, p, r, f1, ap, unique_classes.astype(int)
91
+
92
+
93
+ def compute_ap(recall, precision):
94
+ """ Compute the average precision, given the recall and precision curves
95
+ # Arguments
96
+ recall: The recall curve (list)
97
+ precision: The precision curve (list)
98
+ # Returns
99
+ Average precision, precision curve, recall curve
100
+ """
101
+
102
+ # Append sentinel values to beginning and end
103
+ mrec = np.concatenate(([0.0], recall, [1.0]))
104
+ mpre = np.concatenate(([1.0], precision, [0.0]))
105
+
106
+ # Compute the precision envelope
107
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
108
+
109
+ # Integrate area under curve
110
+ method = 'interp' # methods: 'continuous', 'interp'
111
+ if method == 'interp':
112
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
113
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
114
+ else: # 'continuous'
115
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
116
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
117
+
118
+ return ap, mpre, mrec
119
+
120
+
121
+ class ConfusionMatrix:
122
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
123
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
124
+ self.matrix = np.zeros((nc + 1, nc + 1))
125
+ self.nc = nc # number of classes
126
+ self.conf = conf
127
+ self.iou_thres = iou_thres
128
+
129
+ def process_batch(self, detections, labels):
130
+ """
131
+ Return intersection-over-union (Jaccard index) of boxes.
132
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
133
+ Arguments:
134
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
135
+ labels (Array[M, 5]), class, x1, y1, x2, y2
136
+ Returns:
137
+ None, updates confusion matrix accordingly
138
+ """
139
+ if detections is None:
140
+ gt_classes = labels.int()
141
+ for gc in gt_classes:
142
+ self.matrix[self.nc, gc] += 1 # background FN
143
+ return
144
+
145
+ detections = detections[detections[:, 4] > self.conf]
146
+ gt_classes = labels[:, 0].int()
147
+ detection_classes = detections[:, 5].int()
148
+ iou = box_iou(labels[:, 1:], detections[:, :4])
149
+
150
+ x = torch.where(iou > self.iou_thres)
151
+ if x[0].shape[0]:
152
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
153
+ if x[0].shape[0] > 1:
154
+ matches = matches[matches[:, 2].argsort()[::-1]]
155
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
156
+ matches = matches[matches[:, 2].argsort()[::-1]]
157
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
158
+ else:
159
+ matches = np.zeros((0, 3))
160
+
161
+ n = matches.shape[0] > 0
162
+ m0, m1, _ = matches.transpose().astype(int)
163
+ for i, gc in enumerate(gt_classes):
164
+ j = m0 == i
165
+ if n and sum(j) == 1:
166
+ self.matrix[detection_classes[m1[j]], gc] += 1 # correct
167
+ else:
168
+ self.matrix[self.nc, gc] += 1 # true background
169
+
170
+ if n:
171
+ for i, dc in enumerate(detection_classes):
172
+ if not any(m1 == i):
173
+ self.matrix[dc, self.nc] += 1 # predicted background
174
+
175
+ def matrix(self):
176
+ return self.matrix
177
+
178
+ def tp_fp(self):
179
+ tp = self.matrix.diagonal() # true positives
180
+ fp = self.matrix.sum(1) - tp # false positives
181
+ # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
182
+ return tp[:-1], fp[:-1] # remove background class
183
+
184
+ @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')
185
+ def plot(self, normalize=True, save_dir='', names=()):
186
+ import seaborn as sn
187
+
188
+ array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns
189
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
190
+
191
+ fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)
192
+ nc, nn = self.nc, len(names) # number of classes, names
193
+ sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size
194
+ labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
195
+ ticklabels = (names + ['background']) if labels else "auto"
196
+ with warnings.catch_warnings():
197
+ warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
198
+ sn.heatmap(array,
199
+ ax=ax,
200
+ annot=nc < 30,
201
+ annot_kws={
202
+ "size": 8},
203
+ cmap='Blues',
204
+ fmt='.2f',
205
+ square=True,
206
+ vmin=0.0,
207
+ xticklabels=ticklabels,
208
+ yticklabels=ticklabels).set_facecolor((1, 1, 1))
209
+ ax.set_ylabel('True')
210
+ ax.set_ylabel('Predicted')
211
+ ax.set_title('Confusion Matrix')
212
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
213
+ plt.close(fig)
214
+
215
+ def print(self):
216
+ for i in range(self.nc + 1):
217
+ print(' '.join(map(str, self.matrix[i])))
218
+
219
+
220
+ class WIoU_Scale:
221
+ ''' monotonous: {
222
+ None: origin v1
223
+ True: monotonic FM v2
224
+ False: non-monotonic FM v3
225
+ }
226
+ momentum: The momentum of running mean'''
227
+
228
+ iou_mean = 1.
229
+ monotonous = False
230
+ _momentum = 1 - 0.5 ** (1 / 7000)
231
+ _is_train = True
232
+
233
+ def __init__(self, iou):
234
+ self.iou = iou
235
+ self._update(self)
236
+
237
+ @classmethod
238
+ def _update(cls, self):
239
+ if cls._is_train: cls.iou_mean = (1 - cls._momentum) * cls.iou_mean + \
240
+ cls._momentum * self.iou.detach().mean().item()
241
+
242
+ @classmethod
243
+ def _scaled_loss(cls, self, gamma=1.9, delta=3):
244
+ if isinstance(self.monotonous, bool):
245
+ if self.monotonous:
246
+ return (self.iou.detach() / self.iou_mean).sqrt()
247
+ else:
248
+ beta = self.iou.detach() / self.iou_mean
249
+ alpha = delta * torch.pow(gamma, beta - delta)
250
+ return beta / alpha
251
+ return 1
252
+
253
+
254
+ def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, MDPIoU=False, feat_h=640, feat_w=640, eps=1e-7):
255
+ # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
256
+
257
+ # Get the coordinates of bounding boxes
258
+ if xywh: # transform from xywh to xyxy
259
+ (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
260
+ w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
261
+ b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
262
+ b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
263
+ else: # x1, y1, x2, y2 = box1
264
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
265
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
266
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
267
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
268
+
269
+ # Intersection area
270
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
271
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
272
+
273
+ # Union Area
274
+ union = w1 * h1 + w2 * h2 - inter + eps
275
+
276
+ # IoU
277
+ iou = inter / union
278
+ if CIoU or DIoU or GIoU:
279
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
280
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
281
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
282
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
283
+ rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
284
+ if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
285
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
286
+ with torch.no_grad():
287
+ alpha = v / (v - iou + (1 + eps))
288
+ return iou - (rho2 / c2 + v * alpha) # CIoU
289
+ return iou - rho2 / c2 # DIoU
290
+ c_area = cw * ch + eps # convex area
291
+ return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
292
+ elif MDPIoU:
293
+ d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
294
+ d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
295
+ mpdiou_hw_pow = feat_h ** 2 + feat_w ** 2
296
+ return iou - d1 / mpdiou_hw_pow - d2 / mpdiou_hw_pow # MPDIoU
297
+ return iou # IoU
298
+
299
+
300
+ def box_iou(box1, box2, eps=1e-7):
301
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
302
+ """
303
+ Return intersection-over-union (Jaccard index) of boxes.
304
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
305
+ Arguments:
306
+ box1 (Tensor[N, 4])
307
+ box2 (Tensor[M, 4])
308
+ Returns:
309
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
310
+ IoU values for every element in boxes1 and boxes2
311
+ """
312
+
313
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
314
+ (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)
315
+ inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)
316
+
317
+ # IoU = inter / (area1 + area2 - inter)
318
+ return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
319
+
320
+
321
+ def bbox_ioa(box1, box2, eps=1e-7):
322
+ """Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
323
+ box1: np.array of shape(nx4)
324
+ box2: np.array of shape(mx4)
325
+ returns: np.array of shape(nxm)
326
+ """
327
+
328
+ # Get the coordinates of bounding boxes
329
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
330
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
331
+
332
+ # Intersection area
333
+ inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \
334
+ (np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)
335
+
336
+ # box2 area
337
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
338
+
339
+ # Intersection over box2 area
340
+ return inter_area / box2_area
341
+
342
+
343
+ def wh_iou(wh1, wh2, eps=1e-7):
344
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
345
+ wh1 = wh1[:, None] # [N,1,2]
346
+ wh2 = wh2[None] # [1,M,2]
347
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
348
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter + eps) # iou = inter / (area1 + area2 - inter)
349
+
350
+
351
+ # Plots ----------------------------------------------------------------------------------------------------------------
352
+
353
+
354
+ @threaded
355
+ def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()):
356
+ # Precision-recall curve
357
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
358
+ py = np.stack(py, axis=1)
359
+
360
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
361
+ for i, y in enumerate(py.T):
362
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
363
+ else:
364
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
365
+
366
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
367
+ ax.set_xlabel('Recall')
368
+ ax.set_ylabel('Precision')
369
+ ax.set_xlim(0, 1)
370
+ ax.set_ylim(0, 1)
371
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
372
+ ax.set_title('Precision-Recall Curve')
373
+ fig.savefig(save_dir, dpi=250)
374
+ plt.close(fig)
375
+
376
+
377
+ @threaded
378
+ def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'):
379
+ # Metric-confidence curve
380
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
381
+
382
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
383
+ for i, y in enumerate(py):
384
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
385
+ else:
386
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
387
+
388
+ y = smooth(py.mean(0), 0.05)
389
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
390
+ ax.set_xlabel(xlabel)
391
+ ax.set_ylabel(ylabel)
392
+ ax.set_xlim(0, 1)
393
+ ax.set_ylim(0, 1)
394
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
395
+ ax.set_title(f'{ylabel}-Confidence Curve')
396
+ fig.savefig(save_dir, dpi=250)
397
+ plt.close(fig)
utils/panoptic/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # init
utils/panoptic/augmentations.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+
4
+ import cv2
5
+ import numpy as np
6
+
7
+ from ..augmentations import box_candidates
8
+ from ..general import resample_segments, segment2box
9
+ from ..metrics import bbox_ioa
10
+
11
+
12
+ def mixup(im, labels, segments, seg_cls, semantic_masks, im2, labels2, segments2, seg_cls2, semantic_masks2):
13
+ # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
14
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
15
+ im = (im * r + im2 * (1 - r)).astype(np.uint8)
16
+ labels = np.concatenate((labels, labels2), 0)
17
+ segments = np.concatenate((segments, segments2), 0)
18
+ seg_cls = np.concatenate((seg_cls, seg_cls2), 0)
19
+ semantic_masks = np.concatenate((semantic_masks, semantic_masks2), 0)
20
+ return im, labels, segments, seg_cls, semantic_masks
21
+
22
+
23
+ def random_perspective(im,
24
+ targets=(),
25
+ segments=(),
26
+ semantic_masks = (),
27
+ degrees=10,
28
+ translate=.1,
29
+ scale=.1,
30
+ shear=10,
31
+ perspective=0.0,
32
+ border=(0, 0)):
33
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
34
+ # targets = [cls, xyxy]
35
+
36
+ height = im.shape[0] + border[0] * 2 # shape(h,w,c)
37
+ width = im.shape[1] + border[1] * 2
38
+
39
+ # Center
40
+ C = np.eye(3)
41
+ C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
42
+ C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
43
+
44
+ # Perspective
45
+ P = np.eye(3)
46
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
47
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
48
+
49
+ # Rotation and Scale
50
+ R = np.eye(3)
51
+ a = random.uniform(-degrees, degrees)
52
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
53
+ s = random.uniform(1 - scale, 1 + scale)
54
+ # s = 2 ** random.uniform(-scale, scale)
55
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
56
+
57
+ # Shear
58
+ S = np.eye(3)
59
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
60
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
61
+
62
+ # Translation
63
+ T = np.eye(3)
64
+ T[0, 2] = (random.uniform(0.5 - translate, 0.5 + translate) * width) # x translation (pixels)
65
+ T[1, 2] = (random.uniform(0.5 - translate, 0.5 + translate) * height) # y translation (pixels)
66
+
67
+ # Combined rotation matrix
68
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
69
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
70
+ if perspective:
71
+ im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
72
+ else: # affine
73
+ im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
74
+
75
+ # Visualize
76
+ # import matplotlib.pyplot as plt
77
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
78
+ # ax[0].imshow(im[:, :, ::-1]) # base
79
+ # ax[1].imshow(im2[:, :, ::-1]) # warped
80
+
81
+ # Transform label coordinates
82
+ n = len(targets)
83
+ new_segments = []
84
+ new_semantic_masks = []
85
+ if n:
86
+ new = np.zeros((n, 4))
87
+ segments = resample_segments(segments) # upsample
88
+ for i, segment in enumerate(segments):
89
+ xy = np.ones((len(segment), 3))
90
+ xy[:, :2] = segment
91
+ xy = xy @ M.T # transform
92
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]) # perspective rescale or affine
93
+
94
+ # clip
95
+ new[i] = segment2box(xy, width, height)
96
+ new_segments.append(xy)
97
+
98
+ semantic_masks = resample_segments(semantic_masks)
99
+ for i, semantic_mask in enumerate(semantic_masks):
100
+ #if i < n:
101
+ # xy = np.ones((len(segments[i]), 3))
102
+ # xy[:, :2] = segments[i]
103
+ # xy = xy @ M.T # transform
104
+ # xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]) # perspective rescale or affine
105
+
106
+ # new[i] = segment2box(xy, width, height)
107
+ # new_segments.append(xy)
108
+
109
+ xy_s = np.ones((len(semantic_mask), 3))
110
+ xy_s[:, :2] = semantic_mask
111
+ xy_s = xy_s @ M.T # transform
112
+ xy_s = (xy_s[:, :2] / xy_s[:, 2:3] if perspective else xy_s[:, :2]) # perspective rescale or affine
113
+
114
+ new_semantic_masks.append(xy_s)
115
+
116
+ # filter candidates
117
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01)
118
+ targets = targets[i]
119
+ targets[:, 1:5] = new[i]
120
+ new_segments = np.array(new_segments)[i]
121
+ new_semantic_masks = np.array(new_semantic_masks)
122
+
123
+ return im, targets, new_segments, new_semantic_masks
124
+
125
+
126
+ def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
127
+ # Resize and pad image while meeting stride-multiple constraints
128
+ shape = im.shape[:2] # current shape [height, width]
129
+ if isinstance(new_shape, int):
130
+ new_shape = (new_shape, new_shape)
131
+
132
+ # Scale ratio (new / old)
133
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
134
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
135
+ r = min(r, 1.0)
136
+
137
+ # Compute padding
138
+ ratio = r, r # width, height ratios
139
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
140
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
141
+ if auto: # minimum rectangle
142
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
143
+ elif scaleFill: # stretch
144
+ dw, dh = 0.0, 0.0
145
+ new_unpad = (new_shape[1], new_shape[0])
146
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
147
+
148
+ dw /= 2 # divide padding into 2 sides
149
+ dh /= 2
150
+
151
+ if shape[::-1] != new_unpad: # resize
152
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
153
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
154
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
155
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
156
+ return im, ratio, (dw, dh)
157
+
158
+
159
+ def copy_paste(im, labels, segments, seg_cls, semantic_masks, p=0.5):
160
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
161
+ n = len(segments)
162
+ if p and n:
163
+ h, w, _ = im.shape # height, width, channels
164
+ im_new = np.zeros(im.shape, np.uint8)
165
+
166
+ # calculate ioa first then select indexes randomly
167
+ boxes = np.stack([w - labels[:, 3], labels[:, 2], w - labels[:, 1], labels[:, 4]], axis=-1) # (n, 4)
168
+ ioa = bbox_ioa(boxes, labels[:, 1:5]) # intersection over area
169
+ indexes = np.nonzero((ioa < 0.30).all(1))[0] # (N, )
170
+ n = len(indexes)
171
+ for j in random.sample(list(indexes), k=round(p * n)):
172
+ l, box, s = labels[j], boxes[j], segments[j]
173
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
174
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
175
+ seg_cls.append(l[0].astype(int))
176
+ semantic_masks.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
177
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)
178
+
179
+ result = cv2.flip(im, 1) # augment segments (flip left-right)
180
+ i = cv2.flip(im_new, 1).astype(bool)
181
+ im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
182
+
183
+ return im, labels, segments, seg_cls, semantic_masks