Mauricio Guerta commited on
Commit
640ea1d
1 Parent(s): a03571e

My yolov7detect

Browse files
app.py CHANGED
@@ -1,7 +1,8 @@
1
  import gradio as gr
2
  import torch
3
  import json
4
- import yolov7
 
5
 
6
 
7
  # Images
@@ -32,7 +33,7 @@ def yolov7_inference(
32
  Rendered image
33
  """
34
 
35
- model = yolov7.load(model_path, device="cpu", hf_model=True, trace=False)
36
  model.conf = conf_threshold
37
  model.iou = iou_threshold
38
  results = model([image], size=image_size)
 
1
  import gradio as gr
2
  import torch
3
  import json
4
+ #import yolov7
5
+ import yolov7detect.helpers as yolov7d
6
 
7
 
8
  # Images
 
33
  Rendered image
34
  """
35
 
36
+ model = yolov7d.load_model(model_path, device="cpu", hf_model=True, trace=False)
37
  model.conf = conf_threshold
38
  model.iou = iou_threshold
39
  results = model([image], size=image_size)
app1.py CHANGED
@@ -1,7 +1,8 @@
1
  import gradio as gr
2
  import torch
3
  import json
4
- import yolov7
 
5
 
6
 
7
  # Images
@@ -32,7 +33,7 @@ def yolov7_inference(
32
  Rendered image
33
  """
34
 
35
- model = yolov7.load(model_path, device="cpu", hf_model=True, trace=False)
36
  model.conf = conf_threshold
37
  model.iou = iou_threshold
38
  results = model([image], size=image_size)
 
1
  import gradio as gr
2
  import torch
3
  import json
4
+ #import yolov7
5
+ import yolov7detect.helpers as yolov7d
6
 
7
 
8
  # Images
 
33
  Rendered image
34
  """
35
 
36
+ model = yolov7d.load_model(model_path, device="cpu", hf_model=True, trace=False)
37
  model.conf = conf_threshold
38
  model.iou = iou_threshold
39
  results = model([image], size=image_size)
yolov7detect/__pycache__/helpers.cpython-38.pyc ADDED
Binary file (1.82 kB). View file
 
yolov7detect/detect.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import time
3
+ from pathlib import Path
4
+
5
+ import cv2
6
+ import torch
7
+ import torch.backends.cudnn as cudnn
8
+ from numpy import random
9
+
10
+ from yolov7.models.experimental import attempt_load
11
+ from yolov7.utils.datasets import LoadStreams, LoadImages
12
+ from yolov7.utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
13
+ scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
14
+ from yolov7.utils.plots import plot_one_box
15
+ from yolov7.utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
16
+
17
+
18
+ def detect(save_img=False):
19
+ source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
20
+ save_img = not opt.nosave and not source.endswith('.txt') # save inference images
21
+ webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
22
+ ('rtsp://', 'rtmp://', 'http://', 'https://'))
23
+
24
+ # Directories
25
+ save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
26
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
27
+
28
+ # Initialize
29
+ set_logging()
30
+ device = select_device(opt.device)
31
+ half = device.type != 'cpu' # half precision only supported on CUDA
32
+
33
+ # Load model
34
+ model = attempt_load(weights, map_location=device) # load FP32 model
35
+ stride = int(model.stride.max()) # model stride
36
+ imgsz = check_img_size(imgsz, s=stride) # check img_size
37
+
38
+ if trace:
39
+ model = TracedModel(model, device, opt.img_size)
40
+
41
+ if half:
42
+ model.half() # to FP16
43
+
44
+ # Second-stage classifier
45
+ classify = False
46
+ if classify:
47
+ modelc = load_classifier(name='resnet101', n=2) # initialize
48
+ modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
49
+
50
+ # Set Dataloader
51
+ vid_path, vid_writer = None, None
52
+ if webcam:
53
+ view_img = check_imshow()
54
+ cudnn.benchmark = True # set True to speed up constant image size inference
55
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride)
56
+ else:
57
+ dataset = LoadImages(source, img_size=imgsz, stride=stride)
58
+
59
+ # Get names and colors
60
+ names = model.module.names if hasattr(model, 'module') else model.names
61
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
62
+
63
+ # Run inference
64
+ if device.type != 'cpu':
65
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
66
+ old_img_w = old_img_h = imgsz
67
+ old_img_b = 1
68
+
69
+ t0 = time.time()
70
+ for path, img, im0s, vid_cap in dataset:
71
+ img = torch.from_numpy(img).to(device)
72
+ img = img.half() if half else img.float() # uint8 to fp16/32
73
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
74
+ if img.ndimension() == 3:
75
+ img = img.unsqueeze(0)
76
+
77
+ # Warmup
78
+ if device.type != 'cpu' and (old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
79
+ old_img_b = img.shape[0]
80
+ old_img_h = img.shape[2]
81
+ old_img_w = img.shape[3]
82
+ for i in range(3):
83
+ model(img, augment=opt.augment)[0]
84
+
85
+ # Inference
86
+ t1 = time_synchronized()
87
+ with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
88
+ pred = model(img, augment=opt.augment)[0]
89
+ t2 = time_synchronized()
90
+
91
+ # Apply NMS
92
+ pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
93
+ t3 = time_synchronized()
94
+
95
+ # Apply Classifier
96
+ if classify:
97
+ pred = apply_classifier(pred, modelc, img, im0s)
98
+
99
+ # Process detections
100
+ for i, det in enumerate(pred): # detections per image
101
+ if webcam: # batch_size >= 1
102
+ p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
103
+ else:
104
+ p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
105
+
106
+ p = Path(p) # to Path
107
+ save_path = str(save_dir / p.name) # img.jpg
108
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
109
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
110
+ if len(det):
111
+ # Rescale boxes from img_size to im0 size
112
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
113
+
114
+ # Print results
115
+ for c in det[:, -1].unique():
116
+ n = (det[:, -1] == c).sum() # detections per class
117
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
118
+
119
+ # Write results
120
+ for *xyxy, conf, cls in reversed(det):
121
+ if save_txt: # Write to file
122
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
123
+ line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
124
+ with open(txt_path + '.txt', 'a') as f:
125
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
126
+
127
+ if save_img or view_img: # Add bbox to image
128
+ label = f'{names[int(cls)]} {conf:.2f}'
129
+ plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
130
+
131
+ # Print time (inference + NMS)
132
+ print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
133
+
134
+ # Stream results
135
+ if view_img:
136
+ cv2.imshow(str(p), im0)
137
+ cv2.waitKey(1) # 1 millisecond
138
+
139
+ # Save results (image with detections)
140
+ if save_img:
141
+ if dataset.mode == 'image':
142
+ cv2.imwrite(save_path, im0)
143
+ print(f" The image with the result is saved in: {save_path}")
144
+ else: # 'video' or 'stream'
145
+ if vid_path != save_path: # new video
146
+ vid_path = save_path
147
+ if isinstance(vid_writer, cv2.VideoWriter):
148
+ vid_writer.release() # release previous video writer
149
+ if vid_cap: # video
150
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
151
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
152
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
153
+ else: # stream
154
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
155
+ save_path += '.mp4'
156
+ vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
157
+ vid_writer.write(im0)
158
+
159
+ if save_txt or save_img:
160
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
161
+ #print(f"Results saved to {save_dir}{s}")
162
+
163
+ print(f'Done. ({time.time() - t0:.3f}s)')
164
+
165
+
166
+ if __name__ == '__main__':
167
+ parser = argparse.ArgumentParser()
168
+ parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
169
+ parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
170
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
171
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
172
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
173
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
174
+ parser.add_argument('--view-img', action='store_true', help='display results')
175
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
176
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
177
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
178
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
179
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
180
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
181
+ parser.add_argument('--update', action='store_true', help='update all models')
182
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
183
+ parser.add_argument('--name', default='exp', help='save results to project/name')
184
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
185
+ parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
186
+ opt = parser.parse_args()
187
+ print(opt)
188
+ #check_requirements(exclude=('pycocotools', 'thop'))
189
+
190
+ with torch.no_grad():
191
+ if opt.update: # update all models (to fix SourceChangeWarning)
192
+ for opt.weights in ['yolov7.pt']:
193
+ detect()
194
+ strip_optimizer(opt.weights)
195
+ else:
196
+ detect()
yolov7detect/export.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+ import time
4
+ import warnings
5
+
6
+ sys.path.append('./') # to run '$ python *.py' files in subdirectories
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from torch.utils.mobile_optimizer import optimize_for_mobile
11
+
12
+ import models
13
+ from yolov7.models.experimental import attempt_load, End2End
14
+ from yolov7.utils.activations import Hardswish, SiLU
15
+ from yolov7.utils.general import set_logging, check_img_size
16
+ from yolov7.utils.torch_utils import select_device
17
+ from yolov7.utils.add_nms import RegisterNMS
18
+
19
+ if __name__ == '__main__':
20
+ parser = argparse.ArgumentParser()
21
+ parser.add_argument('--weights', type=str, default='./yolor-csp-c.pt', help='weights path')
22
+ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
23
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
24
+ parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes')
25
+ parser.add_argument('--dynamic-batch', action='store_true', help='dynamic batch onnx for tensorrt and onnx-runtime')
26
+ parser.add_argument('--grid', action='store_true', help='export Detect() layer grid')
27
+ parser.add_argument('--end2end', action='store_true', help='export end2end onnx')
28
+ parser.add_argument('--max-wh', type=int, default=None, help='None for tensorrt nms, int value for onnx-runtime nms')
29
+ parser.add_argument('--topk-all', type=int, default=100, help='topk objects for every images')
30
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='iou threshold for NMS')
31
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='conf threshold for NMS')
32
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
33
+ parser.add_argument('--simplify', action='store_true', help='simplify onnx model')
34
+ parser.add_argument('--include-nms', action='store_true', help='export end2end onnx')
35
+ parser.add_argument('--fp16', action='store_true', help='CoreML FP16 half-precision export')
36
+ parser.add_argument('--int8', action='store_true', help='CoreML INT8 quantization')
37
+ opt = parser.parse_args()
38
+ opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
39
+ opt.dynamic = opt.dynamic and not opt.end2end
40
+ opt.dynamic = False if opt.dynamic_batch else opt.dynamic
41
+ print(opt)
42
+ set_logging()
43
+ t = time.time()
44
+
45
+ # Load PyTorch model
46
+ device = select_device(opt.device)
47
+ model = attempt_load(opt.weights, map_location=device) # load FP32 model
48
+ labels = model.names
49
+
50
+ # Checks
51
+ gs = int(max(model.stride)) # grid size (max stride)
52
+ opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
53
+
54
+ # Input
55
+ img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
56
+
57
+ # Update model
58
+ for k, m in model.named_modules():
59
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
60
+ if isinstance(m, models.common.Conv): # assign export-friendly activations
61
+ if isinstance(m.act, nn.Hardswish):
62
+ m.act = Hardswish()
63
+ elif isinstance(m.act, nn.SiLU):
64
+ m.act = SiLU()
65
+ # elif isinstance(m, models.yolo.Detect):
66
+ # m.forward = m.forward_export # assign forward (optional)
67
+ model.model[-1].export = not opt.grid # set Detect() layer grid export
68
+ y = model(img) # dry run
69
+ if opt.include_nms:
70
+ model.model[-1].include_nms = True
71
+ y = None
72
+
73
+ # TorchScript export
74
+ try:
75
+ print('\nStarting TorchScript export with torch %s...' % torch.__version__)
76
+ f = opt.weights.replace('.pt', '.torchscript.pt') # filename
77
+ ts = torch.jit.trace(model, img, strict=False)
78
+ ts.save(f)
79
+ print('TorchScript export success, saved as %s' % f)
80
+ except Exception as e:
81
+ print('TorchScript export failure: %s' % e)
82
+
83
+ # CoreML export
84
+ try:
85
+ import coremltools as ct
86
+
87
+ print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
88
+ # convert model from torchscript and apply pixel scaling as per detect.py
89
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
90
+ bits, mode = (8, 'kmeans_lut') if opt.int8 else (16, 'linear') if opt.fp16 else (32, None)
91
+ if bits < 32:
92
+ if sys.platform.lower() == 'darwin': # quantization only supported on macOS
93
+ with warnings.catch_warnings():
94
+ warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
95
+ ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
96
+ else:
97
+ print('quantization only supported on macOS, skipping...')
98
+
99
+ f = opt.weights.replace('.pt', '.mlmodel') # filename
100
+ ct_model.save(f)
101
+ print('CoreML export success, saved as %s' % f)
102
+ except Exception as e:
103
+ print('CoreML export failure: %s' % e)
104
+
105
+ # TorchScript-Lite export
106
+ try:
107
+ print('\nStarting TorchScript-Lite export with torch %s...' % torch.__version__)
108
+ f = opt.weights.replace('.pt', '.torchscript.ptl') # filename
109
+ tsl = torch.jit.trace(model, img, strict=False)
110
+ tsl = optimize_for_mobile(tsl)
111
+ tsl._save_for_lite_interpreter(f)
112
+ print('TorchScript-Lite export success, saved as %s' % f)
113
+ except Exception as e:
114
+ print('TorchScript-Lite export failure: %s' % e)
115
+
116
+ # ONNX export
117
+ try:
118
+ import onnx
119
+
120
+ print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
121
+ f = opt.weights.replace('.pt', '.onnx') # filename
122
+ model.eval()
123
+ output_names = ['classes', 'boxes'] if y is None else ['output']
124
+ dynamic_axes = None
125
+ if opt.dynamic:
126
+ dynamic_axes = {'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
127
+ 'output': {0: 'batch', 2: 'y', 3: 'x'}}
128
+ if opt.dynamic_batch:
129
+ opt.batch_size = 'batch'
130
+ dynamic_axes = {
131
+ 'images': {
132
+ 0: 'batch',
133
+ }, }
134
+ if opt.end2end and opt.max_wh is None:
135
+ output_axes = {
136
+ 'num_dets': {0: 'batch'},
137
+ 'det_boxes': {0: 'batch'},
138
+ 'det_scores': {0: 'batch'},
139
+ 'det_classes': {0: 'batch'},
140
+ }
141
+ else:
142
+ output_axes = {
143
+ 'output': {0: 'batch'},
144
+ }
145
+ dynamic_axes.update(output_axes)
146
+ if opt.grid:
147
+ if opt.end2end:
148
+ print('\nStarting export end2end onnx model for %s...' % 'TensorRT' if opt.max_wh is None else 'onnxruntime')
149
+ model = End2End(model,opt.topk_all,opt.iou_thres,opt.conf_thres,opt.max_wh,device,len(labels))
150
+ if opt.end2end and opt.max_wh is None:
151
+ output_names = ['num_dets', 'det_boxes', 'det_scores', 'det_classes']
152
+ shapes = [opt.batch_size, 1, opt.batch_size, opt.topk_all, 4,
153
+ opt.batch_size, opt.topk_all, opt.batch_size, opt.topk_all]
154
+ else:
155
+ output_names = ['output']
156
+ else:
157
+ model.model[-1].concat = True
158
+
159
+ torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
160
+ output_names=output_names,
161
+ dynamic_axes=dynamic_axes)
162
+
163
+ # Checks
164
+ onnx_model = onnx.load(f) # load onnx model
165
+ onnx.checker.check_model(onnx_model) # check onnx model
166
+
167
+ if opt.end2end and opt.max_wh is None:
168
+ for i in onnx_model.graph.output:
169
+ for j in i.type.tensor_type.shape.dim:
170
+ j.dim_param = str(shapes.pop(0))
171
+
172
+ # print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
173
+
174
+ # # Metadata
175
+ # d = {'stride': int(max(model.stride))}
176
+ # for k, v in d.items():
177
+ # meta = onnx_model.metadata_props.add()
178
+ # meta.key, meta.value = k, str(v)
179
+ # onnx.save(onnx_model, f)
180
+
181
+ if opt.simplify:
182
+ try:
183
+ import onnxsim
184
+
185
+ print('\nStarting to simplify ONNX...')
186
+ onnx_model, check = onnxsim.simplify(onnx_model)
187
+ assert check, 'assert check failed'
188
+ except Exception as e:
189
+ print(f'Simplifier failure: {e}')
190
+
191
+ # print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
192
+ onnx.save(onnx_model,f)
193
+ print('ONNX export success, saved as %s' % f)
194
+
195
+ if opt.include_nms:
196
+ print('Registering NMS plugin for ONNX...')
197
+ mo = RegisterNMS(f)
198
+ mo.register_nms()
199
+ mo.save(f)
200
+
201
+ except Exception as e:
202
+ print('ONNX export failure: %s' % e)
203
+
204
+ # Finish
205
+ print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))
yolov7detect/helpers.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/fcakyon/yolov5-pip/blob/main/yolov5/helpers.py
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ FILE = Path(__file__).resolve()
7
+ ROOT = FILE.parents[0] # YOLOv5 root directory
8
+ if str(ROOT) not in sys.path:
9
+ sys.path.append(str(ROOT)) # add ROOT to PATH
10
+
11
+ from pathlib import Path
12
+
13
+ from PIL import Image
14
+
15
+ from yolov7.models.common import autoShape
16
+ from yolov7.models.experimental import attempt_load
17
+ from yolov7.utils.google_utils import attempt_download_from_hub, attempt_download
18
+ from yolov7.utils.torch_utils import TracedModel
19
+
20
+
21
+ def load_model(model_path, autoshape=True, device='cpu', trace=False, size=640, half=False, hf_model=False):
22
+ """
23
+ Creates a specified YOLOv7 model
24
+ Arguments:
25
+ model_path (str): path of the model
26
+ device (str): select device that model will be loaded (cpu, cuda)
27
+ trace (bool): if True, model will be traced
28
+ size (int): size of the input image
29
+ half (bool): if True, model will be in half precision
30
+ hf_model (bool): if True, model will be loaded from huggingface hub
31
+ Returns:
32
+ pytorch model
33
+ (Adapted from yolov7.hubconf.create)
34
+ """
35
+ if hf_model:
36
+ model_file = attempt_download_from_hub(model_path)
37
+ else:
38
+ model_file = attempt_download(model_path)
39
+
40
+ model = attempt_load(model_file, map_location=device)
41
+ if trace:
42
+ model = TracedModel(model, device, size)
43
+
44
+ if autoshape:
45
+ model = autoShape(model)
46
+
47
+ if half:
48
+ model.half()
49
+
50
+ return model
51
+
52
+
53
+ if __name__ == "__main__":
54
+ model_path = "yolov7.pt"
55
+ device = "cuda:0"
56
+ model = load_model(model_path, device, trace=False, size=640, hf_model=False)
57
+ imgs = [Image.open(x) for x in Path("inference/images").glob("*.jpg")]
58
+ results = model(imgs, size=640, augment=False)
yolov7detect/hubconf.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch Hub models
2
+
3
+ Usage:
4
+ import torch
5
+ model = torch.hub.load('repo', 'model')
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ import torch
11
+
12
+ from yolov7.models.yolo import Model
13
+ from yolov7.utils.general import check_requirements, set_logging
14
+ from yolov7.utils.google_utils import attempt_download
15
+ from yolov7.utils.torch_utils import select_device
16
+
17
+ dependencies = ['torch', 'yaml']
18
+ check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('pycocotools', 'thop'))
19
+ set_logging()
20
+
21
+
22
+ def create(name, pretrained, channels, classes, autoshape):
23
+ """Creates a specified model
24
+
25
+ Arguments:
26
+ name (str): name of model, i.e. 'yolov7'
27
+ pretrained (bool): load pretrained weights into the model
28
+ channels (int): number of input channels
29
+ classes (int): number of model classes
30
+
31
+ Returns:
32
+ pytorch model
33
+ """
34
+ try:
35
+ cfg = list((Path(__file__).parent / 'cfg').rglob(f'{name}.yaml'))[0] # model.yaml path
36
+ model = Model(cfg, channels, classes)
37
+ if pretrained:
38
+ fname = f'{name}.pt' # checkpoint filename
39
+ attempt_download(fname) # download if not found locally
40
+ ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
41
+ msd = model.state_dict() # model state_dict
42
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
43
+ csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
44
+ model.load_state_dict(csd, strict=False) # load
45
+ if len(ckpt['model'].names) == classes:
46
+ model.names = ckpt['model'].names # set class names attribute
47
+ if autoshape:
48
+ model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
49
+ device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
50
+ return model.to(device)
51
+
52
+ except Exception as e:
53
+ s = 'Cache maybe be out of date, try force_reload=True.'
54
+ raise Exception(s) from e
55
+
56
+
57
+ def custom(path_or_model='path/to/model.pt', autoshape=True):
58
+ """custom mode
59
+
60
+ Arguments (3 options):
61
+ path_or_model (str): 'path/to/model.pt'
62
+ path_or_model (dict): torch.load('path/to/model.pt')
63
+ path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
64
+
65
+ Returns:
66
+ pytorch model
67
+ """
68
+ model = torch.load(path_or_model, map_location=torch.device('cpu')) if isinstance(path_or_model, str) else path_or_model # load checkpoint
69
+ if isinstance(model, dict):
70
+ model = model['ema' if model.get('ema') else 'model'] # load model
71
+
72
+ hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
73
+ hub_model.load_state_dict(model.float().state_dict()) # load state_dict
74
+ hub_model.names = model.names # class names
75
+ if autoshape:
76
+ hub_model = hub_model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
77
+ device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
78
+ return hub_model.to(device)
79
+
80
+
81
+ def yolov7(pretrained=True, channels=3, classes=80, autoshape=True):
82
+ return create('yolov7', pretrained, channels, classes, autoshape)
83
+
84
+
85
+ if __name__ == '__main__':
86
+ model = custom(path_or_model='yolov7.pt') # custom example
87
+ # model = create(name='yolov7', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example
88
+
89
+ # Verify inference
90
+ import numpy as np
91
+ from PIL import Image
92
+
93
+ imgs = [np.zeros((640, 480, 3))]
94
+
95
+ results = model(imgs) # batched inference
96
+ results.print()
97
+ results.save()
yolov7detect/models/common.py ADDED
@@ -0,0 +1,2253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from copy import copy
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import requests
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from PIL import Image
12
+ from torch.cuda import amp
13
+
14
+ from yolov7.utils.datasets import letterbox
15
+ from yolov7.utils.general import increment_path, make_divisible, non_max_suppression, scale_coords, xyxy2xywh
16
+ from yolov7.utils.plots import color_list, plot_one_box
17
+ from yolov7.utils.torch_utils import copy_attr, time_synchronized
18
+
19
+ ##### basic ####
20
+
21
+
22
+ def autopad(k, p=None): # kernel, padding
23
+ # Pad to 'same'
24
+ if p is None:
25
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
26
+ return p
27
+
28
+
29
+ class MP(nn.Module):
30
+ def __init__(self, k=2):
31
+ super(MP, self).__init__()
32
+ self.m = nn.MaxPool2d(kernel_size=k, stride=k)
33
+
34
+ def forward(self, x):
35
+ return self.m(x)
36
+
37
+
38
+ class SP(nn.Module):
39
+ def __init__(self, k=3, s=1):
40
+ super(SP, self).__init__()
41
+ self.m = nn.MaxPool2d(kernel_size=k, stride=s, padding=k // 2)
42
+
43
+ def forward(self, x):
44
+ return self.m(x)
45
+
46
+
47
+ class ReOrg(nn.Module):
48
+ def __init__(self):
49
+ super(ReOrg, self).__init__()
50
+
51
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
52
+ return torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)
53
+
54
+
55
+ class Concat(nn.Module):
56
+ def __init__(self, dimension=1):
57
+ super(Concat, self).__init__()
58
+ self.d = dimension
59
+
60
+ def forward(self, x):
61
+ return torch.cat(x, self.d)
62
+
63
+
64
+ class Chuncat(nn.Module):
65
+ def __init__(self, dimension=1):
66
+ super(Chuncat, self).__init__()
67
+ self.d = dimension
68
+
69
+ def forward(self, x):
70
+ x1 = []
71
+ x2 = []
72
+ for xi in x:
73
+ xi1, xi2 = xi.chunk(2, self.d)
74
+ x1.append(xi1)
75
+ x2.append(xi2)
76
+ return torch.cat(x1 + x2, self.d)
77
+
78
+
79
+ class Shortcut(nn.Module):
80
+ def __init__(self, dimension=0):
81
+ super(Shortcut, self).__init__()
82
+ self.d = dimension
83
+
84
+ def forward(self, x):
85
+ return x[0] + x[1]
86
+
87
+
88
+ class Foldcut(nn.Module):
89
+ def __init__(self, dimension=0):
90
+ super(Foldcut, self).__init__()
91
+ self.d = dimension
92
+
93
+ def forward(self, x):
94
+ x1, x2 = x.chunk(2, self.d)
95
+ return x1 + x2
96
+
97
+
98
+ class Conv(nn.Module):
99
+ # Standard convolution
100
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
101
+ super(Conv, self).__init__()
102
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
103
+ self.bn = nn.BatchNorm2d(c2)
104
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
105
+
106
+ def forward(self, x):
107
+ return self.act(self.bn(self.conv(x)))
108
+
109
+ def fuseforward(self, x):
110
+ return self.act(self.conv(x))
111
+
112
+
113
+ class RobustConv(nn.Module):
114
+ # Robust convolution (use high kernel size 7-11 for: downsampling and other layers). Train for 300 - 450 epochs.
115
+ def __init__(
116
+ self, c1, c2, k=7, s=1, p=None, g=1, act=True, layer_scale_init_value=1e-6
117
+ ): # ch_in, ch_out, kernel, stride, padding, groups
118
+ super(RobustConv, self).__init__()
119
+ self.conv_dw = Conv(c1, c1, k=k, s=s, p=p, g=c1, act=act)
120
+ self.conv1x1 = nn.Conv2d(c1, c2, 1, 1, 0, groups=1, bias=True)
121
+ self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(c2)) if layer_scale_init_value > 0 else None
122
+
123
+ def forward(self, x):
124
+ x = x.to(memory_format=torch.channels_last)
125
+ x = self.conv1x1(self.conv_dw(x))
126
+ if self.gamma is not None:
127
+ x = x.mul(self.gamma.reshape(1, -1, 1, 1))
128
+ return x
129
+
130
+
131
+ class RobustConv2(nn.Module):
132
+ # Robust convolution 2 (use [32, 5, 2] or [32, 7, 4] or [32, 11, 8] for one of the paths in CSP).
133
+ def __init__(
134
+ self, c1, c2, k=7, s=4, p=None, g=1, act=True, layer_scale_init_value=1e-6
135
+ ): # ch_in, ch_out, kernel, stride, padding, groups
136
+ super(RobustConv2, self).__init__()
137
+ self.conv_strided = Conv(c1, c1, k=k, s=s, p=p, g=c1, act=act)
138
+ self.conv_deconv = nn.ConvTranspose2d(
139
+ in_channels=c1, out_channels=c2, kernel_size=s, stride=s, padding=0, bias=True, dilation=1, groups=1
140
+ )
141
+ self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(c2)) if layer_scale_init_value > 0 else None
142
+
143
+ def forward(self, x):
144
+ x = self.conv_deconv(self.conv_strided(x))
145
+ if self.gamma is not None:
146
+ x = x.mul(self.gamma.reshape(1, -1, 1, 1))
147
+ return x
148
+
149
+
150
+ def DWConv(c1, c2, k=1, s=1, act=True):
151
+ # Depthwise convolution
152
+ return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
153
+
154
+
155
+ class GhostConv(nn.Module):
156
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
157
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
158
+ super(GhostConv, self).__init__()
159
+ c_ = c2 // 2 # hidden channels
160
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
161
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
162
+
163
+ def forward(self, x):
164
+ y = self.cv1(x)
165
+ return torch.cat([y, self.cv2(y)], 1)
166
+
167
+
168
+ class Stem(nn.Module):
169
+ # Stem
170
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
171
+ super(Stem, self).__init__()
172
+ c_ = int(c2 / 2) # hidden channels
173
+ self.cv1 = Conv(c1, c_, 3, 2)
174
+ self.cv2 = Conv(c_, c_, 1, 1)
175
+ self.cv3 = Conv(c_, c_, 3, 2)
176
+ self.pool = torch.nn.MaxPool2d(2, stride=2)
177
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
178
+
179
+ def forward(self, x):
180
+ x = self.cv1(x)
181
+ return self.cv4(torch.cat((self.cv3(self.cv2(x)), self.pool(x)), dim=1))
182
+
183
+
184
+ class DownC(nn.Module):
185
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
186
+ def __init__(self, c1, c2, n=1, k=2):
187
+ super(DownC, self).__init__()
188
+ c_ = int(c1) # hidden channels
189
+ self.cv1 = Conv(c1, c_, 1, 1)
190
+ self.cv2 = Conv(c_, c2 // 2, 3, k)
191
+ self.cv3 = Conv(c1, c2 // 2, 1, 1)
192
+ self.mp = nn.MaxPool2d(kernel_size=k, stride=k)
193
+
194
+ def forward(self, x):
195
+ return torch.cat((self.cv2(self.cv1(x)), self.cv3(self.mp(x))), dim=1)
196
+
197
+
198
+ class SPP(nn.Module):
199
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
200
+ def __init__(self, c1, c2, k=(5, 9, 13)):
201
+ super(SPP, self).__init__()
202
+ c_ = c1 // 2 # hidden channels
203
+ self.cv1 = Conv(c1, c_, 1, 1)
204
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
205
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
206
+
207
+ def forward(self, x):
208
+ x = self.cv1(x)
209
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
210
+
211
+
212
+ class Bottleneck(nn.Module):
213
+ # Darknet bottleneck
214
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
215
+ super(Bottleneck, self).__init__()
216
+ c_ = int(c2 * e) # hidden channels
217
+ self.cv1 = Conv(c1, c_, 1, 1)
218
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
219
+ self.add = shortcut and c1 == c2
220
+
221
+ def forward(self, x):
222
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
223
+
224
+
225
+ class Res(nn.Module):
226
+ # ResNet bottleneck
227
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
228
+ super(Res, self).__init__()
229
+ c_ = int(c2 * e) # hidden channels
230
+ self.cv1 = Conv(c1, c_, 1, 1)
231
+ self.cv2 = Conv(c_, c_, 3, 1, g=g)
232
+ self.cv3 = Conv(c_, c2, 1, 1)
233
+ self.add = shortcut and c1 == c2
234
+
235
+ def forward(self, x):
236
+ return x + self.cv3(self.cv2(self.cv1(x))) if self.add else self.cv3(self.cv2(self.cv1(x)))
237
+
238
+
239
+ class ResX(Res):
240
+ # ResNet bottleneck
241
+ def __init__(self, c1, c2, shortcut=True, g=32, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
242
+ super().__init__(c1, c2, shortcut, g, e)
243
+ c_ = int(c2 * e) # hidden channels
244
+
245
+
246
+ class Ghost(nn.Module):
247
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
248
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
249
+ super(Ghost, self).__init__()
250
+ c_ = c2 // 2
251
+ self.conv = nn.Sequential(
252
+ GhostConv(c1, c_, 1, 1), # pw
253
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
254
+ GhostConv(c_, c2, 1, 1, act=False),
255
+ ) # pw-linear
256
+ self.shortcut = (
257
+ nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
258
+ )
259
+
260
+ def forward(self, x):
261
+ return self.conv(x) + self.shortcut(x)
262
+
263
+
264
+ ##### end of basic #####
265
+
266
+
267
+ ##### cspnet #####
268
+
269
+
270
+ class SPPCSPC(nn.Module):
271
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
272
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)):
273
+ super(SPPCSPC, self).__init__()
274
+ c_ = int(2 * c2 * e) # hidden channels
275
+ self.cv1 = Conv(c1, c_, 1, 1)
276
+ self.cv2 = Conv(c1, c_, 1, 1)
277
+ self.cv3 = Conv(c_, c_, 3, 1)
278
+ self.cv4 = Conv(c_, c_, 1, 1)
279
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
280
+ self.cv5 = Conv(4 * c_, c_, 1, 1)
281
+ self.cv6 = Conv(c_, c_, 3, 1)
282
+ self.cv7 = Conv(2 * c_, c2, 1, 1)
283
+
284
+ def forward(self, x):
285
+ x1 = self.cv4(self.cv3(self.cv1(x)))
286
+ y1 = self.cv6(self.cv5(torch.cat([x1] + [m(x1) for m in self.m], 1)))
287
+ y2 = self.cv2(x)
288
+ return self.cv7(torch.cat((y1, y2), dim=1))
289
+
290
+
291
+ class GhostSPPCSPC(SPPCSPC):
292
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
293
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)):
294
+ super().__init__(c1, c2, n, shortcut, g, e, k)
295
+ c_ = int(2 * c2 * e) # hidden channels
296
+ self.cv1 = GhostConv(c1, c_, 1, 1)
297
+ self.cv2 = GhostConv(c1, c_, 1, 1)
298
+ self.cv3 = GhostConv(c_, c_, 3, 1)
299
+ self.cv4 = GhostConv(c_, c_, 1, 1)
300
+ self.cv5 = GhostConv(4 * c_, c_, 1, 1)
301
+ self.cv6 = GhostConv(c_, c_, 3, 1)
302
+ self.cv7 = GhostConv(2 * c_, c2, 1, 1)
303
+
304
+
305
+ class GhostStem(Stem):
306
+ # Stem
307
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
308
+ super().__init__(c1, c2, k, s, p, g, act)
309
+ c_ = int(c2 / 2) # hidden channels
310
+ self.cv1 = GhostConv(c1, c_, 3, 2)
311
+ self.cv2 = GhostConv(c_, c_, 1, 1)
312
+ self.cv3 = GhostConv(c_, c_, 3, 2)
313
+ self.cv4 = GhostConv(2 * c_, c2, 1, 1)
314
+
315
+
316
+ class BottleneckCSPA(nn.Module):
317
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
318
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
319
+ super(BottleneckCSPA, self).__init__()
320
+ c_ = int(c2 * e) # hidden channels
321
+ self.cv1 = Conv(c1, c_, 1, 1)
322
+ self.cv2 = Conv(c1, c_, 1, 1)
323
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
324
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
325
+
326
+ def forward(self, x):
327
+ y1 = self.m(self.cv1(x))
328
+ y2 = self.cv2(x)
329
+ return self.cv3(torch.cat((y1, y2), dim=1))
330
+
331
+
332
+ class BottleneckCSPB(nn.Module):
333
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
334
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
335
+ super(BottleneckCSPB, self).__init__()
336
+ c_ = int(c2) # hidden channels
337
+ self.cv1 = Conv(c1, c_, 1, 1)
338
+ self.cv2 = Conv(c_, c_, 1, 1)
339
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
340
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
341
+
342
+ def forward(self, x):
343
+ x1 = self.cv1(x)
344
+ y1 = self.m(x1)
345
+ y2 = self.cv2(x1)
346
+ return self.cv3(torch.cat((y1, y2), dim=1))
347
+
348
+
349
+ class BottleneckCSPC(nn.Module):
350
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
351
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
352
+ super(BottleneckCSPC, self).__init__()
353
+ c_ = int(c2 * e) # hidden channels
354
+ self.cv1 = Conv(c1, c_, 1, 1)
355
+ self.cv2 = Conv(c1, c_, 1, 1)
356
+ self.cv3 = Conv(c_, c_, 1, 1)
357
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
358
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
359
+
360
+ def forward(self, x):
361
+ y1 = self.cv3(self.m(self.cv1(x)))
362
+ y2 = self.cv2(x)
363
+ return self.cv4(torch.cat((y1, y2), dim=1))
364
+
365
+
366
+ class ResCSPA(BottleneckCSPA):
367
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
368
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
369
+ super().__init__(c1, c2, n, shortcut, g, e)
370
+ c_ = int(c2 * e) # hidden channels
371
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
372
+
373
+
374
+ class ResCSPB(BottleneckCSPB):
375
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
376
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
377
+ super().__init__(c1, c2, n, shortcut, g, e)
378
+ c_ = int(c2) # hidden channels
379
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
380
+
381
+
382
+ class ResCSPC(BottleneckCSPC):
383
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
384
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
385
+ super().__init__(c1, c2, n, shortcut, g, e)
386
+ c_ = int(c2 * e) # hidden channels
387
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
388
+
389
+
390
+ class ResXCSPA(ResCSPA):
391
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
392
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
393
+ super().__init__(c1, c2, n, shortcut, g, e)
394
+ c_ = int(c2 * e) # hidden channels
395
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
396
+
397
+
398
+ class ResXCSPB(ResCSPB):
399
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
400
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
401
+ super().__init__(c1, c2, n, shortcut, g, e)
402
+ c_ = int(c2) # hidden channels
403
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
404
+
405
+
406
+ class ResXCSPC(ResCSPC):
407
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
408
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
409
+ super().__init__(c1, c2, n, shortcut, g, e)
410
+ c_ = int(c2 * e) # hidden channels
411
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
412
+
413
+
414
+ class GhostCSPA(BottleneckCSPA):
415
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
416
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
417
+ super().__init__(c1, c2, n, shortcut, g, e)
418
+ c_ = int(c2 * e) # hidden channels
419
+ self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)])
420
+
421
+
422
+ class GhostCSPB(BottleneckCSPB):
423
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
424
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
425
+ super().__init__(c1, c2, n, shortcut, g, e)
426
+ c_ = int(c2) # hidden channels
427
+ self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)])
428
+
429
+
430
+ class GhostCSPC(BottleneckCSPC):
431
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
432
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
433
+ super().__init__(c1, c2, n, shortcut, g, e)
434
+ c_ = int(c2 * e) # hidden channels
435
+ self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)])
436
+
437
+
438
+ ##### end of cspnet #####
439
+
440
+
441
+ ##### yolor #####
442
+
443
+
444
+ class ImplicitA(nn.Module):
445
+ def __init__(self, channel, mean=0.0, std=0.02):
446
+ super(ImplicitA, self).__init__()
447
+ self.channel = channel
448
+ self.mean = mean
449
+ self.std = std
450
+ self.implicit = nn.Parameter(torch.zeros(1, channel, 1, 1))
451
+ nn.init.normal_(self.implicit, mean=self.mean, std=self.std)
452
+
453
+ def forward(self, x):
454
+ return self.implicit + x
455
+
456
+
457
+ class ImplicitM(nn.Module):
458
+ def __init__(self, channel, mean=1.0, std=0.02):
459
+ super(ImplicitM, self).__init__()
460
+ self.channel = channel
461
+ self.mean = mean
462
+ self.std = std
463
+ self.implicit = nn.Parameter(torch.ones(1, channel, 1, 1))
464
+ nn.init.normal_(self.implicit, mean=self.mean, std=self.std)
465
+
466
+ def forward(self, x):
467
+ return self.implicit * x
468
+
469
+
470
+ ##### end of yolor #####
471
+
472
+
473
+ ##### repvgg #####
474
+
475
+
476
+ class RepConv(nn.Module):
477
+ # Represented convolution
478
+ # https://arxiv.org/abs/2101.03697
479
+
480
+ def __init__(self, c1, c2, k=3, s=1, p=None, g=1, act=True, deploy=False):
481
+ super(RepConv, self).__init__()
482
+
483
+ self.deploy = deploy
484
+ self.groups = g
485
+ self.in_channels = c1
486
+ self.out_channels = c2
487
+
488
+ assert k == 3
489
+ assert autopad(k, p) == 1
490
+
491
+ padding_11 = autopad(k, p) - k // 2
492
+
493
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
494
+
495
+ if deploy:
496
+ self.rbr_reparam = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=True)
497
+
498
+ else:
499
+ self.rbr_identity = nn.BatchNorm2d(num_features=c1) if c2 == c1 and s == 1 else None
500
+
501
+ self.rbr_dense = nn.Sequential(
502
+ nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False),
503
+ nn.BatchNorm2d(num_features=c2),
504
+ )
505
+
506
+ self.rbr_1x1 = nn.Sequential(
507
+ nn.Conv2d(c1, c2, 1, s, padding_11, groups=g, bias=False),
508
+ nn.BatchNorm2d(num_features=c2),
509
+ )
510
+
511
+ def forward(self, inputs):
512
+ if hasattr(self, "rbr_reparam"):
513
+ return self.act(self.rbr_reparam(inputs))
514
+
515
+ if self.rbr_identity is None:
516
+ id_out = 0
517
+ else:
518
+ id_out = self.rbr_identity(inputs)
519
+
520
+ return self.act(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)
521
+
522
+ def get_equivalent_kernel_bias(self):
523
+ kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
524
+ kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
525
+ kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
526
+ return (
527
+ kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid,
528
+ bias3x3 + bias1x1 + biasid,
529
+ )
530
+
531
+ def _pad_1x1_to_3x3_tensor(self, kernel1x1):
532
+ if kernel1x1 is None:
533
+ return 0
534
+ else:
535
+ return nn.functional.pad(kernel1x1, [1, 1, 1, 1])
536
+
537
+ def _fuse_bn_tensor(self, branch):
538
+ if branch is None:
539
+ return 0, 0
540
+ if isinstance(branch, nn.Sequential):
541
+ kernel = branch[0].weight
542
+ running_mean = branch[1].running_mean
543
+ running_var = branch[1].running_var
544
+ gamma = branch[1].weight
545
+ beta = branch[1].bias
546
+ eps = branch[1].eps
547
+ else:
548
+ assert isinstance(branch, nn.BatchNorm2d)
549
+ if not hasattr(self, "id_tensor"):
550
+ input_dim = self.in_channels // self.groups
551
+ kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
552
+ for i in range(self.in_channels):
553
+ kernel_value[i, i % input_dim, 1, 1] = 1
554
+ self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
555
+ kernel = self.id_tensor
556
+ running_mean = branch.running_mean
557
+ running_var = branch.running_var
558
+ gamma = branch.weight
559
+ beta = branch.bias
560
+ eps = branch.eps
561
+ std = (running_var + eps).sqrt()
562
+ t = (gamma / std).reshape(-1, 1, 1, 1)
563
+ return kernel * t, beta - running_mean * gamma / std
564
+
565
+ def repvgg_convert(self):
566
+ kernel, bias = self.get_equivalent_kernel_bias()
567
+ return (
568
+ kernel.detach().cpu().numpy(),
569
+ bias.detach().cpu().numpy(),
570
+ )
571
+
572
+ def fuse_conv_bn(self, conv, bn):
573
+
574
+ std = (bn.running_var + bn.eps).sqrt()
575
+ bias = bn.bias - bn.running_mean * bn.weight / std
576
+
577
+ t = (bn.weight / std).reshape(-1, 1, 1, 1)
578
+ weights = conv.weight * t
579
+
580
+ bn = nn.Identity()
581
+ conv = nn.Conv2d(
582
+ in_channels=conv.in_channels,
583
+ out_channels=conv.out_channels,
584
+ kernel_size=conv.kernel_size,
585
+ stride=conv.stride,
586
+ padding=conv.padding,
587
+ dilation=conv.dilation,
588
+ groups=conv.groups,
589
+ bias=True,
590
+ padding_mode=conv.padding_mode,
591
+ )
592
+
593
+ conv.weight = torch.nn.Parameter(weights)
594
+ conv.bias = torch.nn.Parameter(bias)
595
+ return conv
596
+
597
+ def fuse_repvgg_block(self):
598
+ if self.deploy:
599
+ return
600
+ print(f"RepConv.fuse_repvgg_block")
601
+
602
+ self.rbr_dense = self.fuse_conv_bn(self.rbr_dense[0], self.rbr_dense[1])
603
+
604
+ self.rbr_1x1 = self.fuse_conv_bn(self.rbr_1x1[0], self.rbr_1x1[1])
605
+ rbr_1x1_bias = self.rbr_1x1.bias
606
+ weight_1x1_expanded = torch.nn.functional.pad(self.rbr_1x1.weight, [1, 1, 1, 1])
607
+
608
+ # Fuse self.rbr_identity
609
+ if isinstance(self.rbr_identity, nn.BatchNorm2d) or isinstance(
610
+ self.rbr_identity, nn.modules.batchnorm.SyncBatchNorm
611
+ ):
612
+ # print(f"fuse: rbr_identity == BatchNorm2d or SyncBatchNorm")
613
+ identity_conv_1x1 = nn.Conv2d(
614
+ in_channels=self.in_channels,
615
+ out_channels=self.out_channels,
616
+ kernel_size=1,
617
+ stride=1,
618
+ padding=0,
619
+ groups=self.groups,
620
+ bias=False,
621
+ )
622
+ identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.to(self.rbr_1x1.weight.data.device)
623
+ identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.squeeze().squeeze()
624
+ # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}")
625
+ identity_conv_1x1.weight.data.fill_(0.0)
626
+ identity_conv_1x1.weight.data.fill_diagonal_(1.0)
627
+ identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.unsqueeze(2).unsqueeze(3)
628
+ # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}")
629
+
630
+ identity_conv_1x1 = self.fuse_conv_bn(identity_conv_1x1, self.rbr_identity)
631
+ bias_identity_expanded = identity_conv_1x1.bias
632
+ weight_identity_expanded = torch.nn.functional.pad(identity_conv_1x1.weight, [1, 1, 1, 1])
633
+ else:
634
+ # print(f"fuse: rbr_identity != BatchNorm2d, rbr_identity = {self.rbr_identity}")
635
+ bias_identity_expanded = torch.nn.Parameter(torch.zeros_like(rbr_1x1_bias))
636
+ weight_identity_expanded = torch.nn.Parameter(torch.zeros_like(weight_1x1_expanded))
637
+
638
+ # print(f"self.rbr_1x1.weight = {self.rbr_1x1.weight.shape}, ")
639
+ # print(f"weight_1x1_expanded = {weight_1x1_expanded.shape}, ")
640
+ # print(f"self.rbr_dense.weight = {self.rbr_dense.weight.shape}, ")
641
+
642
+ self.rbr_dense.weight = torch.nn.Parameter(
643
+ self.rbr_dense.weight + weight_1x1_expanded + weight_identity_expanded
644
+ )
645
+ self.rbr_dense.bias = torch.nn.Parameter(self.rbr_dense.bias + rbr_1x1_bias + bias_identity_expanded)
646
+
647
+ self.rbr_reparam = self.rbr_dense
648
+ self.deploy = True
649
+
650
+ if self.rbr_identity is not None:
651
+ del self.rbr_identity
652
+ self.rbr_identity = None
653
+
654
+ if self.rbr_1x1 is not None:
655
+ del self.rbr_1x1
656
+ self.rbr_1x1 = None
657
+
658
+ if self.rbr_dense is not None:
659
+ del self.rbr_dense
660
+ self.rbr_dense = None
661
+
662
+
663
+ class RepBottleneck(Bottleneck):
664
+ # Standard bottleneck
665
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
666
+ super().__init__(c1, c2, shortcut=True, g=1, e=0.5)
667
+ c_ = int(c2 * e) # hidden channels
668
+ self.cv2 = RepConv(c_, c2, 3, 1, g=g)
669
+
670
+
671
+ class RepBottleneckCSPA(BottleneckCSPA):
672
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
673
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
674
+ super().__init__(c1, c2, n, shortcut, g, e)
675
+ c_ = int(c2 * e) # hidden channels
676
+ self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
677
+
678
+
679
+ class RepBottleneckCSPB(BottleneckCSPB):
680
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
681
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
682
+ super().__init__(c1, c2, n, shortcut, g, e)
683
+ c_ = int(c2) # hidden channels
684
+ self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
685
+
686
+
687
+ class RepBottleneckCSPC(BottleneckCSPC):
688
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
689
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
690
+ super().__init__(c1, c2, n, shortcut, g, e)
691
+ c_ = int(c2 * e) # hidden channels
692
+ self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
693
+
694
+
695
+ class RepRes(Res):
696
+ # Standard bottleneck
697
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
698
+ super().__init__(c1, c2, shortcut, g, e)
699
+ c_ = int(c2 * e) # hidden channels
700
+ self.cv2 = RepConv(c_, c_, 3, 1, g=g)
701
+
702
+
703
+ class RepResCSPA(ResCSPA):
704
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
705
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
706
+ super().__init__(c1, c2, n, shortcut, g, e)
707
+ c_ = int(c2 * e) # hidden channels
708
+ self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
709
+
710
+
711
+ class RepResCSPB(ResCSPB):
712
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
713
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
714
+ super().__init__(c1, c2, n, shortcut, g, e)
715
+ c_ = int(c2) # hidden channels
716
+ self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
717
+
718
+
719
+ class RepResCSPC(ResCSPC):
720
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
721
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
722
+ super().__init__(c1, c2, n, shortcut, g, e)
723
+ c_ = int(c2 * e) # hidden channels
724
+ self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
725
+
726
+
727
+ class RepResX(ResX):
728
+ # Standard bottleneck
729
+ def __init__(self, c1, c2, shortcut=True, g=32, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
730
+ super().__init__(c1, c2, shortcut, g, e)
731
+ c_ = int(c2 * e) # hidden channels
732
+ self.cv2 = RepConv(c_, c_, 3, 1, g=g)
733
+
734
+
735
+ class RepResXCSPA(ResXCSPA):
736
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
737
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
738
+ super().__init__(c1, c2, n, shortcut, g, e)
739
+ c_ = int(c2 * e) # hidden channels
740
+ self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
741
+
742
+
743
+ class RepResXCSPB(ResXCSPB):
744
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
745
+ def __init__(self, c1, c2, n=1, shortcut=False, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
746
+ super().__init__(c1, c2, n, shortcut, g, e)
747
+ c_ = int(c2) # hidden channels
748
+ self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
749
+
750
+
751
+ class RepResXCSPC(ResXCSPC):
752
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
753
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
754
+ super().__init__(c1, c2, n, shortcut, g, e)
755
+ c_ = int(c2 * e) # hidden channels
756
+ self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
757
+
758
+
759
+ ##### end of repvgg #####
760
+
761
+
762
+ ##### transformer #####
763
+
764
+
765
+ class TransformerLayer(nn.Module):
766
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
767
+ def __init__(self, c, num_heads):
768
+ super().__init__()
769
+ self.q = nn.Linear(c, c, bias=False)
770
+ self.k = nn.Linear(c, c, bias=False)
771
+ self.v = nn.Linear(c, c, bias=False)
772
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
773
+ self.fc1 = nn.Linear(c, c, bias=False)
774
+ self.fc2 = nn.Linear(c, c, bias=False)
775
+
776
+ def forward(self, x):
777
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
778
+ x = self.fc2(self.fc1(x)) + x
779
+ return x
780
+
781
+
782
+ class TransformerBlock(nn.Module):
783
+ # Vision Transformer https://arxiv.org/abs/2010.11929
784
+ def __init__(self, c1, c2, num_heads, num_layers):
785
+ super().__init__()
786
+ self.conv = None
787
+ if c1 != c2:
788
+ self.conv = Conv(c1, c2)
789
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
790
+ self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
791
+ self.c2 = c2
792
+
793
+ def forward(self, x):
794
+ if self.conv is not None:
795
+ x = self.conv(x)
796
+ b, _, w, h = x.shape
797
+ p = x.flatten(2)
798
+ p = p.unsqueeze(0)
799
+ p = p.transpose(0, 3)
800
+ p = p.squeeze(3)
801
+ e = self.linear(p)
802
+ x = p + e
803
+
804
+ x = self.tr(x)
805
+ x = x.unsqueeze(3)
806
+ x = x.transpose(0, 3)
807
+ x = x.reshape(b, self.c2, w, h)
808
+ return x
809
+
810
+
811
+ ##### end of transformer #####
812
+
813
+
814
+ ##### yolov5 #####
815
+
816
+
817
+ class Focus(nn.Module):
818
+ # Focus wh information into c-space
819
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
820
+ super(Focus, self).__init__()
821
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
822
+ # self.contract = Contract(gain=2)
823
+
824
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
825
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
826
+ # return self.conv(self.contract(x))
827
+
828
+
829
+ class SPPF(nn.Module):
830
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
831
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
832
+ super().__init__()
833
+ c_ = c1 // 2 # hidden channels
834
+ self.cv1 = Conv(c1, c_, 1, 1)
835
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
836
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
837
+
838
+ def forward(self, x):
839
+ x = self.cv1(x)
840
+ y1 = self.m(x)
841
+ y2 = self.m(y1)
842
+ return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
843
+
844
+
845
+ class Contract(nn.Module):
846
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
847
+ def __init__(self, gain=2):
848
+ super().__init__()
849
+ self.gain = gain
850
+
851
+ def forward(self, x):
852
+ N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'
853
+ s = self.gain
854
+ x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2)
855
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
856
+ return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40)
857
+
858
+
859
+ class Expand(nn.Module):
860
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
861
+ def __init__(self, gain=2):
862
+ super().__init__()
863
+ self.gain = gain
864
+
865
+ def forward(self, x):
866
+ N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
867
+ s = self.gain
868
+ x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80)
869
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
870
+ return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160)
871
+
872
+
873
+ class NMS(nn.Module):
874
+ # Non-Maximum Suppression (NMS) module
875
+ conf = 0.25 # confidence threshold
876
+ iou = 0.45 # IoU threshold
877
+ classes = None # (optional list) filter by class
878
+
879
+ def __init__(self):
880
+ super(NMS, self).__init__()
881
+
882
+ def forward(self, x):
883
+ return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)
884
+
885
+
886
+ class autoShape(nn.Module):
887
+ # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
888
+ conf = 0.25 # NMS confidence threshold
889
+ iou = 0.45 # NMS IoU threshold
890
+ classes = None # (optional list) filter by class
891
+
892
+ def __init__(self, model):
893
+ super(autoShape, self).__init__()
894
+ """
895
+ The copy_attr function was added by @kadirnar.
896
+ """
897
+ copy_attr(self, model, include=("yaml", "nc", "hyp", "names", "stride", "abc"), exclude=()) # copy attributes
898
+ self.model = model.eval()
899
+
900
+ def autoshape(self):
901
+ print("autoShape already enabled, skipping... ") # model already converted to model.autoshape()
902
+ return self
903
+
904
+ @torch.no_grad()
905
+ def forward(self, imgs, size=640, augment=False, profile=False):
906
+ # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
907
+ # filename: imgs = 'data/samples/zidane.jpg'
908
+ # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg'
909
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
910
+ # PIL: = Image.open('image.jpg') # HWC x(640,1280,3)
911
+ # numpy: = np.zeros((640,1280,3)) # HWC
912
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
913
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
914
+ t = [time_synchronized()]
915
+ p = next(self.model.parameters()) # for device and type
916
+ if isinstance(imgs, torch.Tensor): # torch
917
+ with amp.autocast(enabled=p.device.type != "cpu"):
918
+ return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
919
+
920
+ # Pre-process
921
+ n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
922
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
923
+ for i, im in enumerate(imgs):
924
+ f = f"image{i}" # filename
925
+ if isinstance(im, str): # filename or uri
926
+ im, f = np.asarray(Image.open(requests.get(im, stream=True).raw if im.startswith("http") else im)), im
927
+ elif isinstance(im, Image.Image): # PIL Image
928
+ im, f = np.asarray(im), getattr(im, "filename", f) or f
929
+ files.append(Path(f).with_suffix(".jpg").name)
930
+ if im.shape[0] < 5: # image in CHW
931
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
932
+ im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input
933
+ s = im.shape[:2] # HWC
934
+ shape0.append(s) # image shape
935
+ g = size / max(s) # gain
936
+ shape1.append([y * g for y in s])
937
+ imgs[i] = im # update
938
+ shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
939
+ x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
940
+ x = np.stack(x, 0) if n > 1 else x[0][None] # stack
941
+ x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
942
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255.0 # uint8 to fp16/32
943
+ t.append(time_synchronized())
944
+
945
+ with amp.autocast(enabled=p.device.type != "cpu"):
946
+ # Inference
947
+ y = self.model(x, augment, profile)[0] # forward
948
+ t.append(time_synchronized())
949
+
950
+ # Post-process
951
+ y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS
952
+ for i in range(n):
953
+ scale_coords(shape1, y[i][:, :4], shape0[i])
954
+
955
+ t.append(time_synchronized())
956
+ return Detections(imgs, y, files, t, self.names, x.shape)
957
+
958
+
959
+ class Detections:
960
+ # detections class for YOLOv5 inference results
961
+ def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
962
+ super(Detections, self).__init__()
963
+ d = pred[0].device # device
964
+ gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1.0, 1.0], device=d) for im in imgs] # normalizations
965
+ self.imgs = imgs # list of images as numpy arrays
966
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
967
+ self.names = names # class names
968
+ self.files = files # image filenames
969
+ self.xyxy = pred # xyxy pixels
970
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
971
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
972
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
973
+ self.n = len(self.pred) # number of images (batch size)
974
+ self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
975
+ self.s = shape # inference BCHW shape
976
+
977
+ def display(self, pprint=False, show=False, save=False, render=False, save_dir=""):
978
+ colors = color_list()
979
+ for i, (img, pred) in enumerate(zip(self.imgs, self.pred)):
980
+ str = f"image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} "
981
+ if pred is not None:
982
+ for c in pred[:, -1].unique():
983
+ n = (pred[:, -1] == c).sum() # detections per class
984
+ str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
985
+ if show or save or render:
986
+ for *box, conf, cls in pred: # xyxy, confidence, class
987
+ label = f"{self.names[int(cls)]} {conf:.2f}"
988
+ plot_one_box(box, img, label=label, color=colors[int(cls) % 10])
989
+ img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img # from np
990
+ if pprint:
991
+ print(str.rstrip(", "))
992
+ if show:
993
+ img.show(self.files[i]) # show
994
+ if save:
995
+ f = self.files[i]
996
+ img.save(Path(save_dir) / f) # save
997
+ print(f"{'Saved' * (i == 0)} {f}", end="," if i < self.n - 1 else f" to {save_dir}\n")
998
+ if render:
999
+ self.imgs[i] = np.asarray(img)
1000
+
1001
+ def print(self):
1002
+ self.display(pprint=True) # print results
1003
+ print(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}" % self.t)
1004
+
1005
+ def show(self):
1006
+ self.display(show=True) # show results
1007
+
1008
+ def save(self, save_dir="runs/hub/exp"):
1009
+ save_dir = increment_path(save_dir, exist_ok=save_dir != "runs/hub/exp") # increment save_dir
1010
+ Path(save_dir).mkdir(parents=True, exist_ok=True)
1011
+ self.display(save=True, save_dir=save_dir) # save results
1012
+
1013
+ def render(self):
1014
+ self.display(render=True) # render results
1015
+ return self.imgs
1016
+
1017
+ def pandas(self):
1018
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
1019
+ new = copy(self) # return copy
1020
+ ca = "xmin", "ymin", "xmax", "ymax", "confidence", "class", "name" # xyxy columns
1021
+ cb = "xcenter", "ycenter", "width", "height", "confidence", "class", "name" # xywh columns
1022
+ for k, c in zip(["xyxy", "xyxyn", "xywh", "xywhn"], [ca, ca, cb, cb]):
1023
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
1024
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
1025
+ return new
1026
+
1027
+ def tolist(self):
1028
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
1029
+ x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
1030
+ for d in x:
1031
+ for k in ["imgs", "pred", "xyxy", "xyxyn", "xywh", "xywhn"]:
1032
+ setattr(d, k, getattr(d, k)[0]) # pop out of list
1033
+ return x
1034
+
1035
+ def __len__(self):
1036
+ return self.n
1037
+
1038
+
1039
+ class Classify(nn.Module):
1040
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
1041
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
1042
+ super(Classify, self).__init__()
1043
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
1044
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
1045
+ self.flat = nn.Flatten()
1046
+
1047
+ def forward(self, x):
1048
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
1049
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
1050
+
1051
+
1052
+ ##### end of yolov5 ######
1053
+
1054
+
1055
+ ##### orepa #####
1056
+
1057
+
1058
+ def transI_fusebn(kernel, bn):
1059
+ gamma = bn.weight
1060
+ std = (bn.running_var + bn.eps).sqrt()
1061
+ return kernel * ((gamma / std).reshape(-1, 1, 1, 1)), bn.bias - bn.running_mean * gamma / std
1062
+
1063
+
1064
+ class ConvBN(nn.Module):
1065
+ def __init__(
1066
+ self,
1067
+ in_channels,
1068
+ out_channels,
1069
+ kernel_size,
1070
+ stride=1,
1071
+ padding=0,
1072
+ dilation=1,
1073
+ groups=1,
1074
+ deploy=False,
1075
+ nonlinear=None,
1076
+ ):
1077
+ super().__init__()
1078
+ if nonlinear is None:
1079
+ self.nonlinear = nn.Identity()
1080
+ else:
1081
+ self.nonlinear = nonlinear
1082
+ if deploy:
1083
+ self.conv = nn.Conv2d(
1084
+ in_channels=in_channels,
1085
+ out_channels=out_channels,
1086
+ kernel_size=kernel_size,
1087
+ stride=stride,
1088
+ padding=padding,
1089
+ dilation=dilation,
1090
+ groups=groups,
1091
+ bias=True,
1092
+ )
1093
+ else:
1094
+ self.conv = nn.Conv2d(
1095
+ in_channels=in_channels,
1096
+ out_channels=out_channels,
1097
+ kernel_size=kernel_size,
1098
+ stride=stride,
1099
+ padding=padding,
1100
+ dilation=dilation,
1101
+ groups=groups,
1102
+ bias=False,
1103
+ )
1104
+ self.bn = nn.BatchNorm2d(num_features=out_channels)
1105
+
1106
+ def forward(self, x):
1107
+ if hasattr(self, "bn"):
1108
+ return self.nonlinear(self.bn(self.conv(x)))
1109
+ else:
1110
+ return self.nonlinear(self.conv(x))
1111
+
1112
+ def switch_to_deploy(self):
1113
+ kernel, bias = transI_fusebn(self.conv.weight, self.bn)
1114
+ conv = nn.Conv2d(
1115
+ in_channels=self.conv.in_channels,
1116
+ out_channels=self.conv.out_channels,
1117
+ kernel_size=self.conv.kernel_size,
1118
+ stride=self.conv.stride,
1119
+ padding=self.conv.padding,
1120
+ dilation=self.conv.dilation,
1121
+ groups=self.conv.groups,
1122
+ bias=True,
1123
+ )
1124
+ conv.weight.data = kernel
1125
+ conv.bias.data = bias
1126
+ for para in self.parameters():
1127
+ para.detach_()
1128
+ self.__delattr__("conv")
1129
+ self.__delattr__("bn")
1130
+ self.conv = conv
1131
+
1132
+
1133
+ class OREPA_3x3_RepConv(nn.Module):
1134
+ def __init__(
1135
+ self,
1136
+ in_channels,
1137
+ out_channels,
1138
+ kernel_size,
1139
+ stride=1,
1140
+ padding=0,
1141
+ dilation=1,
1142
+ groups=1,
1143
+ internal_channels_1x1_3x3=None,
1144
+ deploy=False,
1145
+ nonlinear=None,
1146
+ single_init=False,
1147
+ ):
1148
+ super(OREPA_3x3_RepConv, self).__init__()
1149
+ self.deploy = deploy
1150
+
1151
+ if nonlinear is None:
1152
+ self.nonlinear = nn.Identity()
1153
+ else:
1154
+ self.nonlinear = nonlinear
1155
+
1156
+ self.kernel_size = kernel_size
1157
+ self.in_channels = in_channels
1158
+ self.out_channels = out_channels
1159
+ self.groups = groups
1160
+ assert padding == kernel_size // 2
1161
+
1162
+ self.stride = stride
1163
+ self.padding = padding
1164
+ self.dilation = dilation
1165
+
1166
+ self.branch_counter = 0
1167
+
1168
+ self.weight_rbr_origin = nn.Parameter(
1169
+ torch.Tensor(out_channels, int(in_channels / self.groups), kernel_size, kernel_size)
1170
+ )
1171
+ nn.init.kaiming_uniform_(self.weight_rbr_origin, a=math.sqrt(1.0))
1172
+ self.branch_counter += 1
1173
+
1174
+ if groups < out_channels:
1175
+ self.weight_rbr_avg_conv = nn.Parameter(torch.Tensor(out_channels, int(in_channels / self.groups), 1, 1))
1176
+ self.weight_rbr_pfir_conv = nn.Parameter(torch.Tensor(out_channels, int(in_channels / self.groups), 1, 1))
1177
+ nn.init.kaiming_uniform_(self.weight_rbr_avg_conv, a=1.0)
1178
+ nn.init.kaiming_uniform_(self.weight_rbr_pfir_conv, a=1.0)
1179
+ self.weight_rbr_avg_conv.data
1180
+ self.weight_rbr_pfir_conv.data
1181
+ self.register_buffer(
1182
+ "weight_rbr_avg_avg", torch.ones(kernel_size, kernel_size).mul(1.0 / kernel_size / kernel_size)
1183
+ )
1184
+ self.branch_counter += 1
1185
+
1186
+ else:
1187
+ raise NotImplementedError
1188
+ self.branch_counter += 1
1189
+
1190
+ if internal_channels_1x1_3x3 is None:
1191
+ internal_channels_1x1_3x3 = (
1192
+ in_channels if groups < out_channels else 2 * in_channels
1193
+ ) # For mobilenet, it is better to have 2X internal channels
1194
+
1195
+ if internal_channels_1x1_3x3 == in_channels:
1196
+ self.weight_rbr_1x1_kxk_idconv1 = nn.Parameter(
1197
+ torch.zeros(in_channels, int(in_channels / self.groups), 1, 1)
1198
+ )
1199
+ id_value = np.zeros((in_channels, int(in_channels / self.groups), 1, 1))
1200
+ for i in range(in_channels):
1201
+ id_value[i, i % int(in_channels / self.groups), 0, 0] = 1
1202
+ id_tensor = torch.from_numpy(id_value).type_as(self.weight_rbr_1x1_kxk_idconv1)
1203
+ self.register_buffer("id_tensor", id_tensor)
1204
+
1205
+ else:
1206
+ self.weight_rbr_1x1_kxk_conv1 = nn.Parameter(
1207
+ torch.Tensor(internal_channels_1x1_3x3, int(in_channels / self.groups), 1, 1)
1208
+ )
1209
+ nn.init.kaiming_uniform_(self.weight_rbr_1x1_kxk_conv1, a=math.sqrt(1.0))
1210
+ self.weight_rbr_1x1_kxk_conv2 = nn.Parameter(
1211
+ torch.Tensor(out_channels, int(internal_channels_1x1_3x3 / self.groups), kernel_size, kernel_size)
1212
+ )
1213
+ nn.init.kaiming_uniform_(self.weight_rbr_1x1_kxk_conv2, a=math.sqrt(1.0))
1214
+ self.branch_counter += 1
1215
+
1216
+ expand_ratio = 8
1217
+ self.weight_rbr_gconv_dw = nn.Parameter(torch.Tensor(in_channels * expand_ratio, 1, kernel_size, kernel_size))
1218
+ self.weight_rbr_gconv_pw = nn.Parameter(torch.Tensor(out_channels, in_channels * expand_ratio, 1, 1))
1219
+ nn.init.kaiming_uniform_(self.weight_rbr_gconv_dw, a=math.sqrt(1.0))
1220
+ nn.init.kaiming_uniform_(self.weight_rbr_gconv_pw, a=math.sqrt(1.0))
1221
+ self.branch_counter += 1
1222
+
1223
+ if out_channels == in_channels and stride == 1:
1224
+ self.branch_counter += 1
1225
+
1226
+ self.vector = nn.Parameter(torch.Tensor(self.branch_counter, self.out_channels))
1227
+ self.bn = nn.BatchNorm2d(out_channels)
1228
+
1229
+ self.fre_init()
1230
+
1231
+ nn.init.constant_(self.vector[0, :], 0.25) # origin
1232
+ nn.init.constant_(self.vector[1, :], 0.25) # avg
1233
+ nn.init.constant_(self.vector[2, :], 0.0) # prior
1234
+ nn.init.constant_(self.vector[3, :], 0.5) # 1x1_kxk
1235
+ nn.init.constant_(self.vector[4, :], 0.5) # dws_conv
1236
+
1237
+ def fre_init(self):
1238
+ prior_tensor = torch.Tensor(self.out_channels, self.kernel_size, self.kernel_size)
1239
+ half_fg = self.out_channels / 2
1240
+ for i in range(self.out_channels):
1241
+ for h in range(3):
1242
+ for w in range(3):
1243
+ if i < half_fg:
1244
+ prior_tensor[i, h, w] = math.cos(math.pi * (h + 0.5) * (i + 1) / 3)
1245
+ else:
1246
+ prior_tensor[i, h, w] = math.cos(math.pi * (w + 0.5) * (i + 1 - half_fg) / 3)
1247
+
1248
+ self.register_buffer("weight_rbr_prior", prior_tensor)
1249
+
1250
+ def weight_gen(self):
1251
+
1252
+ weight_rbr_origin = torch.einsum("oihw,o->oihw", self.weight_rbr_origin, self.vector[0, :])
1253
+
1254
+ weight_rbr_avg = torch.einsum(
1255
+ "oihw,o->oihw",
1256
+ torch.einsum("oihw,hw->oihw", self.weight_rbr_avg_conv, self.weight_rbr_avg_avg),
1257
+ self.vector[1, :],
1258
+ )
1259
+
1260
+ weight_rbr_pfir = torch.einsum(
1261
+ "oihw,o->oihw",
1262
+ torch.einsum("oihw,ohw->oihw", self.weight_rbr_pfir_conv, self.weight_rbr_prior),
1263
+ self.vector[2, :],
1264
+ )
1265
+
1266
+ weight_rbr_1x1_kxk_conv1 = None
1267
+ if hasattr(self, "weight_rbr_1x1_kxk_idconv1"):
1268
+ weight_rbr_1x1_kxk_conv1 = (self.weight_rbr_1x1_kxk_idconv1 + self.id_tensor).squeeze()
1269
+ elif hasattr(self, "weight_rbr_1x1_kxk_conv1"):
1270
+ weight_rbr_1x1_kxk_conv1 = self.weight_rbr_1x1_kxk_conv1.squeeze()
1271
+ else:
1272
+ raise NotImplementedError
1273
+ weight_rbr_1x1_kxk_conv2 = self.weight_rbr_1x1_kxk_conv2
1274
+
1275
+ if self.groups > 1:
1276
+ g = self.groups
1277
+ t, ig = weight_rbr_1x1_kxk_conv1.size()
1278
+ o, tg, h, w = weight_rbr_1x1_kxk_conv2.size()
1279
+ weight_rbr_1x1_kxk_conv1 = weight_rbr_1x1_kxk_conv1.view(g, int(t / g), ig)
1280
+ weight_rbr_1x1_kxk_conv2 = weight_rbr_1x1_kxk_conv2.view(g, int(o / g), tg, h, w)
1281
+ weight_rbr_1x1_kxk = torch.einsum(
1282
+ "gti,gothw->goihw", weight_rbr_1x1_kxk_conv1, weight_rbr_1x1_kxk_conv2
1283
+ ).view(o, ig, h, w)
1284
+ else:
1285
+ weight_rbr_1x1_kxk = torch.einsum("ti,othw->oihw", weight_rbr_1x1_kxk_conv1, weight_rbr_1x1_kxk_conv2)
1286
+
1287
+ weight_rbr_1x1_kxk = torch.einsum("oihw,o->oihw", weight_rbr_1x1_kxk, self.vector[3, :])
1288
+
1289
+ weight_rbr_gconv = self.dwsc2full(self.weight_rbr_gconv_dw, self.weight_rbr_gconv_pw, self.in_channels)
1290
+ weight_rbr_gconv = torch.einsum("oihw,o->oihw", weight_rbr_gconv, self.vector[4, :])
1291
+
1292
+ weight = weight_rbr_origin + weight_rbr_avg + weight_rbr_1x1_kxk + weight_rbr_pfir + weight_rbr_gconv
1293
+
1294
+ return weight
1295
+
1296
+ def dwsc2full(self, weight_dw, weight_pw, groups):
1297
+
1298
+ t, ig, h, w = weight_dw.size()
1299
+ o, _, _, _ = weight_pw.size()
1300
+ tg = int(t / groups)
1301
+ i = int(ig * groups)
1302
+ weight_dw = weight_dw.view(groups, tg, ig, h, w)
1303
+ weight_pw = weight_pw.squeeze().view(o, groups, tg)
1304
+
1305
+ weight_dsc = torch.einsum("gtihw,ogt->ogihw", weight_dw, weight_pw)
1306
+ return weight_dsc.view(o, i, h, w)
1307
+
1308
+ def forward(self, inputs):
1309
+ weight = self.weight_gen()
1310
+ out = F.conv2d(
1311
+ inputs,
1312
+ weight,
1313
+ bias=None,
1314
+ stride=self.stride,
1315
+ padding=self.padding,
1316
+ dilation=self.dilation,
1317
+ groups=self.groups,
1318
+ )
1319
+
1320
+ return self.nonlinear(self.bn(out))
1321
+
1322
+
1323
+ class RepConv_OREPA(nn.Module):
1324
+ def __init__(
1325
+ self,
1326
+ c1,
1327
+ c2,
1328
+ k=3,
1329
+ s=1,
1330
+ padding=1,
1331
+ dilation=1,
1332
+ groups=1,
1333
+ padding_mode="zeros",
1334
+ deploy=False,
1335
+ use_se=False,
1336
+ nonlinear=nn.SiLU(),
1337
+ ):
1338
+ super(RepConv_OREPA, self).__init__()
1339
+ self.deploy = deploy
1340
+ self.groups = groups
1341
+ self.in_channels = c1
1342
+ self.out_channels = c2
1343
+
1344
+ self.padding = padding
1345
+ self.dilation = dilation
1346
+ self.groups = groups
1347
+
1348
+ assert k == 3
1349
+ assert padding == 1
1350
+
1351
+ padding_11 = padding - k // 2
1352
+
1353
+ if nonlinear is None:
1354
+ self.nonlinearity = nn.Identity()
1355
+ else:
1356
+ self.nonlinearity = nonlinear
1357
+
1358
+ if use_se:
1359
+ self.se = SEBlock(self.out_channels, internal_neurons=self.out_channels // 16)
1360
+ else:
1361
+ self.se = nn.Identity()
1362
+
1363
+ if deploy:
1364
+ self.rbr_reparam = nn.Conv2d(
1365
+ in_channels=self.in_channels,
1366
+ out_channels=self.out_channels,
1367
+ kernel_size=k,
1368
+ stride=s,
1369
+ padding=padding,
1370
+ dilation=dilation,
1371
+ groups=groups,
1372
+ bias=True,
1373
+ padding_mode=padding_mode,
1374
+ )
1375
+
1376
+ else:
1377
+ self.rbr_identity = (
1378
+ nn.BatchNorm2d(num_features=self.in_channels)
1379
+ if self.out_channels == self.in_channels and s == 1
1380
+ else None
1381
+ )
1382
+ self.rbr_dense = OREPA_3x3_RepConv(
1383
+ in_channels=self.in_channels,
1384
+ out_channels=self.out_channels,
1385
+ kernel_size=k,
1386
+ stride=s,
1387
+ padding=padding,
1388
+ groups=groups,
1389
+ dilation=1,
1390
+ )
1391
+ self.rbr_1x1 = ConvBN(
1392
+ in_channels=self.in_channels,
1393
+ out_channels=self.out_channels,
1394
+ kernel_size=1,
1395
+ stride=s,
1396
+ padding=padding_11,
1397
+ groups=groups,
1398
+ dilation=1,
1399
+ )
1400
+ print("RepVGG Block, identity = ", self.rbr_identity)
1401
+
1402
+ def forward(self, inputs):
1403
+ if hasattr(self, "rbr_reparam"):
1404
+ return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
1405
+
1406
+ if self.rbr_identity is None:
1407
+ id_out = 0
1408
+ else:
1409
+ id_out = self.rbr_identity(inputs)
1410
+
1411
+ out1 = self.rbr_dense(inputs)
1412
+ out2 = self.rbr_1x1(inputs)
1413
+ out3 = id_out
1414
+ out = out1 + out2 + out3
1415
+
1416
+ return self.nonlinearity(self.se(out))
1417
+
1418
+ # Optional. This improves the accuracy and facilitates quantization.
1419
+ # 1. Cancel the original weight decay on rbr_dense.conv.weight and rbr_1x1.conv.weight.
1420
+ # 2. Use like this.
1421
+ # loss = criterion(....)
1422
+ # for every RepVGGBlock blk:
1423
+ # loss += weight_decay_coefficient * 0.5 * blk.get_cust_L2()
1424
+ # optimizer.zero_grad()
1425
+ # loss.backward()
1426
+
1427
+ # Not used for OREPA
1428
+ def get_custom_L2(self):
1429
+ K3 = self.rbr_dense.weight_gen()
1430
+ K1 = self.rbr_1x1.conv.weight
1431
+ t3 = (
1432
+ (self.rbr_dense.bn.weight / ((self.rbr_dense.bn.running_var + self.rbr_dense.bn.eps).sqrt()))
1433
+ .reshape(-1, 1, 1, 1)
1434
+ .detach()
1435
+ )
1436
+ t1 = (
1437
+ (self.rbr_1x1.bn.weight / ((self.rbr_1x1.bn.running_var + self.rbr_1x1.bn.eps).sqrt()))
1438
+ .reshape(-1, 1, 1, 1)
1439
+ .detach()
1440
+ )
1441
+
1442
+ l2_loss_circle = (K3 ** 2).sum() - (
1443
+ K3[:, :, 1:2, 1:2] ** 2
1444
+ ).sum() # The L2 loss of the "circle" of weights in 3x3 kernel. Use regular L2 on them.
1445
+ eq_kernel = K3[:, :, 1:2, 1:2] * t3 + K1 * t1 # The equivalent resultant central point of 3x3 kernel.
1446
+ l2_loss_eq_kernel = (
1447
+ eq_kernel ** 2 / (t3 ** 2 + t1 ** 2)
1448
+ ).sum() # Normalize for an L2 coefficient comparable to regular L2.
1449
+ return l2_loss_eq_kernel + l2_loss_circle
1450
+
1451
+ def get_equivalent_kernel_bias(self):
1452
+ kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
1453
+ kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
1454
+ kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
1455
+ return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
1456
+
1457
+ def _pad_1x1_to_3x3_tensor(self, kernel1x1):
1458
+ if kernel1x1 is None:
1459
+ return 0
1460
+ else:
1461
+ return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
1462
+
1463
+ def _fuse_bn_tensor(self, branch):
1464
+ if branch is None:
1465
+ return 0, 0
1466
+ if not isinstance(branch, nn.BatchNorm2d):
1467
+ if isinstance(branch, OREPA_3x3_RepConv):
1468
+ kernel = branch.weight_gen()
1469
+ elif isinstance(branch, ConvBN):
1470
+ kernel = branch.conv.weight
1471
+ else:
1472
+ raise NotImplementedError
1473
+ running_mean = branch.bn.running_mean
1474
+ running_var = branch.bn.running_var
1475
+ gamma = branch.bn.weight
1476
+ beta = branch.bn.bias
1477
+ eps = branch.bn.eps
1478
+ else:
1479
+ if not hasattr(self, "id_tensor"):
1480
+ input_dim = self.in_channels // self.groups
1481
+ kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
1482
+ for i in range(self.in_channels):
1483
+ kernel_value[i, i % input_dim, 1, 1] = 1
1484
+ self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
1485
+ kernel = self.id_tensor
1486
+ running_mean = branch.running_mean
1487
+ running_var = branch.running_var
1488
+ gamma = branch.weight
1489
+ beta = branch.bias
1490
+ eps = branch.eps
1491
+ std = (running_var + eps).sqrt()
1492
+ t = (gamma / std).reshape(-1, 1, 1, 1)
1493
+ return kernel * t, beta - running_mean * gamma / std
1494
+
1495
+ def switch_to_deploy(self):
1496
+ if hasattr(self, "rbr_reparam"):
1497
+ return
1498
+ print(f"RepConv_OREPA.switch_to_deploy")
1499
+ kernel, bias = self.get_equivalent_kernel_bias()
1500
+ self.rbr_reparam = nn.Conv2d(
1501
+ in_channels=self.rbr_dense.in_channels,
1502
+ out_channels=self.rbr_dense.out_channels,
1503
+ kernel_size=self.rbr_dense.kernel_size,
1504
+ stride=self.rbr_dense.stride,
1505
+ padding=self.rbr_dense.padding,
1506
+ dilation=self.rbr_dense.dilation,
1507
+ groups=self.rbr_dense.groups,
1508
+ bias=True,
1509
+ )
1510
+ self.rbr_reparam.weight.data = kernel
1511
+ self.rbr_reparam.bias.data = bias
1512
+ for para in self.parameters():
1513
+ para.detach_()
1514
+ self.__delattr__("rbr_dense")
1515
+ self.__delattr__("rbr_1x1")
1516
+ if hasattr(self, "rbr_identity"):
1517
+ self.__delattr__("rbr_identity")
1518
+
1519
+
1520
+ ##### end of orepa #####
1521
+
1522
+
1523
+ ##### swin transformer #####
1524
+
1525
+
1526
+ class WindowAttention(nn.Module):
1527
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
1528
+
1529
+ super().__init__()
1530
+ self.dim = dim
1531
+ self.window_size = window_size # Wh, Ww
1532
+ self.num_heads = num_heads
1533
+ head_dim = dim // num_heads
1534
+ self.scale = qk_scale or head_dim ** -0.5
1535
+
1536
+ # define a parameter table of relative position bias
1537
+ self.relative_position_bias_table = nn.Parameter(
1538
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
1539
+ ) # 2*Wh-1 * 2*Ww-1, nH
1540
+
1541
+ # get pair-wise relative position index for each token inside the window
1542
+ coords_h = torch.arange(self.window_size[0])
1543
+ coords_w = torch.arange(self.window_size[1])
1544
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
1545
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
1546
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
1547
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
1548
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
1549
+ relative_coords[:, :, 1] += self.window_size[1] - 1
1550
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
1551
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
1552
+ self.register_buffer("relative_position_index", relative_position_index)
1553
+
1554
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
1555
+ self.attn_drop = nn.Dropout(attn_drop)
1556
+ self.proj = nn.Linear(dim, dim)
1557
+ self.proj_drop = nn.Dropout(proj_drop)
1558
+
1559
+ nn.init.normal_(self.relative_position_bias_table, std=0.02)
1560
+ self.softmax = nn.Softmax(dim=-1)
1561
+
1562
+ def forward(self, x, mask=None):
1563
+
1564
+ B_, N, C = x.shape
1565
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
1566
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
1567
+
1568
+ q = q * self.scale
1569
+ attn = q @ k.transpose(-2, -1)
1570
+
1571
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
1572
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
1573
+ ) # Wh*Ww,Wh*Ww,nH
1574
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
1575
+ attn = attn + relative_position_bias.unsqueeze(0)
1576
+
1577
+ if mask is not None:
1578
+ nW = mask.shape[0]
1579
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
1580
+ attn = attn.view(-1, self.num_heads, N, N)
1581
+ attn = self.softmax(attn)
1582
+ else:
1583
+ attn = self.softmax(attn)
1584
+
1585
+ attn = self.attn_drop(attn)
1586
+
1587
+ # print(attn.dtype, v.dtype)
1588
+ try:
1589
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
1590
+ except:
1591
+ # print(attn.dtype, v.dtype)
1592
+ x = (attn.half() @ v).transpose(1, 2).reshape(B_, N, C)
1593
+ x = self.proj(x)
1594
+ x = self.proj_drop(x)
1595
+ return x
1596
+
1597
+
1598
+ class Mlp(nn.Module):
1599
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0):
1600
+ super().__init__()
1601
+ out_features = out_features or in_features
1602
+ hidden_features = hidden_features or in_features
1603
+ self.fc1 = nn.Linear(in_features, hidden_features)
1604
+ self.act = act_layer()
1605
+ self.fc2 = nn.Linear(hidden_features, out_features)
1606
+ self.drop = nn.Dropout(drop)
1607
+
1608
+ def forward(self, x):
1609
+ x = self.fc1(x)
1610
+ x = self.act(x)
1611
+ x = self.drop(x)
1612
+ x = self.fc2(x)
1613
+ x = self.drop(x)
1614
+ return x
1615
+
1616
+
1617
+ def window_partition(x, window_size):
1618
+
1619
+ B, H, W, C = x.shape
1620
+ assert H % window_size == 0, "feature map h and w can not divide by window size"
1621
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
1622
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
1623
+ return windows
1624
+
1625
+
1626
+ def window_reverse(windows, window_size, H, W):
1627
+
1628
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
1629
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
1630
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
1631
+ return x
1632
+
1633
+
1634
+ class SwinTransformerLayer(nn.Module):
1635
+ def __init__(
1636
+ self,
1637
+ dim,
1638
+ num_heads,
1639
+ window_size=8,
1640
+ shift_size=0,
1641
+ mlp_ratio=4.0,
1642
+ qkv_bias=True,
1643
+ qk_scale=None,
1644
+ drop=0.0,
1645
+ attn_drop=0.0,
1646
+ drop_path=0.0,
1647
+ act_layer=nn.SiLU,
1648
+ norm_layer=nn.LayerNorm,
1649
+ ):
1650
+ super().__init__()
1651
+ self.dim = dim
1652
+ self.num_heads = num_heads
1653
+ self.window_size = window_size
1654
+ self.shift_size = shift_size
1655
+ self.mlp_ratio = mlp_ratio
1656
+ # if min(self.input_resolution) <= self.window_size:
1657
+ # # if window size is larger than input resolution, we don't partition windows
1658
+ # self.shift_size = 0
1659
+ # self.window_size = min(self.input_resolution)
1660
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
1661
+
1662
+ self.norm1 = norm_layer(dim)
1663
+ self.attn = WindowAttention(
1664
+ dim,
1665
+ window_size=(self.window_size, self.window_size),
1666
+ num_heads=num_heads,
1667
+ qkv_bias=qkv_bias,
1668
+ qk_scale=qk_scale,
1669
+ attn_drop=attn_drop,
1670
+ proj_drop=drop,
1671
+ )
1672
+
1673
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
1674
+ self.norm2 = norm_layer(dim)
1675
+ mlp_hidden_dim = int(dim * mlp_ratio)
1676
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
1677
+
1678
+ def create_mask(self, H, W):
1679
+ # calculate attention mask for SW-MSA
1680
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
1681
+ h_slices = (
1682
+ slice(0, -self.window_size),
1683
+ slice(-self.window_size, -self.shift_size),
1684
+ slice(-self.shift_size, None),
1685
+ )
1686
+ w_slices = (
1687
+ slice(0, -self.window_size),
1688
+ slice(-self.window_size, -self.shift_size),
1689
+ slice(-self.shift_size, None),
1690
+ )
1691
+ cnt = 0
1692
+ for h in h_slices:
1693
+ for w in w_slices:
1694
+ img_mask[:, h, w, :] = cnt
1695
+ cnt += 1
1696
+
1697
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
1698
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
1699
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
1700
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
1701
+
1702
+ return attn_mask
1703
+
1704
+ def forward(self, x):
1705
+ # reshape x[b c h w] to x[b l c]
1706
+ _, _, H_, W_ = x.shape
1707
+
1708
+ Padding = False
1709
+ if min(H_, W_) < self.window_size or H_ % self.window_size != 0 or W_ % self.window_size != 0:
1710
+ Padding = True
1711
+ # print(f'img_size {min(H_, W_)} is less than (or not divided by) window_size {self.window_size}, Padding.')
1712
+ pad_r = (self.window_size - W_ % self.window_size) % self.window_size
1713
+ pad_b = (self.window_size - H_ % self.window_size) % self.window_size
1714
+ x = F.pad(x, (0, pad_r, 0, pad_b))
1715
+
1716
+ # print('2', x.shape)
1717
+ B, C, H, W = x.shape
1718
+ L = H * W
1719
+ x = x.permute(0, 2, 3, 1).contiguous().view(B, L, C) # b, L, c
1720
+
1721
+ # create mask from init to forward
1722
+ if self.shift_size > 0:
1723
+ attn_mask = self.create_mask(H, W).to(x.device)
1724
+ else:
1725
+ attn_mask = None
1726
+
1727
+ shortcut = x
1728
+ x = self.norm1(x)
1729
+ x = x.view(B, H, W, C)
1730
+
1731
+ # cyclic shift
1732
+ if self.shift_size > 0:
1733
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
1734
+ else:
1735
+ shifted_x = x
1736
+
1737
+ # partition windows
1738
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
1739
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
1740
+
1741
+ # W-MSA/SW-MSA
1742
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
1743
+
1744
+ # merge windows
1745
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
1746
+ shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
1747
+
1748
+ # reverse cyclic shift
1749
+ if self.shift_size > 0:
1750
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
1751
+ else:
1752
+ x = shifted_x
1753
+ x = x.view(B, H * W, C)
1754
+
1755
+ # FFN
1756
+ x = shortcut + self.drop_path(x)
1757
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
1758
+
1759
+ x = x.permute(0, 2, 1).contiguous().view(-1, C, H, W) # b c h w
1760
+
1761
+ if Padding:
1762
+ x = x[:, :, :H_, :W_] # reverse padding
1763
+
1764
+ return x
1765
+
1766
+
1767
+ class SwinTransformerBlock(nn.Module):
1768
+ def __init__(self, c1, c2, num_heads, num_layers, window_size=8):
1769
+ super().__init__()
1770
+ self.conv = None
1771
+ if c1 != c2:
1772
+ self.conv = Conv(c1, c2)
1773
+
1774
+ # remove input_resolution
1775
+ self.blocks = nn.Sequential(
1776
+ *[
1777
+ SwinTransformerLayer(
1778
+ dim=c2,
1779
+ num_heads=num_heads,
1780
+ window_size=window_size,
1781
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
1782
+ )
1783
+ for i in range(num_layers)
1784
+ ]
1785
+ )
1786
+
1787
+ def forward(self, x):
1788
+ if self.conv is not None:
1789
+ x = self.conv(x)
1790
+ x = self.blocks(x)
1791
+ return x
1792
+
1793
+
1794
+ class STCSPA(nn.Module):
1795
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1796
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1797
+ super(STCSPA, self).__init__()
1798
+ c_ = int(c2 * e) # hidden channels
1799
+ self.cv1 = Conv(c1, c_, 1, 1)
1800
+ self.cv2 = Conv(c1, c_, 1, 1)
1801
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
1802
+ num_heads = c_ // 32
1803
+ self.m = SwinTransformerBlock(c_, c_, num_heads, n)
1804
+ # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1805
+
1806
+ def forward(self, x):
1807
+ y1 = self.m(self.cv1(x))
1808
+ y2 = self.cv2(x)
1809
+ return self.cv3(torch.cat((y1, y2), dim=1))
1810
+
1811
+
1812
+ class STCSPB(nn.Module):
1813
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1814
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1815
+ super(STCSPB, self).__init__()
1816
+ c_ = int(c2) # hidden channels
1817
+ self.cv1 = Conv(c1, c_, 1, 1)
1818
+ self.cv2 = Conv(c_, c_, 1, 1)
1819
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
1820
+ num_heads = c_ // 32
1821
+ self.m = SwinTransformerBlock(c_, c_, num_heads, n)
1822
+ # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1823
+
1824
+ def forward(self, x):
1825
+ x1 = self.cv1(x)
1826
+ y1 = self.m(x1)
1827
+ y2 = self.cv2(x1)
1828
+ return self.cv3(torch.cat((y1, y2), dim=1))
1829
+
1830
+
1831
+ class STCSPC(nn.Module):
1832
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1833
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1834
+ super(STCSPC, self).__init__()
1835
+ c_ = int(c2 * e) # hidden channels
1836
+ self.cv1 = Conv(c1, c_, 1, 1)
1837
+ self.cv2 = Conv(c1, c_, 1, 1)
1838
+ self.cv3 = Conv(c_, c_, 1, 1)
1839
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
1840
+ num_heads = c_ // 32
1841
+ self.m = SwinTransformerBlock(c_, c_, num_heads, n)
1842
+ # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1843
+
1844
+ def forward(self, x):
1845
+ y1 = self.cv3(self.m(self.cv1(x)))
1846
+ y2 = self.cv2(x)
1847
+ return self.cv4(torch.cat((y1, y2), dim=1))
1848
+
1849
+
1850
+ ##### end of swin transformer #####
1851
+
1852
+
1853
+ ##### swin transformer v2 #####
1854
+
1855
+
1856
+ class WindowAttention_v2(nn.Module):
1857
+ def __init__(
1858
+ self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0.0, proj_drop=0.0, pretrained_window_size=[0, 0]
1859
+ ):
1860
+
1861
+ super().__init__()
1862
+ self.dim = dim
1863
+ self.window_size = window_size # Wh, Ww
1864
+ self.pretrained_window_size = pretrained_window_size
1865
+ self.num_heads = num_heads
1866
+
1867
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))), requires_grad=True)
1868
+
1869
+ # mlp to generate continuous relative position bias
1870
+ self.cpb_mlp = nn.Sequential(
1871
+ nn.Linear(2, 512, bias=True), nn.ReLU(inplace=True), nn.Linear(512, num_heads, bias=False)
1872
+ )
1873
+
1874
+ # get relative_coords_table
1875
+ relative_coords_h = torch.arange(-(self.window_size[0] - 1), self.window_size[0], dtype=torch.float32)
1876
+ relative_coords_w = torch.arange(-(self.window_size[1] - 1), self.window_size[1], dtype=torch.float32)
1877
+ relative_coords_table = (
1878
+ torch.stack(torch.meshgrid([relative_coords_h, relative_coords_w]))
1879
+ .permute(1, 2, 0)
1880
+ .contiguous()
1881
+ .unsqueeze(0)
1882
+ ) # 1, 2*Wh-1, 2*Ww-1, 2
1883
+ if pretrained_window_size[0] > 0:
1884
+ relative_coords_table[:, :, :, 0] /= pretrained_window_size[0] - 1
1885
+ relative_coords_table[:, :, :, 1] /= pretrained_window_size[1] - 1
1886
+ else:
1887
+ relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1
1888
+ relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1
1889
+ relative_coords_table *= 8 # normalize to -8, 8
1890
+ relative_coords_table = (
1891
+ torch.sign(relative_coords_table) * torch.log2(torch.abs(relative_coords_table) + 1.0) / np.log2(8)
1892
+ )
1893
+
1894
+ self.register_buffer("relative_coords_table", relative_coords_table)
1895
+
1896
+ # get pair-wise relative position index for each token inside the window
1897
+ coords_h = torch.arange(self.window_size[0])
1898
+ coords_w = torch.arange(self.window_size[1])
1899
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
1900
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
1901
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
1902
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
1903
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
1904
+ relative_coords[:, :, 1] += self.window_size[1] - 1
1905
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
1906
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
1907
+ self.register_buffer("relative_position_index", relative_position_index)
1908
+
1909
+ self.qkv = nn.Linear(dim, dim * 3, bias=False)
1910
+ if qkv_bias:
1911
+ self.q_bias = nn.Parameter(torch.zeros(dim))
1912
+ self.v_bias = nn.Parameter(torch.zeros(dim))
1913
+ else:
1914
+ self.q_bias = None
1915
+ self.v_bias = None
1916
+ self.attn_drop = nn.Dropout(attn_drop)
1917
+ self.proj = nn.Linear(dim, dim)
1918
+ self.proj_drop = nn.Dropout(proj_drop)
1919
+ self.softmax = nn.Softmax(dim=-1)
1920
+
1921
+ def forward(self, x, mask=None):
1922
+
1923
+ B_, N, C = x.shape
1924
+ qkv_bias = None
1925
+ if self.q_bias is not None:
1926
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
1927
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
1928
+ qkv = qkv.reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
1929
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
1930
+
1931
+ # cosine attention
1932
+ attn = F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1)
1933
+ logit_scale = torch.clamp(self.logit_scale, max=torch.log(torch.tensor(1.0 / 0.01))).exp()
1934
+ attn = attn * logit_scale
1935
+
1936
+ relative_position_bias_table = self.cpb_mlp(self.relative_coords_table).view(-1, self.num_heads)
1937
+ relative_position_bias = relative_position_bias_table[self.relative_position_index.view(-1)].view(
1938
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
1939
+ ) # Wh*Ww,Wh*Ww,nH
1940
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
1941
+ relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
1942
+ attn = attn + relative_position_bias.unsqueeze(0)
1943
+
1944
+ if mask is not None:
1945
+ nW = mask.shape[0]
1946
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
1947
+ attn = attn.view(-1, self.num_heads, N, N)
1948
+ attn = self.softmax(attn)
1949
+ else:
1950
+ attn = self.softmax(attn)
1951
+
1952
+ attn = self.attn_drop(attn)
1953
+
1954
+ try:
1955
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
1956
+ except:
1957
+ x = (attn.half() @ v).transpose(1, 2).reshape(B_, N, C)
1958
+
1959
+ x = self.proj(x)
1960
+ x = self.proj_drop(x)
1961
+ return x
1962
+
1963
+ def extra_repr(self) -> str:
1964
+ return (
1965
+ f"dim={self.dim}, window_size={self.window_size}, "
1966
+ f"pretrained_window_size={self.pretrained_window_size}, num_heads={self.num_heads}"
1967
+ )
1968
+
1969
+ def flops(self, N):
1970
+ # calculate flops for 1 window with token length of N
1971
+ flops = 0
1972
+ # qkv = self.qkv(x)
1973
+ flops += N * self.dim * 3 * self.dim
1974
+ # attn = (q @ k.transpose(-2, -1))
1975
+ flops += self.num_heads * N * (self.dim // self.num_heads) * N
1976
+ # x = (attn @ v)
1977
+ flops += self.num_heads * N * N * (self.dim // self.num_heads)
1978
+ # x = self.proj(x)
1979
+ flops += N * self.dim * self.dim
1980
+ return flops
1981
+
1982
+
1983
+ class Mlp_v2(nn.Module):
1984
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0):
1985
+ super().__init__()
1986
+ out_features = out_features or in_features
1987
+ hidden_features = hidden_features or in_features
1988
+ self.fc1 = nn.Linear(in_features, hidden_features)
1989
+ self.act = act_layer()
1990
+ self.fc2 = nn.Linear(hidden_features, out_features)
1991
+ self.drop = nn.Dropout(drop)
1992
+
1993
+ def forward(self, x):
1994
+ x = self.fc1(x)
1995
+ x = self.act(x)
1996
+ x = self.drop(x)
1997
+ x = self.fc2(x)
1998
+ x = self.drop(x)
1999
+ return x
2000
+
2001
+
2002
+ def window_partition_v2(x, window_size):
2003
+
2004
+ B, H, W, C = x.shape
2005
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
2006
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
2007
+ return windows
2008
+
2009
+
2010
+ def window_reverse_v2(windows, window_size, H, W):
2011
+
2012
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
2013
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
2014
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
2015
+ return x
2016
+
2017
+
2018
+ class SwinTransformerLayer_v2(nn.Module):
2019
+ def __init__(
2020
+ self,
2021
+ dim,
2022
+ num_heads,
2023
+ window_size=7,
2024
+ shift_size=0,
2025
+ mlp_ratio=4.0,
2026
+ qkv_bias=True,
2027
+ drop=0.0,
2028
+ attn_drop=0.0,
2029
+ drop_path=0.0,
2030
+ act_layer=nn.SiLU,
2031
+ norm_layer=nn.LayerNorm,
2032
+ pretrained_window_size=0,
2033
+ ):
2034
+ super().__init__()
2035
+ self.dim = dim
2036
+ # self.input_resolution = input_resolution
2037
+ self.num_heads = num_heads
2038
+ self.window_size = window_size
2039
+ self.shift_size = shift_size
2040
+ self.mlp_ratio = mlp_ratio
2041
+ # if min(self.input_resolution) <= self.window_size:
2042
+ # # if window size is larger than input resolution, we don't partition windows
2043
+ # self.shift_size = 0
2044
+ # self.window_size = min(self.input_resolution)
2045
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
2046
+
2047
+ self.norm1 = norm_layer(dim)
2048
+ self.attn = WindowAttention_v2(
2049
+ dim,
2050
+ window_size=(self.window_size, self.window_size),
2051
+ num_heads=num_heads,
2052
+ qkv_bias=qkv_bias,
2053
+ attn_drop=attn_drop,
2054
+ proj_drop=drop,
2055
+ pretrained_window_size=(pretrained_window_size, pretrained_window_size),
2056
+ )
2057
+
2058
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
2059
+ self.norm2 = norm_layer(dim)
2060
+ mlp_hidden_dim = int(dim * mlp_ratio)
2061
+ self.mlp = Mlp_v2(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
2062
+
2063
+ def create_mask(self, H, W):
2064
+ # calculate attention mask for SW-MSA
2065
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
2066
+ h_slices = (
2067
+ slice(0, -self.window_size),
2068
+ slice(-self.window_size, -self.shift_size),
2069
+ slice(-self.shift_size, None),
2070
+ )
2071
+ w_slices = (
2072
+ slice(0, -self.window_size),
2073
+ slice(-self.window_size, -self.shift_size),
2074
+ slice(-self.shift_size, None),
2075
+ )
2076
+ cnt = 0
2077
+ for h in h_slices:
2078
+ for w in w_slices:
2079
+ img_mask[:, h, w, :] = cnt
2080
+ cnt += 1
2081
+
2082
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
2083
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
2084
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
2085
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
2086
+
2087
+ return attn_mask
2088
+
2089
+ def forward(self, x):
2090
+ # reshape x[b c h w] to x[b l c]
2091
+ _, _, H_, W_ = x.shape
2092
+
2093
+ Padding = False
2094
+ if min(H_, W_) < self.window_size or H_ % self.window_size != 0 or W_ % self.window_size != 0:
2095
+ Padding = True
2096
+ # print(f'img_size {min(H_, W_)} is less than (or not divided by) window_size {self.window_size}, Padding.')
2097
+ pad_r = (self.window_size - W_ % self.window_size) % self.window_size
2098
+ pad_b = (self.window_size - H_ % self.window_size) % self.window_size
2099
+ x = F.pad(x, (0, pad_r, 0, pad_b))
2100
+
2101
+ # print('2', x.shape)
2102
+ B, C, H, W = x.shape
2103
+ L = H * W
2104
+ x = x.permute(0, 2, 3, 1).contiguous().view(B, L, C) # b, L, c
2105
+
2106
+ # create mask from init to forward
2107
+ if self.shift_size > 0:
2108
+ attn_mask = self.create_mask(H, W).to(x.device)
2109
+ else:
2110
+ attn_mask = None
2111
+
2112
+ shortcut = x
2113
+ x = x.view(B, H, W, C)
2114
+
2115
+ # cyclic shift
2116
+ if self.shift_size > 0:
2117
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
2118
+ else:
2119
+ shifted_x = x
2120
+
2121
+ # partition windows
2122
+ x_windows = window_partition_v2(shifted_x, self.window_size) # nW*B, window_size, window_size, C
2123
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
2124
+
2125
+ # W-MSA/SW-MSA
2126
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
2127
+
2128
+ # merge windows
2129
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
2130
+ shifted_x = window_reverse_v2(attn_windows, self.window_size, H, W) # B H' W' C
2131
+
2132
+ # reverse cyclic shift
2133
+ if self.shift_size > 0:
2134
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
2135
+ else:
2136
+ x = shifted_x
2137
+ x = x.view(B, H * W, C)
2138
+ x = shortcut + self.drop_path(self.norm1(x))
2139
+
2140
+ # FFN
2141
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
2142
+ x = x.permute(0, 2, 1).contiguous().view(-1, C, H, W) # b c h w
2143
+
2144
+ if Padding:
2145
+ x = x[:, :, :H_, :W_] # reverse padding
2146
+
2147
+ return x
2148
+
2149
+ def extra_repr(self) -> str:
2150
+ return (
2151
+ f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, "
2152
+ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
2153
+ )
2154
+
2155
+ def flops(self):
2156
+ flops = 0
2157
+ H, W = self.input_resolution
2158
+ # norm1
2159
+ flops += self.dim * H * W
2160
+ # W-MSA/SW-MSA
2161
+ nW = H * W / self.window_size / self.window_size
2162
+ flops += nW * self.attn.flops(self.window_size * self.window_size)
2163
+ # mlp
2164
+ flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
2165
+ # norm2
2166
+ flops += self.dim * H * W
2167
+ return flops
2168
+
2169
+
2170
+ class SwinTransformer2Block(nn.Module):
2171
+ def __init__(self, c1, c2, num_heads, num_layers, window_size=7):
2172
+ super().__init__()
2173
+ self.conv = None
2174
+ if c1 != c2:
2175
+ self.conv = Conv(c1, c2)
2176
+
2177
+ # remove input_resolution
2178
+ self.blocks = nn.Sequential(
2179
+ *[
2180
+ SwinTransformerLayer_v2(
2181
+ dim=c2,
2182
+ num_heads=num_heads,
2183
+ window_size=window_size,
2184
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
2185
+ )
2186
+ for i in range(num_layers)
2187
+ ]
2188
+ )
2189
+
2190
+ def forward(self, x):
2191
+ if self.conv is not None:
2192
+ x = self.conv(x)
2193
+ x = self.blocks(x)
2194
+ return x
2195
+
2196
+
2197
+ class ST2CSPA(nn.Module):
2198
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
2199
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
2200
+ super(ST2CSPA, self).__init__()
2201
+ c_ = int(c2 * e) # hidden channels
2202
+ self.cv1 = Conv(c1, c_, 1, 1)
2203
+ self.cv2 = Conv(c1, c_, 1, 1)
2204
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
2205
+ num_heads = c_ // 32
2206
+ self.m = SwinTransformer2Block(c_, c_, num_heads, n)
2207
+ # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
2208
+
2209
+ def forward(self, x):
2210
+ y1 = self.m(self.cv1(x))
2211
+ y2 = self.cv2(x)
2212
+ return self.cv3(torch.cat((y1, y2), dim=1))
2213
+
2214
+
2215
+ class ST2CSPB(nn.Module):
2216
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
2217
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
2218
+ super(ST2CSPB, self).__init__()
2219
+ c_ = int(c2) # hidden channels
2220
+ self.cv1 = Conv(c1, c_, 1, 1)
2221
+ self.cv2 = Conv(c_, c_, 1, 1)
2222
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
2223
+ num_heads = c_ // 32
2224
+ self.m = SwinTransformer2Block(c_, c_, num_heads, n)
2225
+ # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
2226
+
2227
+ def forward(self, x):
2228
+ x1 = self.cv1(x)
2229
+ y1 = self.m(x1)
2230
+ y2 = self.cv2(x1)
2231
+ return self.cv3(torch.cat((y1, y2), dim=1))
2232
+
2233
+
2234
+ class ST2CSPC(nn.Module):
2235
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
2236
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
2237
+ super(ST2CSPC, self).__init__()
2238
+ c_ = int(c2 * e) # hidden channels
2239
+ self.cv1 = Conv(c1, c_, 1, 1)
2240
+ self.cv2 = Conv(c1, c_, 1, 1)
2241
+ self.cv3 = Conv(c_, c_, 1, 1)
2242
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
2243
+ num_heads = c_ // 32
2244
+ self.m = SwinTransformer2Block(c_, c_, num_heads, n)
2245
+ # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
2246
+
2247
+ def forward(self, x):
2248
+ y1 = self.cv3(self.m(self.cv1(x)))
2249
+ y2 = self.cv2(x)
2250
+ return self.cv4(torch.cat((y1, y2), dim=1))
2251
+
2252
+
2253
+ ##### end of swin transformer v2 #####
yolov7detect/models/experimental.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import random
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from yolov7.models.common import Conv, DWConv
7
+ from yolov7.utils.google_utils import attempt_download, attempt_download_from_hub
8
+
9
+
10
+ class CrossConv(nn.Module):
11
+ # Cross Convolution Downsample
12
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
13
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
14
+ super(CrossConv, self).__init__()
15
+ c_ = int(c2 * e) # hidden channels
16
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
17
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
18
+ self.add = shortcut and c1 == c2
19
+
20
+ def forward(self, x):
21
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
22
+
23
+
24
+ class Sum(nn.Module):
25
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
26
+ def __init__(self, n, weight=False): # n: number of inputs
27
+ super(Sum, self).__init__()
28
+ self.weight = weight # apply weights boolean
29
+ self.iter = range(n - 1) # iter object
30
+ if weight:
31
+ self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
32
+
33
+ def forward(self, x):
34
+ y = x[0] # no weight
35
+ if self.weight:
36
+ w = torch.sigmoid(self.w) * 2
37
+ for i in self.iter:
38
+ y = y + x[i + 1] * w[i]
39
+ else:
40
+ for i in self.iter:
41
+ y = y + x[i + 1]
42
+ return y
43
+
44
+
45
+ class MixConv2d(nn.Module):
46
+ # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
47
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
48
+ super(MixConv2d, self).__init__()
49
+ groups = len(k)
50
+ if equal_ch: # equal c_ per group
51
+ i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
52
+ c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
53
+ else: # equal weight.numel() per group
54
+ b = [c2] + [0] * groups
55
+ a = np.eye(groups + 1, groups, k=-1)
56
+ a -= np.roll(a, 1, axis=1)
57
+ a *= np.array(k) ** 2
58
+ a[0] = 1
59
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
60
+
61
+ self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
62
+ self.bn = nn.BatchNorm2d(c2)
63
+ self.act = nn.LeakyReLU(0.1, inplace=True)
64
+
65
+ def forward(self, x):
66
+ return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
67
+
68
+
69
+ class Ensemble(nn.ModuleList):
70
+ # Ensemble of models
71
+ def __init__(self):
72
+ super(Ensemble, self).__init__()
73
+
74
+ def forward(self, x, augment=False):
75
+ y = []
76
+ for module in self:
77
+ y.append(module(x, augment)[0])
78
+ # y = torch.stack(y).max(0)[0] # max ensemble
79
+ # y = torch.stack(y).mean(0) # mean ensemble
80
+ y = torch.cat(y, 1) # nms ensemble
81
+ return y, None # inference, train output
82
+
83
+
84
+
85
+
86
+
87
+ class ORT_NMS(torch.autograd.Function):
88
+ '''ONNX-Runtime NMS operation'''
89
+ @staticmethod
90
+ def forward(ctx,
91
+ boxes,
92
+ scores,
93
+ max_output_boxes_per_class=torch.tensor([100]),
94
+ iou_threshold=torch.tensor([0.45]),
95
+ score_threshold=torch.tensor([0.25])):
96
+ device = boxes.device
97
+ batch = scores.shape[0]
98
+ num_det = random.randint(0, 100)
99
+ batches = torch.randint(0, batch, (num_det,)).sort()[0].to(device)
100
+ idxs = torch.arange(100, 100 + num_det).to(device)
101
+ zeros = torch.zeros((num_det,), dtype=torch.int64).to(device)
102
+ selected_indices = torch.cat([batches[None], zeros[None], idxs[None]], 0).T.contiguous()
103
+ selected_indices = selected_indices.to(torch.int64)
104
+ return selected_indices
105
+
106
+ @staticmethod
107
+ def symbolic(g, boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold):
108
+ return g.op("NonMaxSuppression", boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold)
109
+
110
+
111
+ class TRT_NMS(torch.autograd.Function):
112
+ '''TensorRT NMS operation'''
113
+ @staticmethod
114
+ def forward(
115
+ ctx,
116
+ boxes,
117
+ scores,
118
+ background_class=-1,
119
+ box_coding=1,
120
+ iou_threshold=0.45,
121
+ max_output_boxes=100,
122
+ plugin_version="1",
123
+ score_activation=0,
124
+ score_threshold=0.25,
125
+ ):
126
+ batch_size, num_boxes, num_classes = scores.shape
127
+ num_det = torch.randint(0, max_output_boxes, (batch_size, 1), dtype=torch.int32)
128
+ det_boxes = torch.randn(batch_size, max_output_boxes, 4)
129
+ det_scores = torch.randn(batch_size, max_output_boxes)
130
+ det_classes = torch.randint(0, num_classes, (batch_size, max_output_boxes), dtype=torch.int32)
131
+ return num_det, det_boxes, det_scores, det_classes
132
+
133
+ @staticmethod
134
+ def symbolic(g,
135
+ boxes,
136
+ scores,
137
+ background_class=-1,
138
+ box_coding=1,
139
+ iou_threshold=0.45,
140
+ max_output_boxes=100,
141
+ plugin_version="1",
142
+ score_activation=0,
143
+ score_threshold=0.25):
144
+ out = g.op("TRT::EfficientNMS_TRT",
145
+ boxes,
146
+ scores,
147
+ background_class_i=background_class,
148
+ box_coding_i=box_coding,
149
+ iou_threshold_f=iou_threshold,
150
+ max_output_boxes_i=max_output_boxes,
151
+ plugin_version_s=plugin_version,
152
+ score_activation_i=score_activation,
153
+ score_threshold_f=score_threshold,
154
+ outputs=4)
155
+ nums, boxes, scores, classes = out
156
+ return nums, boxes, scores, classes
157
+
158
+
159
+ class ONNX_ORT(nn.Module):
160
+ '''onnx module with ONNX-Runtime NMS operation.'''
161
+ def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=640, device=None, n_classes=80):
162
+ super().__init__()
163
+ self.device = device if device else torch.device("cpu")
164
+ self.max_obj = torch.tensor([max_obj]).to(device)
165
+ self.iou_threshold = torch.tensor([iou_thres]).to(device)
166
+ self.score_threshold = torch.tensor([score_thres]).to(device)
167
+ self.max_wh = max_wh # if max_wh != 0 : non-agnostic else : agnostic
168
+ self.convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
169
+ dtype=torch.float32,
170
+ device=self.device)
171
+ self.n_classes=n_classes
172
+
173
+ def forward(self, x):
174
+ boxes = x[:, :, :4]
175
+ conf = x[:, :, 4:5]
176
+ scores = x[:, :, 5:]
177
+ if self.n_classes == 1:
178
+ scores = conf # for models with one class, cls_loss is 0 and cls_conf is always 0.5,
179
+ # so there is no need to multiplicate.
180
+ else:
181
+ scores *= conf # conf = obj_conf * cls_conf
182
+ boxes @= self.convert_matrix
183
+ max_score, category_id = scores.max(2, keepdim=True)
184
+ dis = category_id.float() * self.max_wh
185
+ nmsbox = boxes + dis
186
+ max_score_tp = max_score.transpose(1, 2).contiguous()
187
+ selected_indices = ORT_NMS.apply(nmsbox, max_score_tp, self.max_obj, self.iou_threshold, self.score_threshold)
188
+ X, Y = selected_indices[:, 0], selected_indices[:, 2]
189
+ selected_boxes = boxes[X, Y, :]
190
+ selected_categories = category_id[X, Y, :].float()
191
+ selected_scores = max_score[X, Y, :]
192
+ X = X.unsqueeze(1).float()
193
+ return torch.cat([X, selected_boxes, selected_categories, selected_scores], 1)
194
+
195
+ class ONNX_TRT(nn.Module):
196
+ '''onnx module with TensorRT NMS operation.'''
197
+ def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None ,device=None, n_classes=80):
198
+ super().__init__()
199
+ assert max_wh is None
200
+ self.device = device if device else torch.device('cpu')
201
+ self.background_class = -1,
202
+ self.box_coding = 1,
203
+ self.iou_threshold = iou_thres
204
+ self.max_obj = max_obj
205
+ self.plugin_version = '1'
206
+ self.score_activation = 0
207
+ self.score_threshold = score_thres
208
+ self.n_classes=n_classes
209
+
210
+ def forward(self, x):
211
+ boxes = x[:, :, :4]
212
+ conf = x[:, :, 4:5]
213
+ scores = x[:, :, 5:]
214
+ if self.n_classes == 1:
215
+ scores = conf # for models with one class, cls_loss is 0 and cls_conf is always 0.5,
216
+ # so there is no need to multiplicate.
217
+ else:
218
+ scores *= conf # conf = obj_conf * cls_conf
219
+ num_det, det_boxes, det_scores, det_classes = TRT_NMS.apply(boxes, scores, self.background_class, self.box_coding,
220
+ self.iou_threshold, self.max_obj,
221
+ self.plugin_version, self.score_activation,
222
+ self.score_threshold)
223
+ return num_det, det_boxes, det_scores, det_classes
224
+
225
+
226
+ class End2End(nn.Module):
227
+ '''export onnx or tensorrt model with NMS operation.'''
228
+ def __init__(self, model, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None, device=None, n_classes=80):
229
+ super().__init__()
230
+ device = device if device else torch.device('cpu')
231
+ assert isinstance(max_wh,(int)) or max_wh is None
232
+ self.model = model.to(device)
233
+ self.model.model[-1].end2end = True
234
+ self.patch_model = ONNX_TRT if max_wh is None else ONNX_ORT
235
+ self.end2end = self.patch_model(max_obj, iou_thres, score_thres, max_wh, device, n_classes)
236
+ self.end2end.eval()
237
+
238
+ def forward(self, x):
239
+ x = self.model(x)
240
+ x = self.end2end(x)
241
+ return x
242
+
243
+
244
+ def attempt_load(weights, map_location=None):
245
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
246
+ model = Ensemble()
247
+ for w in weights if isinstance(weights, list) else [weights]:
248
+ ckpt = torch.load(weights, map_location=map_location) # load
249
+ model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
250
+
251
+ # Compatibility updates
252
+ for m in model.modules():
253
+ if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
254
+ m.inplace = True # pytorch 1.7.0 compatibility
255
+ elif type(m) is nn.Upsample:
256
+ m.recompute_scale_factor = None # torch 1.11.0 compatibility
257
+ elif type(m) is Conv:
258
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
259
+
260
+ if len(model) == 1:
261
+ return model[-1] # return model
262
+ else:
263
+ print('Ensemble created with %s\n' % weights)
264
+ for k in ['names', 'stride']:
265
+ setattr(model, k, getattr(model[-1], k))
266
+ return model # return ensemble
267
+
268
+
yolov7detect/models/yolo.py ADDED
@@ -0,0 +1,843 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import sys
4
+ from copy import deepcopy
5
+
6
+ sys.path.append('./') # to run '$ python *.py' files in subdirectories
7
+ logger = logging.getLogger(__name__)
8
+ import torch
9
+ from yolov7.models.common import *
10
+ from yolov7.models.experimental import *
11
+ from yolov7.utils.autoanchor import check_anchor_order
12
+ from yolov7.utils.general import make_divisible, check_file, set_logging
13
+ from yolov7.utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \
14
+ select_device, copy_attr
15
+ from yolov7.utils.loss import SigmoidBin
16
+
17
+ try:
18
+ import thop # for FLOPS computation
19
+ except ImportError:
20
+ thop = None
21
+
22
+
23
+ class Detect(nn.Module):
24
+ stride = None # strides computed during build
25
+ export = False # onnx export
26
+ end2end = False
27
+ include_nms = False
28
+ concat = False
29
+
30
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
31
+ super(Detect, self).__init__()
32
+ self.nc = nc # number of classes
33
+ self.no = nc + 5 # number of outputs per anchor
34
+ self.nl = len(anchors) # number of detection layers
35
+ self.na = len(anchors[0]) // 2 # number of anchors
36
+ self.grid = [torch.zeros(1)] * self.nl # init grid
37
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
38
+ self.register_buffer('anchors', a) # shape(nl,na,2)
39
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
40
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
41
+
42
+ def forward(self, x):
43
+ # x = x.copy() # for profiling
44
+ z = [] # inference output
45
+ self.training |= self.export
46
+ for i in range(self.nl):
47
+ x[i] = self.m[i](x[i]) # conv
48
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
49
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
50
+
51
+ if not self.training: # inference
52
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
53
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
54
+ y = x[i].sigmoid()
55
+ if not torch.onnx.is_in_onnx_export():
56
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
57
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
58
+ else:
59
+ xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
60
+ xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy
61
+ wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh
62
+ y = torch.cat((xy, wh, conf), 4)
63
+ z.append(y.view(bs, -1, self.no))
64
+
65
+ if self.training:
66
+ out = x
67
+ elif self.end2end:
68
+ out = torch.cat(z, 1)
69
+ elif self.include_nms:
70
+ z = self.convert(z)
71
+ out = (z, )
72
+ elif self.concat:
73
+ out = torch.cat(z, 1)
74
+ else:
75
+ out = (torch.cat(z, 1), x)
76
+
77
+ return out
78
+
79
+ @staticmethod
80
+ def _make_grid(nx=20, ny=20):
81
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
82
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
83
+
84
+ def convert(self, z):
85
+ z = torch.cat(z, 1)
86
+ box = z[:, :, :4]
87
+ conf = z[:, :, 4:5]
88
+ score = z[:, :, 5:]
89
+ score *= conf
90
+ convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
91
+ dtype=torch.float32,
92
+ device=z.device)
93
+ box @= convert_matrix
94
+ return (box, score)
95
+
96
+
97
+ class IDetect(nn.Module):
98
+ stride = None # strides computed during build
99
+ export = False # onnx export
100
+ end2end = False
101
+ include_nms = False
102
+ concat = False
103
+
104
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
105
+ super(IDetect, self).__init__()
106
+ self.nc = nc # number of classes
107
+ self.no = nc + 5 # number of outputs per anchor
108
+ self.nl = len(anchors) # number of detection layers
109
+ self.na = len(anchors[0]) // 2 # number of anchors
110
+ self.grid = [torch.zeros(1)] * self.nl # init grid
111
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
112
+ self.register_buffer('anchors', a) # shape(nl,na,2)
113
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
114
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
115
+
116
+ self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
117
+ self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
118
+
119
+ def forward(self, x):
120
+ # x = x.copy() # for profiling
121
+ z = [] # inference output
122
+ self.training |= self.export
123
+ for i in range(self.nl):
124
+ x[i] = self.m[i](self.ia[i](x[i])) # conv
125
+ x[i] = self.im[i](x[i])
126
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
127
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
128
+
129
+ if not self.training: # inference
130
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
131
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
132
+
133
+ y = x[i].sigmoid()
134
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
135
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
136
+ z.append(y.view(bs, -1, self.no))
137
+
138
+ return x if self.training else (torch.cat(z, 1), x)
139
+
140
+ def fuseforward(self, x):
141
+ # x = x.copy() # for profiling
142
+ z = [] # inference output
143
+ self.training |= self.export
144
+ for i in range(self.nl):
145
+ x[i] = self.m[i](x[i]) # conv
146
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
147
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
148
+
149
+ if not self.training: # inference
150
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
151
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
152
+
153
+ y = x[i].sigmoid()
154
+ if not torch.onnx.is_in_onnx_export():
155
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
156
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
157
+ else:
158
+ xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
159
+ xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy
160
+ wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh
161
+ y = torch.cat((xy, wh, conf), 4)
162
+ z.append(y.view(bs, -1, self.no))
163
+
164
+ if self.training:
165
+ out = x
166
+ elif self.end2end:
167
+ out = torch.cat(z, 1)
168
+ elif self.include_nms:
169
+ z = self.convert(z)
170
+ out = (z, )
171
+ elif self.concat:
172
+ out = torch.cat(z, 1)
173
+ else:
174
+ out = (torch.cat(z, 1), x)
175
+
176
+ return out
177
+
178
+ def fuse(self):
179
+ print("IDetect.fuse")
180
+ # fuse ImplicitA and Convolution
181
+ for i in range(len(self.m)):
182
+ c1,c2,_,_ = self.m[i].weight.shape
183
+ c1_,c2_, _,_ = self.ia[i].implicit.shape
184
+ self.m[i].bias += torch.matmul(self.m[i].weight.reshape(c1,c2),self.ia[i].implicit.reshape(c2_,c1_)).squeeze(1)
185
+
186
+ # fuse ImplicitM and Convolution
187
+ for i in range(len(self.m)):
188
+ c1,c2, _,_ = self.im[i].implicit.shape
189
+ self.m[i].bias *= self.im[i].implicit.reshape(c2)
190
+ self.m[i].weight *= self.im[i].implicit.transpose(0,1)
191
+
192
+ @staticmethod
193
+ def _make_grid(nx=20, ny=20):
194
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
195
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
196
+
197
+ def convert(self, z):
198
+ z = torch.cat(z, 1)
199
+ box = z[:, :, :4]
200
+ conf = z[:, :, 4:5]
201
+ score = z[:, :, 5:]
202
+ score *= conf
203
+ convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
204
+ dtype=torch.float32,
205
+ device=z.device)
206
+ box @= convert_matrix
207
+ return (box, score)
208
+
209
+
210
+ class IKeypoint(nn.Module):
211
+ stride = None # strides computed during build
212
+ export = False # onnx export
213
+
214
+ def __init__(self, nc=80, anchors=(), nkpt=17, ch=(), inplace=True, dw_conv_kpt=False): # detection layer
215
+ super(IKeypoint, self).__init__()
216
+ self.nc = nc # number of classes
217
+ self.nkpt = nkpt
218
+ self.dw_conv_kpt = dw_conv_kpt
219
+ self.no_det=(nc + 5) # number of outputs per anchor for box and class
220
+ self.no_kpt = 3*self.nkpt ## number of outputs per anchor for keypoints
221
+ self.no = self.no_det+self.no_kpt
222
+ self.nl = len(anchors) # number of detection layers
223
+ self.na = len(anchors[0]) // 2 # number of anchors
224
+ self.grid = [torch.zeros(1)] * self.nl # init grid
225
+ self.flip_test = False
226
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
227
+ self.register_buffer('anchors', a) # shape(nl,na,2)
228
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
229
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no_det * self.na, 1) for x in ch) # output conv
230
+
231
+ self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
232
+ self.im = nn.ModuleList(ImplicitM(self.no_det * self.na) for _ in ch)
233
+
234
+ if self.nkpt is not None:
235
+ if self.dw_conv_kpt: #keypoint head is slightly more complex
236
+ self.m_kpt = nn.ModuleList(
237
+ nn.Sequential(DWConv(x, x, k=3), Conv(x,x),
238
+ DWConv(x, x, k=3), Conv(x, x),
239
+ DWConv(x, x, k=3), Conv(x,x),
240
+ DWConv(x, x, k=3), Conv(x, x),
241
+ DWConv(x, x, k=3), Conv(x, x),
242
+ DWConv(x, x, k=3), nn.Conv2d(x, self.no_kpt * self.na, 1)) for x in ch)
243
+ else: #keypoint head is a single convolution
244
+ self.m_kpt = nn.ModuleList(nn.Conv2d(x, self.no_kpt * self.na, 1) for x in ch)
245
+
246
+ self.inplace = inplace # use in-place ops (e.g. slice assignment)
247
+
248
+ def forward(self, x):
249
+ # x = x.copy() # for profiling
250
+ z = [] # inference output
251
+ self.training |= self.export
252
+ for i in range(self.nl):
253
+ if self.nkpt is None or self.nkpt==0:
254
+ x[i] = self.im[i](self.m[i](self.ia[i](x[i]))) # conv
255
+ else :
256
+ x[i] = torch.cat((self.im[i](self.m[i](self.ia[i](x[i]))), self.m_kpt[i](x[i])), axis=1)
257
+
258
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
259
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
260
+ x_det = x[i][..., :6]
261
+ x_kpt = x[i][..., 6:]
262
+
263
+ if not self.training: # inference
264
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
265
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
266
+ kpt_grid_x = self.grid[i][..., 0:1]
267
+ kpt_grid_y = self.grid[i][..., 1:2]
268
+
269
+ if self.nkpt == 0:
270
+ y = x[i].sigmoid()
271
+ else:
272
+ y = x_det.sigmoid()
273
+
274
+ if self.inplace:
275
+ xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
276
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh
277
+ if self.nkpt != 0:
278
+ x_kpt[..., 0::3] = (x_kpt[..., ::3] * 2. - 0.5 + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy
279
+ x_kpt[..., 1::3] = (x_kpt[..., 1::3] * 2. - 0.5 + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy
280
+ #x_kpt[..., 0::3] = (x_kpt[..., ::3] + kpt_grid_x.repeat(1,1,1,1,17)) * self.stride[i] # xy
281
+ #x_kpt[..., 1::3] = (x_kpt[..., 1::3] + kpt_grid_y.repeat(1,1,1,1,17)) * self.stride[i] # xy
282
+ #print('=============')
283
+ #print(self.anchor_grid[i].shape)
284
+ #print(self.anchor_grid[i][...,0].unsqueeze(4).shape)
285
+ #print(x_kpt[..., 0::3].shape)
286
+ #x_kpt[..., 0::3] = ((x_kpt[..., 0::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy
287
+ #x_kpt[..., 1::3] = ((x_kpt[..., 1::3].tanh() * 2.) ** 3 * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy
288
+ #x_kpt[..., 0::3] = (((x_kpt[..., 0::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,0].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_x.repeat(1,1,1,1,17) * self.stride[i] # xy
289
+ #x_kpt[..., 1::3] = (((x_kpt[..., 1::3].sigmoid() * 4.) ** 2 - 8.) * self.anchor_grid[i][...,1].unsqueeze(4).repeat(1,1,1,1,self.nkpt)) + kpt_grid_y.repeat(1,1,1,1,17) * self.stride[i] # xy
290
+ x_kpt[..., 2::3] = x_kpt[..., 2::3].sigmoid()
291
+
292
+ y = torch.cat((xy, wh, y[..., 4:], x_kpt), dim = -1)
293
+
294
+ else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
295
+ xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
296
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
297
+ if self.nkpt != 0:
298
+ y[..., 6:] = (y[..., 6:] * 2. - 0.5 + self.grid[i].repeat((1,1,1,1,self.nkpt))) * self.stride[i] # xy
299
+ y = torch.cat((xy, wh, y[..., 4:]), -1)
300
+
301
+ z.append(y.view(bs, -1, self.no))
302
+
303
+ return x if self.training else (torch.cat(z, 1), x)
304
+
305
+ @staticmethod
306
+ def _make_grid(nx=20, ny=20):
307
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
308
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
309
+
310
+
311
+ class IAuxDetect(nn.Module):
312
+ stride = None # strides computed during build
313
+ export = False # onnx export
314
+ end2end = False
315
+ include_nms = False
316
+ concat = False
317
+
318
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
319
+ super(IAuxDetect, self).__init__()
320
+ self.nc = nc # number of classes
321
+ self.no = nc + 5 # number of outputs per anchor
322
+ self.nl = len(anchors) # number of detection layers
323
+ self.na = len(anchors[0]) // 2 # number of anchors
324
+ self.grid = [torch.zeros(1)] * self.nl # init grid
325
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
326
+ self.register_buffer('anchors', a) # shape(nl,na,2)
327
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
328
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[:self.nl]) # output conv
329
+ self.m2 = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch[self.nl:]) # output conv
330
+
331
+ self.ia = nn.ModuleList(ImplicitA(x) for x in ch[:self.nl])
332
+ self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch[:self.nl])
333
+
334
+ def forward(self, x):
335
+ # x = x.copy() # for profiling
336
+ z = [] # inference output
337
+ self.training |= self.export
338
+ for i in range(self.nl):
339
+ x[i] = self.m[i](self.ia[i](x[i])) # conv
340
+ x[i] = self.im[i](x[i])
341
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
342
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
343
+
344
+ x[i+self.nl] = self.m2[i](x[i+self.nl])
345
+ x[i+self.nl] = x[i+self.nl].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
346
+
347
+ if not self.training: # inference
348
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
349
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
350
+
351
+ y = x[i].sigmoid()
352
+ if not torch.onnx.is_in_onnx_export():
353
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
354
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
355
+ else:
356
+ xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
357
+ xy = xy * (2. * self.stride[i]) + (self.stride[i] * (self.grid[i] - 0.5)) # new xy
358
+ wh = wh ** 2 * (4 * self.anchor_grid[i].data) # new wh
359
+ y = torch.cat((xy, wh, conf), 4)
360
+ z.append(y.view(bs, -1, self.no))
361
+
362
+ return x if self.training else (torch.cat(z, 1), x[:self.nl])
363
+
364
+ def fuseforward(self, x):
365
+ # x = x.copy() # for profiling
366
+ z = [] # inference output
367
+ self.training |= self.export
368
+ for i in range(self.nl):
369
+ x[i] = self.m[i](x[i]) # conv
370
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
371
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
372
+
373
+ if not self.training: # inference
374
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
375
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
376
+
377
+ y = x[i].sigmoid()
378
+ if not torch.onnx.is_in_onnx_export():
379
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
380
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
381
+ else:
382
+ xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
383
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].data # wh
384
+ y = torch.cat((xy, wh, y[..., 4:]), -1)
385
+ z.append(y.view(bs, -1, self.no))
386
+
387
+ if self.training:
388
+ out = x
389
+ elif self.end2end:
390
+ out = torch.cat(z, 1)
391
+ elif self.include_nms:
392
+ z = self.convert(z)
393
+ out = (z, )
394
+ elif self.concat:
395
+ out = torch.cat(z, 1)
396
+ else:
397
+ out = (torch.cat(z, 1), x)
398
+
399
+ return out
400
+
401
+ def fuse(self):
402
+ print("IAuxDetect.fuse")
403
+ # fuse ImplicitA and Convolution
404
+ for i in range(len(self.m)):
405
+ c1,c2,_,_ = self.m[i].weight.shape
406
+ c1_,c2_, _,_ = self.ia[i].implicit.shape
407
+ self.m[i].bias += torch.matmul(self.m[i].weight.reshape(c1,c2),self.ia[i].implicit.reshape(c2_,c1_)).squeeze(1)
408
+
409
+ # fuse ImplicitM and Convolution
410
+ for i in range(len(self.m)):
411
+ c1,c2, _,_ = self.im[i].implicit.shape
412
+ self.m[i].bias *= self.im[i].implicit.reshape(c2)
413
+ self.m[i].weight *= self.im[i].implicit.transpose(0,1)
414
+
415
+ @staticmethod
416
+ def _make_grid(nx=20, ny=20):
417
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
418
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
419
+
420
+ def convert(self, z):
421
+ z = torch.cat(z, 1)
422
+ box = z[:, :, :4]
423
+ conf = z[:, :, 4:5]
424
+ score = z[:, :, 5:]
425
+ score *= conf
426
+ convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
427
+ dtype=torch.float32,
428
+ device=z.device)
429
+ box @= convert_matrix
430
+ return (box, score)
431
+
432
+
433
+ class IBin(nn.Module):
434
+ stride = None # strides computed during build
435
+ export = False # onnx export
436
+
437
+ def __init__(self, nc=80, anchors=(), ch=(), bin_count=21): # detection layer
438
+ super(IBin, self).__init__()
439
+ self.nc = nc # number of classes
440
+ self.bin_count = bin_count
441
+
442
+ self.w_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
443
+ self.h_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
444
+ # classes, x,y,obj
445
+ self.no = nc + 3 + \
446
+ self.w_bin_sigmoid.get_length() + self.h_bin_sigmoid.get_length() # w-bce, h-bce
447
+ # + self.x_bin_sigmoid.get_length() + self.y_bin_sigmoid.get_length()
448
+
449
+ self.nl = len(anchors) # number of detection layers
450
+ self.na = len(anchors[0]) // 2 # number of anchors
451
+ self.grid = [torch.zeros(1)] * self.nl # init grid
452
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
453
+ self.register_buffer('anchors', a) # shape(nl,na,2)
454
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
455
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
456
+
457
+ self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
458
+ self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
459
+
460
+ def forward(self, x):
461
+
462
+ #self.x_bin_sigmoid.use_fw_regression = True
463
+ #self.y_bin_sigmoid.use_fw_regression = True
464
+ self.w_bin_sigmoid.use_fw_regression = True
465
+ self.h_bin_sigmoid.use_fw_regression = True
466
+
467
+ # x = x.copy() # for profiling
468
+ z = [] # inference output
469
+ self.training |= self.export
470
+ for i in range(self.nl):
471
+ x[i] = self.m[i](self.ia[i](x[i])) # conv
472
+ x[i] = self.im[i](x[i])
473
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
474
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
475
+
476
+ if not self.training: # inference
477
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
478
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
479
+
480
+ y = x[i].sigmoid()
481
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
482
+ #y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
483
+
484
+
485
+ #px = (self.x_bin_sigmoid.forward(y[..., 0:12]) + self.grid[i][..., 0]) * self.stride[i]
486
+ #py = (self.y_bin_sigmoid.forward(y[..., 12:24]) + self.grid[i][..., 1]) * self.stride[i]
487
+
488
+ pw = self.w_bin_sigmoid.forward(y[..., 2:24]) * self.anchor_grid[i][..., 0]
489
+ ph = self.h_bin_sigmoid.forward(y[..., 24:46]) * self.anchor_grid[i][..., 1]
490
+
491
+ #y[..., 0] = px
492
+ #y[..., 1] = py
493
+ y[..., 2] = pw
494
+ y[..., 3] = ph
495
+
496
+ y = torch.cat((y[..., 0:4], y[..., 46:]), dim=-1)
497
+
498
+ z.append(y.view(bs, -1, y.shape[-1]))
499
+
500
+ return x if self.training else (torch.cat(z, 1), x)
501
+
502
+ @staticmethod
503
+ def _make_grid(nx=20, ny=20):
504
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
505
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
506
+
507
+
508
+ class Model(nn.Module):
509
+ def __init__(self, cfg='yolor-csp-c.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
510
+ super(Model, self).__init__()
511
+ self.traced = False
512
+ if isinstance(cfg, dict):
513
+ self.yaml = cfg # model dict
514
+ else: # is *.yaml
515
+ import yaml # for torch hub
516
+ self.yaml_file = Path(cfg).name
517
+ with open(cfg) as f:
518
+ self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict
519
+
520
+ # Define model
521
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
522
+ if nc and nc != self.yaml['nc']:
523
+ logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
524
+ self.yaml['nc'] = nc # override yaml value
525
+ if anchors:
526
+ logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
527
+ self.yaml['anchors'] = round(anchors) # override yaml value
528
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
529
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
530
+ # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
531
+
532
+ # Build strides, anchors
533
+ m = self.model[-1] # Detect()
534
+ if isinstance(m, Detect):
535
+ s = 256 # 2x min stride
536
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
537
+ check_anchor_order(m)
538
+ m.anchors /= m.stride.view(-1, 1, 1)
539
+ self.stride = m.stride
540
+ self._initialize_biases() # only run once
541
+ # print('Strides: %s' % m.stride.tolist())
542
+ if isinstance(m, IDetect):
543
+ s = 256 # 2x min stride
544
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
545
+ check_anchor_order(m)
546
+ m.anchors /= m.stride.view(-1, 1, 1)
547
+ self.stride = m.stride
548
+ self._initialize_biases() # only run once
549
+ # print('Strides: %s' % m.stride.tolist())
550
+ if isinstance(m, IAuxDetect):
551
+ s = 256 # 2x min stride
552
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))[:4]]) # forward
553
+ #print(m.stride)
554
+ check_anchor_order(m)
555
+ m.anchors /= m.stride.view(-1, 1, 1)
556
+ self.stride = m.stride
557
+ self._initialize_aux_biases() # only run once
558
+ # print('Strides: %s' % m.stride.tolist())
559
+ if isinstance(m, IBin):
560
+ s = 256 # 2x min stride
561
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
562
+ check_anchor_order(m)
563
+ m.anchors /= m.stride.view(-1, 1, 1)
564
+ self.stride = m.stride
565
+ self._initialize_biases_bin() # only run once
566
+ # print('Strides: %s' % m.stride.tolist())
567
+ if isinstance(m, IKeypoint):
568
+ s = 256 # 2x min stride
569
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
570
+ check_anchor_order(m)
571
+ m.anchors /= m.stride.view(-1, 1, 1)
572
+ self.stride = m.stride
573
+ self._initialize_biases_kpt() # only run once
574
+ # print('Strides: %s' % m.stride.tolist())
575
+
576
+ # Init weights, biases
577
+ initialize_weights(self)
578
+ self.info()
579
+ logger.info('')
580
+
581
+ def forward(self, x, augment=False, profile=False):
582
+ if augment:
583
+ img_size = x.shape[-2:] # height, width
584
+ s = [1, 0.83, 0.67] # scales
585
+ f = [None, 3, None] # flips (2-ud, 3-lr)
586
+ y = [] # outputs
587
+ for si, fi in zip(s, f):
588
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
589
+ yi = self.forward_once(xi)[0] # forward
590
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
591
+ yi[..., :4] /= si # de-scale
592
+ if fi == 2:
593
+ yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
594
+ elif fi == 3:
595
+ yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
596
+ y.append(yi)
597
+ return torch.cat(y, 1), None # augmented inference, train
598
+ else:
599
+ return self.forward_once(x, profile) # single-scale inference, train
600
+
601
+ def forward_once(self, x, profile=False):
602
+ y, dt = [], [] # outputs
603
+ for m in self.model:
604
+ if m.f != -1: # if not from previous layer
605
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
606
+
607
+ if not hasattr(self, 'traced'):
608
+ self.traced=False
609
+
610
+ if self.traced:
611
+ if isinstance(m, Detect) or isinstance(m, IDetect) or isinstance(m, IAuxDetect) or isinstance(m, IKeypoint):
612
+ break
613
+
614
+ if profile:
615
+ c = isinstance(m, (Detect, IDetect, IAuxDetect, IBin))
616
+ o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS
617
+ for _ in range(10):
618
+ m(x.copy() if c else x)
619
+ t = time_synchronized()
620
+ for _ in range(10):
621
+ m(x.copy() if c else x)
622
+ dt.append((time_synchronized() - t) * 100)
623
+ print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
624
+
625
+ x = m(x) # run
626
+
627
+ y.append(x if m.i in self.save else None) # save output
628
+
629
+ if profile:
630
+ print('%.1fms total' % sum(dt))
631
+ return x
632
+
633
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
634
+ # https://arxiv.org/abs/1708.02002 section 3.3
635
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
636
+ m = self.model[-1] # Detect() module
637
+ for mi, s in zip(m.m, m.stride): # from
638
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
639
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
640
+ b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
641
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
642
+
643
+ def _initialize_aux_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
644
+ # https://arxiv.org/abs/1708.02002 section 3.3
645
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
646
+ m = self.model[-1] # Detect() module
647
+ for mi, mi2, s in zip(m.m, m.m2, m.stride): # from
648
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
649
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
650
+ b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
651
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
652
+ b2 = mi2.bias.view(m.na, -1) # conv.bias(255) to (3,85)
653
+ b2.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
654
+ b2.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
655
+ mi2.bias = torch.nn.Parameter(b2.view(-1), requires_grad=True)
656
+
657
+ def _initialize_biases_bin(self, cf=None): # initialize biases into Detect(), cf is class frequency
658
+ # https://arxiv.org/abs/1708.02002 section 3.3
659
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
660
+ m = self.model[-1] # Bin() module
661
+ bc = m.bin_count
662
+ for mi, s in zip(m.m, m.stride): # from
663
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
664
+ old = b[:, (0,1,2,bc+3)].data
665
+ obj_idx = 2*bc+4
666
+ b[:, :obj_idx].data += math.log(0.6 / (bc + 1 - 0.99))
667
+ b[:, obj_idx].data += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
668
+ b[:, (obj_idx+1):].data += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
669
+ b[:, (0,1,2,bc+3)].data = old
670
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
671
+
672
+ def _initialize_biases_kpt(self, cf=None): # initialize biases into Detect(), cf is class frequency
673
+ # https://arxiv.org/abs/1708.02002 section 3.3
674
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
675
+ m = self.model[-1] # Detect() module
676
+ for mi, s in zip(m.m, m.stride): # from
677
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
678
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
679
+ b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
680
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
681
+
682
+ def _print_biases(self):
683
+ m = self.model[-1] # Detect() module
684
+ for mi in m.m: # from
685
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
686
+ print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
687
+
688
+ # def _print_weights(self):
689
+ # for m in self.model.modules():
690
+ # if type(m) is Bottleneck:
691
+ # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
692
+
693
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
694
+ print('Fusing layers... ')
695
+ for m in self.model.modules():
696
+ if isinstance(m, RepConv):
697
+ #print(f" fuse_repvgg_block")
698
+ m.fuse_repvgg_block()
699
+ elif isinstance(m, RepConv_OREPA):
700
+ #print(f" switch_to_deploy")
701
+ m.switch_to_deploy()
702
+ elif type(m) is Conv and hasattr(m, 'bn'):
703
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
704
+ delattr(m, 'bn') # remove batchnorm
705
+ m.forward = m.fuseforward # update forward
706
+ elif isinstance(m, (IDetect, IAuxDetect)):
707
+ m.fuse()
708
+ m.forward = m.fuseforward
709
+ self.info()
710
+ return self
711
+
712
+ def nms(self, mode=True): # add or remove NMS module
713
+ present = type(self.model[-1]) is NMS # last layer is NMS
714
+ if mode and not present:
715
+ print('Adding NMS... ')
716
+ m = NMS() # module
717
+ m.f = -1 # from
718
+ m.i = self.model[-1].i + 1 # index
719
+ self.model.add_module(name='%s' % m.i, module=m) # add
720
+ self.eval()
721
+ elif not mode and present:
722
+ print('Removing NMS... ')
723
+ self.model = self.model[:-1] # remove
724
+ return self
725
+
726
+ def autoshape(self): # add autoShape module
727
+ print('Adding autoShape... ')
728
+ m = autoShape(self) # wrap model
729
+ copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
730
+ return m
731
+
732
+ def info(self, verbose=False, img_size=640): # print model information
733
+ model_info(self, verbose, img_size)
734
+
735
+
736
+ def parse_model(d, ch): # model_dict, input_channels(3)
737
+ logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
738
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
739
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
740
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
741
+
742
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
743
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
744
+ m = eval(m) if isinstance(m, str) else m # eval strings
745
+ for j, a in enumerate(args):
746
+ try:
747
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
748
+ except:
749
+ pass
750
+
751
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
752
+ if m in [nn.Conv2d, Conv, RobustConv, RobustConv2, DWConv, GhostConv, RepConv, RepConv_OREPA, DownC,
753
+ SPP, SPPF, SPPCSPC, GhostSPPCSPC, MixConv2d, Focus, Stem, GhostStem, CrossConv,
754
+ Bottleneck, BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
755
+ RepBottleneck, RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
756
+ Res, ResCSPA, ResCSPB, ResCSPC,
757
+ RepRes, RepResCSPA, RepResCSPB, RepResCSPC,
758
+ ResX, ResXCSPA, ResXCSPB, ResXCSPC,
759
+ RepResX, RepResXCSPA, RepResXCSPB, RepResXCSPC,
760
+ Ghost, GhostCSPA, GhostCSPB, GhostCSPC,
761
+ SwinTransformerBlock, STCSPA, STCSPB, STCSPC,
762
+ SwinTransformer2Block, ST2CSPA, ST2CSPB, ST2CSPC]:
763
+ c1, c2 = ch[f], args[0]
764
+ if c2 != no: # if not output
765
+ c2 = make_divisible(c2 * gw, 8)
766
+
767
+ args = [c1, c2, *args[1:]]
768
+ if m in [DownC, SPPCSPC, GhostSPPCSPC,
769
+ BottleneckCSPA, BottleneckCSPB, BottleneckCSPC,
770
+ RepBottleneckCSPA, RepBottleneckCSPB, RepBottleneckCSPC,
771
+ ResCSPA, ResCSPB, ResCSPC,
772
+ RepResCSPA, RepResCSPB, RepResCSPC,
773
+ ResXCSPA, ResXCSPB, ResXCSPC,
774
+ RepResXCSPA, RepResXCSPB, RepResXCSPC,
775
+ GhostCSPA, GhostCSPB, GhostCSPC,
776
+ STCSPA, STCSPB, STCSPC,
777
+ ST2CSPA, ST2CSPB, ST2CSPC]:
778
+ args.insert(2, n) # number of repeats
779
+ n = 1
780
+ elif m is nn.BatchNorm2d:
781
+ args = [ch[f]]
782
+ elif m is Concat:
783
+ c2 = sum([ch[x] for x in f])
784
+ elif m is Chuncat:
785
+ c2 = sum([ch[x] for x in f])
786
+ elif m is Shortcut:
787
+ c2 = ch[f[0]]
788
+ elif m is Foldcut:
789
+ c2 = ch[f] // 2
790
+ elif m in [Detect, IDetect, IAuxDetect, IBin, IKeypoint]:
791
+ args.append([ch[x] for x in f])
792
+ if isinstance(args[1], int): # number of anchors
793
+ args[1] = [list(range(args[1] * 2))] * len(f)
794
+ elif m is ReOrg:
795
+ c2 = ch[f] * 4
796
+ elif m is Contract:
797
+ c2 = ch[f] * args[0] ** 2
798
+ elif m is Expand:
799
+ c2 = ch[f] // args[0] ** 2
800
+ else:
801
+ c2 = ch[f]
802
+
803
+ m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
804
+ t = str(m)[8:-2].replace('__main__.', '') # module type
805
+ np = sum([x.numel() for x in m_.parameters()]) # number params
806
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
807
+ logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
808
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
809
+ layers.append(m_)
810
+ if i == 0:
811
+ ch = []
812
+ ch.append(c2)
813
+ return nn.Sequential(*layers), sorted(save)
814
+
815
+
816
+ if __name__ == '__main__':
817
+ parser = argparse.ArgumentParser()
818
+ parser.add_argument('--cfg', type=str, default='yolor-csp-c.yaml', help='model.yaml')
819
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
820
+ parser.add_argument('--profile', action='store_true', help='profile model speed')
821
+ opt = parser.parse_args()
822
+ opt.cfg = check_file(opt.cfg) # check file
823
+ set_logging()
824
+ device = select_device(opt.device)
825
+
826
+ # Create model
827
+ model = Model(opt.cfg).to(device)
828
+ model.train()
829
+
830
+ if opt.profile:
831
+ img = torch.rand(1, 3, 640, 640).to(device)
832
+ y = model(img, profile=True)
833
+
834
+ # Profile
835
+ # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
836
+ # y = model(img, profile=True)
837
+
838
+ # Tensorboard
839
+ # from torch.utils.tensorboard import SummaryWriter
840
+ # tb_writer = SummaryWriter()
841
+ # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/")
842
+ # tb_writer.add_graph(model.model, img) # add model to tensorboard
843
+ # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
yolov7detect/test.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from threading import Thread
6
+
7
+ import numpy as np
8
+ import torch
9
+ import yaml
10
+ from tqdm import tqdm
11
+
12
+ from yolov7.models.experimental import attempt_load
13
+ from yolov7.utils.datasets import create_dataloader
14
+ from yolov7.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, check_requirements, \
15
+ box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, colorstr
16
+ from yolov7.utils.metrics import ap_per_class, ConfusionMatrix
17
+ from yolov7.utils.plots import plot_images, output_to_target, plot_study_txt
18
+ from yolov7.utils.torch_utils import select_device, time_synchronized, TracedModel
19
+
20
+
21
+ def test(data,
22
+ weights=None,
23
+ batch_size=32,
24
+ imgsz=640,
25
+ conf_thres=0.001,
26
+ iou_thres=0.6, # for NMS
27
+ save_json=False,
28
+ single_cls=False,
29
+ augment=False,
30
+ verbose=False,
31
+ model=None,
32
+ dataloader=None,
33
+ save_dir=Path(''), # for saving images
34
+ save_txt=False, # for auto-labelling
35
+ save_hybrid=False, # for hybrid auto-labelling
36
+ save_conf=False, # save auto-label confidences
37
+ plots=True,
38
+ wandb_logger=None,
39
+ compute_loss=None,
40
+ half_precision=True,
41
+ trace=False,
42
+ is_coco=False,
43
+ v5_metric=False):
44
+ # Initialize/load model and set device
45
+ training = model is not None
46
+ if training: # called by train.py
47
+ device = next(model.parameters()).device # get model device
48
+
49
+ else: # called directly
50
+ set_logging()
51
+ device = select_device(opt.device, batch_size=batch_size)
52
+
53
+ # Directories
54
+ save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
55
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
56
+
57
+ # Load model
58
+ model = attempt_load(weights, map_location=device) # load FP32 model
59
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
60
+ imgsz = check_img_size(imgsz, s=gs) # check img_size
61
+
62
+ if trace:
63
+ model = TracedModel(model, device, imgsz)
64
+
65
+ # Half
66
+ half = device.type != 'cpu' and half_precision # half precision only supported on CUDA
67
+ if half:
68
+ model.half()
69
+
70
+ # Configure
71
+ model.eval()
72
+ if isinstance(data, str):
73
+ is_coco = data.endswith('coco.yaml')
74
+ with open(data) as f:
75
+ data = yaml.load(f, Loader=yaml.SafeLoader)
76
+ check_dataset(data) # check
77
+ nc = 1 if single_cls else int(data['nc']) # number of classes
78
+ iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for [email protected]:0.95
79
+ niou = iouv.numel()
80
+
81
+ # Logging
82
+ log_imgs = 0
83
+ if wandb_logger and wandb_logger.wandb:
84
+ log_imgs = min(wandb_logger.log_imgs, 100)
85
+ # Dataloader
86
+ if not training:
87
+ if device.type != 'cpu':
88
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
89
+ task = opt.task if opt.task in ('train', 'val', 'test') else 'val' # path to train/val/test images
90
+ dataloader = create_dataloader(data[task], imgsz, batch_size, gs, opt, pad=0.5, rect=True,
91
+ prefix=colorstr(f'{task}: '))[0]
92
+
93
+ if v5_metric:
94
+ print("Testing with YOLOv5 AP metric...")
95
+
96
+ seen = 0
97
+ confusion_matrix = ConfusionMatrix(nc=nc)
98
+ names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
99
+ coco91class = coco80_to_coco91_class()
100
+ s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', '[email protected]', '[email protected]:.95')
101
+ p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
102
+ loss = torch.zeros(3, device=device)
103
+ jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
104
+ for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
105
+ img = img.to(device, non_blocking=True)
106
+ img = img.half() if half else img.float() # uint8 to fp16/32
107
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
108
+ targets = targets.to(device)
109
+ nb, _, height, width = img.shape # batch size, channels, height, width
110
+
111
+ with torch.no_grad():
112
+ # Run model
113
+ t = time_synchronized()
114
+ out, train_out = model(img, augment=augment) # inference and training outputs
115
+ t0 += time_synchronized() - t
116
+
117
+ # Compute loss
118
+ if compute_loss:
119
+ loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls
120
+
121
+ # Run NMS
122
+ targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels
123
+ lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
124
+ t = time_synchronized()
125
+ out = non_max_suppression(out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb, multi_label=True)
126
+ t1 += time_synchronized() - t
127
+
128
+ # Statistics per image
129
+ for si, pred in enumerate(out):
130
+ labels = targets[targets[:, 0] == si, 1:]
131
+ nl = len(labels)
132
+ tcls = labels[:, 0].tolist() if nl else [] # target class
133
+ path = Path(paths[si])
134
+ seen += 1
135
+
136
+ if len(pred) == 0:
137
+ if nl:
138
+ stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
139
+ continue
140
+
141
+ # Predictions
142
+ predn = pred.clone()
143
+ scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred
144
+
145
+ # Append to text file
146
+ if save_txt:
147
+ gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
148
+ for *xyxy, conf, cls in predn.tolist():
149
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
150
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
151
+ with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:
152
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
153
+
154
+ # W&B logging - Media Panel Plots
155
+ if len(wandb_images) < log_imgs and wandb_logger.current_epoch > 0: # Check for test operation
156
+ if wandb_logger.current_epoch % wandb_logger.bbox_interval == 0:
157
+ box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
158
+ "class_id": int(cls),
159
+ "box_caption": "%s %.3f" % (names[cls], conf),
160
+ "scores": {"class_score": conf},
161
+ "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
162
+ boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
163
+ wandb_images.append(wandb_logger.wandb.Image(img[si], boxes=boxes, caption=path.name))
164
+ wandb_logger.log_training_progress(predn, path, names) if wandb_logger and wandb_logger.wandb_run else None
165
+
166
+ # Append to pycocotools JSON dictionary
167
+ if save_json:
168
+ # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
169
+ image_id = int(path.stem) if path.stem.isnumeric() else path.stem
170
+ box = xyxy2xywh(predn[:, :4]) # xywh
171
+ box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
172
+ for p, b in zip(pred.tolist(), box.tolist()):
173
+ jdict.append({'image_id': image_id,
174
+ 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
175
+ 'bbox': [round(x, 3) for x in b],
176
+ 'score': round(p[4], 5)})
177
+
178
+ # Assign all predictions as incorrect
179
+ correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
180
+ if nl:
181
+ detected = [] # target indices
182
+ tcls_tensor = labels[:, 0]
183
+
184
+ # target boxes
185
+ tbox = xywh2xyxy(labels[:, 1:5])
186
+ scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels
187
+ if plots:
188
+ confusion_matrix.process_batch(predn, torch.cat((labels[:, 0:1], tbox), 1))
189
+
190
+ # Per target class
191
+ for cls in torch.unique(tcls_tensor):
192
+ ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices
193
+ pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices
194
+
195
+ # Search for detections
196
+ if pi.shape[0]:
197
+ # Prediction to target ious
198
+ ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices
199
+
200
+ # Append detections
201
+ detected_set = set()
202
+ for j in (ious > iouv[0]).nonzero(as_tuple=False):
203
+ d = ti[i[j]] # detected target
204
+ if d.item() not in detected_set:
205
+ detected_set.add(d.item())
206
+ detected.append(d)
207
+ correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
208
+ if len(detected) == nl: # all targets already located in image
209
+ break
210
+
211
+ # Append statistics (correct, conf, pcls, tcls)
212
+ stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
213
+
214
+ # Plot images
215
+ if plots and batch_i < 3:
216
+ f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels
217
+ Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()
218
+ f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions
219
+ Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start()
220
+
221
+ # Compute statistics
222
+ stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
223
+ if len(stats) and stats[0].any():
224
+ p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, v5_metric=v5_metric, save_dir=save_dir, names=names)
225
+ ap50, ap = ap[:, 0], ap.mean(1) # [email protected], [email protected]:0.95
226
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
227
+ nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
228
+ else:
229
+ nt = torch.zeros(1)
230
+
231
+ # Print results
232
+ pf = '%20s' + '%12i' * 2 + '%12.3g' * 4 # print format
233
+ print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
234
+
235
+ # Print results per class
236
+ if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
237
+ for i, c in enumerate(ap_class):
238
+ print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
239
+
240
+ # Print speeds
241
+ t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
242
+ if not training:
243
+ print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
244
+
245
+ # Plots
246
+ if plots:
247
+ confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
248
+ if wandb_logger and wandb_logger.wandb:
249
+ val_batches = [wandb_logger.wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]
250
+ wandb_logger.log({"Validation": val_batches})
251
+ if wandb_images:
252
+ wandb_logger.log({"Bounding Box Debugger/Images": wandb_images})
253
+
254
+ # Save JSON
255
+ if save_json and len(jdict):
256
+ w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
257
+ anno_json = './coco/annotations/instances_val2017.json' # annotations json
258
+ pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
259
+ print('\nEvaluating pycocotools mAP... saving %s...' % pred_json)
260
+ with open(pred_json, 'w') as f:
261
+ json.dump(jdict, f)
262
+
263
+ try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
264
+ from pycocotools.coco import COCO
265
+ from pycocotools.cocoeval import COCOeval
266
+
267
+ anno = COCO(anno_json) # init annotations api
268
+ pred = anno.loadRes(pred_json) # init predictions api
269
+ eval = COCOeval(anno, pred, 'bbox')
270
+ if is_coco:
271
+ eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate
272
+ eval.evaluate()
273
+ eval.accumulate()
274
+ eval.summarize()
275
+ map, map50 = eval.stats[:2] # update results ([email protected]:0.95, [email protected])
276
+ except Exception as e:
277
+ print(f'pycocotools unable to run: {e}')
278
+
279
+ # Return results
280
+ model.float() # for training
281
+ if not training:
282
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
283
+ print(f"Results saved to {save_dir}{s}")
284
+ maps = np.zeros(nc) + map
285
+ for i, c in enumerate(ap_class):
286
+ maps[c] = ap[i]
287
+ return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
288
+
289
+
290
+ if __name__ == '__main__':
291
+ parser = argparse.ArgumentParser(prog='test.py')
292
+ parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
293
+ parser.add_argument('--data', type=str, default='data/coco.yaml', help='*.data path')
294
+ parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
295
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
296
+ parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
297
+ parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS')
298
+ parser.add_argument('--task', default='val', help='train, val, test, speed or study')
299
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
300
+ parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
301
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
302
+ parser.add_argument('--verbose', action='store_true', help='report mAP by class')
303
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
304
+ parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
305
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
306
+ parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
307
+ parser.add_argument('--project', default='runs/test', help='save to project/name')
308
+ parser.add_argument('--name', default='exp', help='save to project/name')
309
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
310
+ parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
311
+ parser.add_argument('--v5-metric', action='store_true', help='assume maximum recall as 1.0 in AP calculation')
312
+ opt = parser.parse_args()
313
+ opt.save_json |= opt.data.endswith('coco.yaml')
314
+ opt.data = check_file(opt.data) # check file
315
+ print(opt)
316
+ #check_requirements()
317
+
318
+ if opt.task in ('train', 'val', 'test'): # run normally
319
+ test(opt.data,
320
+ opt.weights,
321
+ opt.batch_size,
322
+ opt.img_size,
323
+ opt.conf_thres,
324
+ opt.iou_thres,
325
+ opt.save_json,
326
+ opt.single_cls,
327
+ opt.augment,
328
+ opt.verbose,
329
+ save_txt=opt.save_txt | opt.save_hybrid,
330
+ save_hybrid=opt.save_hybrid,
331
+ save_conf=opt.save_conf,
332
+ trace=not opt.no_trace,
333
+ v5_metric=opt.v5_metric
334
+ )
335
+
336
+ elif opt.task == 'speed': # speed benchmarks
337
+ for w in opt.weights:
338
+ test(opt.data, w, opt.batch_size, opt.img_size, 0.25, 0.45, save_json=False, plots=False, v5_metric=opt.v5_metric)
339
+
340
+ elif opt.task == 'study': # run over a range of settings and save/plot
341
+ # python test.py --task study --data coco.yaml --iou 0.65 --weights yolov7.pt
342
+ x = list(range(256, 1536 + 128, 128)) # x axis (image sizes)
343
+ for w in opt.weights:
344
+ f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to
345
+ y = [] # y axis
346
+ for i in x: # img-size
347
+ print(f'\nRunning {f} point {i}...')
348
+ r, _, t = test(opt.data, w, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,
349
+ plots=False, v5_metric=opt.v5_metric)
350
+ y.append(r + t) # results and times
351
+ np.savetxt(f, y, fmt='%10.4g') # save
352
+ os.system('zip -r study.zip study_*.txt')
353
+ plot_study_txt(x=x) # plot
yolov7detect/train.py ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import math
4
+ import os
5
+ import random
6
+ import time
7
+ from copy import deepcopy
8
+ from pathlib import Path
9
+ from threading import Thread
10
+
11
+ import numpy as np
12
+ import torch.distributed as dist
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torch.optim as optim
16
+ import torch.optim.lr_scheduler as lr_scheduler
17
+ import torch.utils.data
18
+ import yaml
19
+ from torch.cuda import amp
20
+ from torch.nn.parallel import DistributedDataParallel as DDP
21
+ from torch.utils.tensorboard import SummaryWriter
22
+ from tqdm import tqdm
23
+
24
+ import yolov7.test as test # import test.py to get mAP after each epoch
25
+ from yolov7.models.experimental import attempt_load
26
+ from yolov7.models.yolo import Model
27
+ from yolov7.utils.autoanchor import check_anchors
28
+ from yolov7.utils.datasets import create_dataloader
29
+ from yolov7.utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \
30
+ fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \
31
+ check_requirements, print_mutation, set_logging, one_cycle, colorstr
32
+ from yolov7.utils.google_utils import attempt_download
33
+ from yolov7.utils.loss import ComputeLoss, ComputeLossOTA
34
+ from yolov7.utils.plots import plot_images, plot_labels, plot_results, plot_evolution
35
+ from yolov7.utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first, is_parallel
36
+ from yolov7.utils.wandb_logging.wandb_utils import WandbLogger, check_wandb_resume
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ def train(hyp, opt, device, tb_writer=None):
42
+ logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
43
+ save_dir, epochs, batch_size, total_batch_size, weights, rank, freeze = \
44
+ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank, opt.freeze
45
+
46
+ # Directories
47
+ wdir = save_dir / 'weights'
48
+ wdir.mkdir(parents=True, exist_ok=True) # make dir
49
+ last = wdir / 'last.pt'
50
+ best = wdir / 'best.pt'
51
+ results_file = save_dir / 'results.txt'
52
+
53
+ # Save run settings
54
+ with open(save_dir / 'hyp.yaml', 'w') as f:
55
+ yaml.dump(hyp, f, sort_keys=False)
56
+ with open(save_dir / 'opt.yaml', 'w') as f:
57
+ yaml.dump(vars(opt), f, sort_keys=False)
58
+
59
+ # Configure
60
+ plots = not opt.evolve # create plots
61
+ cuda = device.type != 'cpu'
62
+ init_seeds(2 + rank)
63
+ with open(opt.data) as f:
64
+ data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict
65
+ is_coco = opt.data.endswith('coco.yaml')
66
+
67
+ # Logging- Doing this before checking the dataset. Might update data_dict
68
+ loggers = {'wandb': None} # loggers dict
69
+ if rank in [-1, 0]:
70
+ opt.hyp = hyp # add hyperparameters
71
+ run_id = torch.load(weights, map_location=device).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None
72
+ wandb_logger = WandbLogger(opt, Path(opt.save_dir).stem, run_id, data_dict)
73
+ loggers['wandb'] = wandb_logger.wandb
74
+ data_dict = wandb_logger.data_dict
75
+ if wandb_logger.wandb:
76
+ weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming
77
+
78
+ nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes
79
+ names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
80
+ assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
81
+
82
+ # Model
83
+ pretrained = weights.endswith('.pt')
84
+ if pretrained:
85
+ with torch_distributed_zero_first(rank):
86
+ attempt_download(weights) # download if not found locally
87
+ ckpt = torch.load(weights, map_location=device) # load checkpoint
88
+ model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
89
+ exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys
90
+ state_dict = ckpt['model'].float().state_dict() # to FP32
91
+ state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect
92
+ model.load_state_dict(state_dict, strict=False) # load
93
+ logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report
94
+ else:
95
+ model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
96
+ with torch_distributed_zero_first(rank):
97
+ check_dataset(data_dict) # check
98
+ train_path = data_dict['train']
99
+ test_path = data_dict['val']
100
+
101
+ # Freeze
102
+ freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # parameter names to freeze (full or partial)
103
+ for k, v in model.named_parameters():
104
+ v.requires_grad = True # train all layers
105
+ if any(x in k for x in freeze):
106
+ print('freezing %s' % k)
107
+ v.requires_grad = False
108
+
109
+ # Optimizer
110
+ nbs = 64 # nominal batch size
111
+ accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
112
+ hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
113
+ logger.info(f"Scaled weight_decay = {hyp['weight_decay']}")
114
+
115
+ pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
116
+ for k, v in model.named_modules():
117
+ if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter):
118
+ pg2.append(v.bias) # biases
119
+ if isinstance(v, nn.BatchNorm2d):
120
+ pg0.append(v.weight) # no decay
121
+ elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter):
122
+ pg1.append(v.weight) # apply decay
123
+ if hasattr(v, 'im'):
124
+ if hasattr(v.im, 'implicit'):
125
+ pg0.append(v.im.implicit)
126
+ else:
127
+ for iv in v.im:
128
+ pg0.append(iv.implicit)
129
+ if hasattr(v, 'imc'):
130
+ if hasattr(v.imc, 'implicit'):
131
+ pg0.append(v.imc.implicit)
132
+ else:
133
+ for iv in v.imc:
134
+ pg0.append(iv.implicit)
135
+ if hasattr(v, 'imb'):
136
+ if hasattr(v.imb, 'implicit'):
137
+ pg0.append(v.imb.implicit)
138
+ else:
139
+ for iv in v.imb:
140
+ pg0.append(iv.implicit)
141
+ if hasattr(v, 'imo'):
142
+ if hasattr(v.imo, 'implicit'):
143
+ pg0.append(v.imo.implicit)
144
+ else:
145
+ for iv in v.imo:
146
+ pg0.append(iv.implicit)
147
+ if hasattr(v, 'ia'):
148
+ if hasattr(v.ia, 'implicit'):
149
+ pg0.append(v.ia.implicit)
150
+ else:
151
+ for iv in v.ia:
152
+ pg0.append(iv.implicit)
153
+ if hasattr(v, 'attn'):
154
+ if hasattr(v.attn, 'logit_scale'):
155
+ pg0.append(v.attn.logit_scale)
156
+ if hasattr(v.attn, 'q_bias'):
157
+ pg0.append(v.attn.q_bias)
158
+ if hasattr(v.attn, 'v_bias'):
159
+ pg0.append(v.attn.v_bias)
160
+ if hasattr(v.attn, 'relative_position_bias_table'):
161
+ pg0.append(v.attn.relative_position_bias_table)
162
+ if hasattr(v, 'rbr_dense'):
163
+ if hasattr(v.rbr_dense, 'weight_rbr_origin'):
164
+ pg0.append(v.rbr_dense.weight_rbr_origin)
165
+ if hasattr(v.rbr_dense, 'weight_rbr_avg_conv'):
166
+ pg0.append(v.rbr_dense.weight_rbr_avg_conv)
167
+ if hasattr(v.rbr_dense, 'weight_rbr_pfir_conv'):
168
+ pg0.append(v.rbr_dense.weight_rbr_pfir_conv)
169
+ if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_idconv1'):
170
+ pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_idconv1)
171
+ if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_conv2'):
172
+ pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_conv2)
173
+ if hasattr(v.rbr_dense, 'weight_rbr_gconv_dw'):
174
+ pg0.append(v.rbr_dense.weight_rbr_gconv_dw)
175
+ if hasattr(v.rbr_dense, 'weight_rbr_gconv_pw'):
176
+ pg0.append(v.rbr_dense.weight_rbr_gconv_pw)
177
+ if hasattr(v.rbr_dense, 'vector'):
178
+ pg0.append(v.rbr_dense.vector)
179
+
180
+ if opt.adam:
181
+ optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
182
+ else:
183
+ optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
184
+
185
+ optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
186
+ optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
187
+ logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
188
+ del pg0, pg1, pg2
189
+
190
+ # Scheduler https://arxiv.org/pdf/1812.01187.pdf
191
+ # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
192
+ if opt.linear_lr:
193
+ lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
194
+ else:
195
+ lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
196
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
197
+ # plot_lr_scheduler(optimizer, scheduler, epochs)
198
+
199
+ # EMA
200
+ ema = ModelEMA(model) if rank in [-1, 0] else None
201
+
202
+ # Resume
203
+ start_epoch, best_fitness = 0, 0.0
204
+ if pretrained:
205
+ # Optimizer
206
+ if ckpt['optimizer'] is not None:
207
+ optimizer.load_state_dict(ckpt['optimizer'])
208
+ best_fitness = ckpt['best_fitness']
209
+
210
+ # EMA
211
+ if ema and ckpt.get('ema'):
212
+ ema.ema.load_state_dict(ckpt['ema'].float().state_dict())
213
+ ema.updates = ckpt['updates']
214
+
215
+ # Results
216
+ if ckpt.get('training_results') is not None:
217
+ results_file.write_text(ckpt['training_results']) # write results.txt
218
+
219
+ # Epochs
220
+ start_epoch = ckpt['epoch'] + 1
221
+ if opt.resume:
222
+ assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs)
223
+ if epochs < start_epoch:
224
+ logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
225
+ (weights, ckpt['epoch'], epochs))
226
+ epochs += ckpt['epoch'] # finetune additional epochs
227
+
228
+ del ckpt, state_dict
229
+
230
+ # Image sizes
231
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
232
+ nl = model.model[-1].nl # number of detection layers (used for scaling hyp['obj'])
233
+ imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
234
+
235
+ # DP mode
236
+ if cuda and rank == -1 and torch.cuda.device_count() > 1:
237
+ model = torch.nn.DataParallel(model)
238
+
239
+ # SyncBatchNorm
240
+ if opt.sync_bn and cuda and rank != -1:
241
+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
242
+ logger.info('Using SyncBatchNorm()')
243
+
244
+ # Trainloader
245
+ dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt,
246
+ hyp=hyp, augment=True, cache=opt.cache_images, rect=opt.rect, rank=rank,
247
+ world_size=opt.world_size, workers=opt.workers,
248
+ image_weights=opt.image_weights, quad=opt.quad, prefix=colorstr('train: '))
249
+ mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
250
+ nb = len(dataloader) # number of batches
251
+ assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)
252
+
253
+ # Process 0
254
+ if rank in [-1, 0]:
255
+ testloader = create_dataloader(test_path, imgsz_test, batch_size * 2, gs, opt, # testloader
256
+ hyp=hyp, cache=opt.cache_images and not opt.notest, rect=True, rank=-1,
257
+ world_size=opt.world_size, workers=opt.workers,
258
+ pad=0.5, prefix=colorstr('val: '))[0]
259
+
260
+ if not opt.resume:
261
+ labels = np.concatenate(dataset.labels, 0)
262
+ c = torch.tensor(labels[:, 0]) # classes
263
+ # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
264
+ # model._initialize_biases(cf.to(device))
265
+ if plots:
266
+ #plot_labels(labels, names, save_dir, loggers)
267
+ if tb_writer:
268
+ tb_writer.add_histogram('classes', c, 0)
269
+
270
+ # Anchors
271
+ if not opt.noautoanchor:
272
+ check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
273
+ model.half().float() # pre-reduce anchor precision
274
+
275
+ # DDP mode
276
+ if cuda and rank != -1:
277
+ model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank,
278
+ # nn.MultiheadAttention incompatibility with DDP https://github.com/pytorch/pytorch/issues/26698
279
+ find_unused_parameters=any(isinstance(layer, nn.MultiheadAttention) for layer in model.modules()))
280
+
281
+ # Model parameters
282
+ hyp['box'] *= 3. / nl # scale to layers
283
+ hyp['cls'] *= nc / 80. * 3. / nl # scale to classes and layers
284
+ hyp['obj'] *= (imgsz / 640) ** 2 * 3. / nl # scale to image size and layers
285
+ hyp['label_smoothing'] = opt.label_smoothing
286
+ model.nc = nc # attach number of classes to model
287
+ model.hyp = hyp # attach hyperparameters to model
288
+ model.gr = 1.0 # iou loss ratio (obj_loss = 1.0 or iou)
289
+ model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
290
+ model.names = names
291
+
292
+ # Start training
293
+ t0 = time.time()
294
+ nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations)
295
+ # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
296
+ maps = np.zeros(nc) # mAP per class
297
+ results = (0, 0, 0, 0, 0, 0, 0) # P, R, [email protected], [email protected], val_loss(box, obj, cls)
298
+ scheduler.last_epoch = start_epoch - 1 # do not move
299
+ scaler = amp.GradScaler(enabled=cuda)
300
+ compute_loss_ota = ComputeLossOTA(model) # init loss class
301
+ compute_loss = ComputeLoss(model) # init loss class
302
+ logger.info(f'Image sizes {imgsz} train, {imgsz_test} test\n'
303
+ f'Using {dataloader.num_workers} dataloader workers\n'
304
+ f'Logging results to {save_dir}\n'
305
+ f'Starting training for {epochs} epochs...')
306
+ torch.save(model, wdir / 'init.pt')
307
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
308
+ model.train()
309
+
310
+ # Update image weights (optional)
311
+ if opt.image_weights:
312
+ # Generate indices
313
+ if rank in [-1, 0]:
314
+ cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
315
+ iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
316
+ dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
317
+ # Broadcast if DDP
318
+ if rank != -1:
319
+ indices = (torch.tensor(dataset.indices) if rank == 0 else torch.zeros(dataset.n)).int()
320
+ dist.broadcast(indices, 0)
321
+ if rank != 0:
322
+ dataset.indices = indices.cpu().numpy()
323
+
324
+ # Update mosaic border
325
+ # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
326
+ # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
327
+
328
+ mloss = torch.zeros(4, device=device) # mean losses
329
+ if rank != -1:
330
+ dataloader.sampler.set_epoch(epoch)
331
+ pbar = enumerate(dataloader)
332
+ logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'labels', 'img_size'))
333
+ if rank in [-1, 0]:
334
+ pbar = tqdm(pbar, total=nb) # progress bar
335
+ optimizer.zero_grad()
336
+ for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
337
+ ni = i + nb * epoch # number integrated batches (since train start)
338
+ imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0
339
+
340
+ # Warmup
341
+ if ni <= nw:
342
+ xi = [0, nw] # x interp
343
+ # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
344
+ accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())
345
+ for j, x in enumerate(optimizer.param_groups):
346
+ # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
347
+ x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
348
+ if 'momentum' in x:
349
+ x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
350
+
351
+ # Multi-scale
352
+ if opt.multi_scale:
353
+ sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
354
+ sf = sz / max(imgs.shape[2:]) # scale factor
355
+ if sf != 1:
356
+ ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
357
+ imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
358
+
359
+ # Forward
360
+ with amp.autocast(enabled=cuda):
361
+ pred = model(imgs) # forward
362
+ if 'loss_ota' not in hyp or hyp['loss_ota'] == 1:
363
+ loss, loss_items = compute_loss_ota(pred, targets.to(device), imgs) # loss scaled by batch_size
364
+ else:
365
+ loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
366
+ if rank != -1:
367
+ loss *= opt.world_size # gradient averaged between devices in DDP mode
368
+ if opt.quad:
369
+ loss *= 4.
370
+
371
+ # Backward
372
+ scaler.scale(loss).backward()
373
+
374
+ # Optimize
375
+ if ni % accumulate == 0:
376
+ scaler.step(optimizer) # optimizer.step
377
+ scaler.update()
378
+ optimizer.zero_grad()
379
+ if ema:
380
+ ema.update(model)
381
+
382
+ # Print
383
+ if rank in [-1, 0]:
384
+ mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
385
+ mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
386
+ s = ('%10s' * 2 + '%10.4g' * 6) % (
387
+ '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
388
+ pbar.set_description(s)
389
+
390
+ # Plot
391
+ if plots and ni < 10:
392
+ f = save_dir / f'train_batch{ni}.jpg' # filename
393
+ Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
394
+ # if tb_writer:
395
+ # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch)
396
+ # tb_writer.add_graph(torch.jit.trace(model, imgs, strict=False), []) # add model graph
397
+ elif plots and ni == 10 and wandb_logger.wandb:
398
+ wandb_logger.log({"Mosaics": [wandb_logger.wandb.Image(str(x), caption=x.name) for x in
399
+ save_dir.glob('train*.jpg') if x.exists()]})
400
+
401
+ # end batch ------------------------------------------------------------------------------------------------
402
+ # end epoch ----------------------------------------------------------------------------------------------------
403
+
404
+ # Scheduler
405
+ lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard
406
+ scheduler.step()
407
+
408
+ # DDP process 0 or single-GPU
409
+ if rank in [-1, 0]:
410
+ # mAP
411
+ ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride', 'class_weights'])
412
+ final_epoch = epoch + 1 == epochs
413
+ if not opt.notest or final_epoch: # Calculate mAP
414
+ wandb_logger.current_epoch = epoch + 1
415
+ results, maps, times = test.test(data_dict,
416
+ batch_size=batch_size * 2,
417
+ imgsz=imgsz_test,
418
+ model=ema.ema,
419
+ single_cls=opt.single_cls,
420
+ dataloader=testloader,
421
+ save_dir=save_dir,
422
+ verbose=nc < 50 and final_epoch,
423
+ plots=plots and final_epoch,
424
+ wandb_logger=wandb_logger,
425
+ compute_loss=compute_loss,
426
+ is_coco=is_coco,
427
+ v5_metric=opt.v5_metric)
428
+
429
+ # Write
430
+ with open(results_file, 'a') as f:
431
+ f.write(s + '%10.4g' * 7 % results + '\n') # append metrics, val_loss
432
+ if len(opt.name) and opt.bucket:
433
+ os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name))
434
+
435
+ # Log
436
+ tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
437
+ 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
438
+ 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
439
+ 'x/lr0', 'x/lr1', 'x/lr2'] # params
440
+ for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags):
441
+ if tb_writer:
442
+ tb_writer.add_scalar(tag, x, epoch) # tensorboard
443
+ if wandb_logger.wandb:
444
+ wandb_logger.log({tag: x}) # W&B
445
+
446
+ # Update best mAP
447
+ fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, [email protected], [email protected]]
448
+ if fi > best_fitness:
449
+ best_fitness = fi
450
+ wandb_logger.end_epoch(best_result=best_fitness == fi)
451
+
452
+ # Save model
453
+ if (not opt.nosave) or (final_epoch and not opt.evolve): # if save
454
+ ckpt = {'epoch': epoch,
455
+ 'best_fitness': best_fitness,
456
+ 'training_results': results_file.read_text(),
457
+ 'model': deepcopy(model.module if is_parallel(model) else model).half(),
458
+ 'ema': deepcopy(ema.ema).half(),
459
+ 'updates': ema.updates,
460
+ 'optimizer': optimizer.state_dict(),
461
+ 'wandb_id': wandb_logger.wandb_run.id if wandb_logger.wandb else None}
462
+
463
+ # Save last, best and delete
464
+ torch.save(ckpt, last)
465
+ if best_fitness == fi:
466
+ torch.save(ckpt, best)
467
+ if (best_fitness == fi) and (epoch >= 200):
468
+ torch.save(ckpt, wdir / 'best_{:03d}.pt'.format(epoch))
469
+ if epoch == 0:
470
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
471
+ elif ((epoch+1) % 25) == 0:
472
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
473
+ elif epoch >= (epochs-5):
474
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
475
+ if wandb_logger.wandb:
476
+ if ((epoch + 1) % opt.save_period == 0 and not final_epoch) and opt.save_period != -1:
477
+ wandb_logger.log_model(
478
+ last.parent, opt, epoch, fi, best_model=best_fitness == fi)
479
+ del ckpt
480
+
481
+ # end epoch ----------------------------------------------------------------------------------------------------
482
+ # end training
483
+ if rank in [-1, 0]:
484
+ # Plots
485
+ if plots:
486
+ plot_results(save_dir=save_dir) # save as results.png
487
+ if wandb_logger.wandb:
488
+ files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]]
489
+ wandb_logger.log({"Results": [wandb_logger.wandb.Image(str(save_dir / f), caption=f) for f in files
490
+ if (save_dir / f).exists()]})
491
+ # Test best.pt
492
+ logger.info('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
493
+ if opt.data.endswith('coco.yaml') and nc == 80: # if COCO
494
+ for m in (last, best) if best.exists() else (last): # speed, mAP tests
495
+ results, _, _ = test.test(opt.data,
496
+ batch_size=batch_size * 2,
497
+ imgsz=imgsz_test,
498
+ conf_thres=0.001,
499
+ iou_thres=0.7,
500
+ model=attempt_load(m, device).half(),
501
+ single_cls=opt.single_cls,
502
+ dataloader=testloader,
503
+ save_dir=save_dir,
504
+ save_json=True,
505
+ plots=False,
506
+ is_coco=is_coco,
507
+ v5_metric=opt.v5_metric)
508
+
509
+ # Strip optimizers
510
+ final = best if best.exists() else last # final model
511
+ for f in last, best:
512
+ if f.exists():
513
+ strip_optimizer(f) # strip optimizers
514
+ if opt.bucket:
515
+ os.system(f'gsutil cp {final} gs://{opt.bucket}/weights') # upload
516
+ if wandb_logger.wandb and not opt.evolve: # Log the stripped model
517
+ wandb_logger.wandb.log_artifact(str(final), type='model',
518
+ name='run_' + wandb_logger.wandb_run.id + '_model',
519
+ aliases=['last', 'best', 'stripped'])
520
+ wandb_logger.finish_run()
521
+ else:
522
+ dist.destroy_process_group()
523
+ torch.cuda.empty_cache()
524
+ return results
525
+
526
+
527
+ if __name__ == '__main__':
528
+ parser = argparse.ArgumentParser()
529
+ parser.add_argument('--weights', type=str, default='yolo7.pt', help='initial weights path')
530
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
531
+ parser.add_argument('--data', type=str, default='data/coco.yaml', help='data.yaml path')
532
+ parser.add_argument('--hyp', type=str, default='data/hyp.scratch.p5.yaml', help='hyperparameters path')
533
+ parser.add_argument('--epochs', type=int, default=300)
534
+ parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
535
+ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
536
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
537
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
538
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
539
+ parser.add_argument('--notest', action='store_true', help='only test final epoch')
540
+ parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
541
+ parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
542
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
543
+ parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
544
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
545
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
546
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
547
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
548
+ parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
549
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
550
+ parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
551
+ parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers')
552
+ parser.add_argument('--project', default='runs/train', help='save to project/name')
553
+ parser.add_argument('--entity', default=None, help='W&B entity')
554
+ parser.add_argument('--name', default='exp', help='save to project/name')
555
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
556
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
557
+ parser.add_argument('--linear-lr', action='store_true', help='linear LR')
558
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
559
+ parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table')
560
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B')
561
+ parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch')
562
+ parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used')
563
+ parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone of yolov7=50, first3=0 1 2')
564
+ parser.add_argument('--v5-metric', action='store_true', help='assume maximum recall as 1.0 in AP calculation')
565
+ opt = parser.parse_args()
566
+
567
+ # Set DDP variables
568
+ opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1
569
+ opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1
570
+ set_logging(opt.global_rank)
571
+ #if opt.global_rank in [-1, 0]:
572
+ # check_git_status()
573
+ # check_requirements()
574
+
575
+ # Resume
576
+ wandb_run = check_wandb_resume(opt)
577
+ if opt.resume and not wandb_run: # resume an interrupted run
578
+ ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
579
+ assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
580
+ apriori = opt.global_rank, opt.local_rank
581
+ with open(Path(ckpt).parent.parent / 'opt.yaml') as f:
582
+ opt = argparse.Namespace(**yaml.load(f, Loader=yaml.SafeLoader)) # replace
583
+ opt.cfg, opt.weights, opt.resume, opt.batch_size, opt.global_rank, opt.local_rank = '', ckpt, True, opt.total_batch_size, *apriori # reinstate
584
+ logger.info('Resuming training from %s' % ckpt)
585
+ else:
586
+ # opt.hyp = opt.hyp or ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml')
587
+ opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
588
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
589
+ opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
590
+ opt.name = 'evolve' if opt.evolve else opt.name
591
+ opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve) # increment run
592
+
593
+ # DDP mode
594
+ opt.total_batch_size = opt.batch_size
595
+ device = select_device(opt.device, batch_size=opt.batch_size)
596
+ if opt.local_rank != -1:
597
+ assert torch.cuda.device_count() > opt.local_rank
598
+ torch.cuda.set_device(opt.local_rank)
599
+ device = torch.device('cuda', opt.local_rank)
600
+ dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
601
+ assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count'
602
+ opt.batch_size = opt.total_batch_size // opt.world_size
603
+
604
+ # Hyperparameters
605
+ with open(opt.hyp) as f:
606
+ hyp = yaml.load(f, Loader=yaml.SafeLoader) # load hyps
607
+
608
+ # Train
609
+ logger.info(opt)
610
+ if not opt.evolve:
611
+ tb_writer = None # init loggers
612
+ if opt.global_rank in [-1, 0]:
613
+ prefix = colorstr('tensorboard: ')
614
+ logger.info(f"{prefix}Start with 'tensorboard --logdir {opt.project}', view at http://localhost:6006/")
615
+ tb_writer = SummaryWriter(opt.save_dir) # Tensorboard
616
+ train(hyp, opt, device, tb_writer)
617
+
618
+ # Evolve hyperparameters (optional)
619
+ else:
620
+ # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
621
+ meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
622
+ 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
623
+ 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
624
+ 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
625
+ 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
626
+ 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
627
+ 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
628
+ 'box': (1, 0.02, 0.2), # box loss gain
629
+ 'cls': (1, 0.2, 4.0), # cls loss gain
630
+ 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
631
+ 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
632
+ 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
633
+ 'iou_t': (0, 0.1, 0.7), # IoU training threshold
634
+ 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
635
+ 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
636
+ 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
637
+ 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
638
+ 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
639
+ 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
640
+ 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
641
+ 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
642
+ 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
643
+ 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
644
+ 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
645
+ 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
646
+ 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
647
+ 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
648
+ 'mixup': (1, 0.0, 1.0), # image mixup (probability)
649
+ 'copy_paste': (1, 0.0, 1.0), # segment copy-paste (probability)
650
+ 'paste_in': (1, 0.0, 1.0)} # segment copy-paste (probability)
651
+
652
+ with open(opt.hyp, errors='ignore') as f:
653
+ hyp = yaml.safe_load(f) # load hyps dict
654
+ if 'anchors' not in hyp: # anchors commented in hyp.yaml
655
+ hyp['anchors'] = 3
656
+
657
+ assert opt.local_rank == -1, 'DDP mode not implemented for --evolve'
658
+ opt.notest, opt.nosave = True, True # only test/save final epoch
659
+ # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
660
+ yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here
661
+ if opt.bucket:
662
+ os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
663
+
664
+ for _ in range(300): # generations to evolve
665
+ if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate
666
+ # Select parent(s)
667
+ parent = 'single' # parent selection method: 'single' or 'weighted'
668
+ x = np.loadtxt('evolve.txt', ndmin=2)
669
+ n = min(5, len(x)) # number of previous results to consider
670
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
671
+ w = fitness(x) - fitness(x).min() # weights
672
+ if parent == 'single' or len(x) == 1:
673
+ # x = x[random.randint(0, n - 1)] # random selection
674
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
675
+ elif parent == 'weighted':
676
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
677
+
678
+ # Mutate
679
+ mp, s = 0.8, 0.2 # mutation probability, sigma
680
+ npr = np.random
681
+ npr.seed(int(time.time()))
682
+ g = np.array([x[0] for x in meta.values()]) # gains 0-1
683
+ ng = len(meta)
684
+ v = np.ones(ng)
685
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
686
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
687
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
688
+ hyp[k] = float(x[i + 7] * v[i]) # mutate
689
+
690
+ # Constrain to limits
691
+ for k, v in meta.items():
692
+ hyp[k] = max(hyp[k], v[1]) # lower limit
693
+ hyp[k] = min(hyp[k], v[2]) # upper limit
694
+ hyp[k] = round(hyp[k], 5) # significant digits
695
+
696
+ # Train mutation
697
+ results = train(hyp.copy(), opt, device)
698
+
699
+ # Write mutation results
700
+ print_mutation(hyp.copy(), results, yaml_file, opt.bucket)
701
+
702
+ # Plot results
703
+ plot_evolution(yaml_file)
704
+ print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n'
705
+ f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}')
yolov7detect/train_aux.py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import math
4
+ import os
5
+ import random
6
+ import time
7
+ from copy import deepcopy
8
+ from pathlib import Path
9
+ from threading import Thread
10
+
11
+ import numpy as np
12
+ import torch.distributed as dist
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torch.optim as optim
16
+ import torch.optim.lr_scheduler as lr_scheduler
17
+ import torch.utils.data
18
+ import yaml
19
+ from torch.cuda import amp
20
+ from torch.nn.parallel import DistributedDataParallel as DDP
21
+ from torch.utils.tensorboard import SummaryWriter
22
+ from tqdm import tqdm
23
+
24
+ import test # import test.py to get mAP after each epoch
25
+ from yolov7.models.experimental import attempt_load
26
+ from yolov7.models.yolo import Model
27
+ from yolov7.utils.autoanchor import check_anchors
28
+ from yolov7.utils.datasets import create_dataloader
29
+ from yolov7.utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \
30
+ fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \
31
+ check_requirements, print_mutation, set_logging, one_cycle, colorstr
32
+ from yolov7.utils.google_utils import attempt_download
33
+ from yolov7.utils.loss import ComputeLoss, ComputeLossAuxOTA
34
+ from yolov7.utils.plots import plot_images, plot_labels, plot_results, plot_evolution
35
+ from yolov7.utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first, is_parallel
36
+ from yolov7.utils.wandb_logging.wandb_utils import WandbLogger, check_wandb_resume
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ def train(hyp, opt, device, tb_writer=None):
42
+ logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
43
+ save_dir, epochs, batch_size, total_batch_size, weights, rank = \
44
+ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
45
+
46
+ # Directories
47
+ wdir = save_dir / 'weights'
48
+ wdir.mkdir(parents=True, exist_ok=True) # make dir
49
+ last = wdir / 'last.pt'
50
+ best = wdir / 'best.pt'
51
+ results_file = save_dir / 'results.txt'
52
+
53
+ # Save run settings
54
+ with open(save_dir / 'hyp.yaml', 'w') as f:
55
+ yaml.dump(hyp, f, sort_keys=False)
56
+ with open(save_dir / 'opt.yaml', 'w') as f:
57
+ yaml.dump(vars(opt), f, sort_keys=False)
58
+
59
+ # Configure
60
+ plots = not opt.evolve # create plots
61
+ cuda = device.type != 'cpu'
62
+ init_seeds(2 + rank)
63
+ with open(opt.data) as f:
64
+ data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict
65
+ is_coco = opt.data.endswith('coco.yaml')
66
+
67
+ # Logging- Doing this before checking the dataset. Might update data_dict
68
+ loggers = {'wandb': None} # loggers dict
69
+ if rank in [-1, 0]:
70
+ opt.hyp = hyp # add hyperparameters
71
+ run_id = torch.load(weights).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None
72
+ wandb_logger = WandbLogger(opt, Path(opt.save_dir).stem, run_id, data_dict)
73
+ loggers['wandb'] = wandb_logger.wandb
74
+ data_dict = wandb_logger.data_dict
75
+ if wandb_logger.wandb:
76
+ weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming
77
+
78
+ nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes
79
+ names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
80
+ assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
81
+
82
+ # Model
83
+ pretrained = weights.endswith('.pt')
84
+ if pretrained:
85
+ with torch_distributed_zero_first(rank):
86
+ attempt_download(weights) # download if not found locally
87
+ ckpt = torch.load(weights, map_location=device) # load checkpoint
88
+ model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
89
+ exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys
90
+ state_dict = ckpt['model'].float().state_dict() # to FP32
91
+ state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect
92
+ model.load_state_dict(state_dict, strict=False) # load
93
+ logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report
94
+ else:
95
+ model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
96
+ with torch_distributed_zero_first(rank):
97
+ check_dataset(data_dict) # check
98
+ train_path = data_dict['train']
99
+ test_path = data_dict['val']
100
+
101
+ # Freeze
102
+ freeze = [] # parameter names to freeze (full or partial)
103
+ for k, v in model.named_parameters():
104
+ v.requires_grad = True # train all layers
105
+ if any(x in k for x in freeze):
106
+ print('freezing %s' % k)
107
+ v.requires_grad = False
108
+
109
+ # Optimizer
110
+ nbs = 64 # nominal batch size
111
+ accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
112
+ hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
113
+ logger.info(f"Scaled weight_decay = {hyp['weight_decay']}")
114
+
115
+ pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
116
+ for k, v in model.named_modules():
117
+ if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter):
118
+ pg2.append(v.bias) # biases
119
+ if isinstance(v, nn.BatchNorm2d):
120
+ pg0.append(v.weight) # no decay
121
+ elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter):
122
+ pg1.append(v.weight) # apply decay
123
+ if hasattr(v, 'im'):
124
+ if hasattr(v.im, 'implicit'):
125
+ pg0.append(v.im.implicit)
126
+ else:
127
+ for iv in v.im:
128
+ pg0.append(iv.implicit)
129
+ if hasattr(v, 'imc'):
130
+ if hasattr(v.imc, 'implicit'):
131
+ pg0.append(v.imc.implicit)
132
+ else:
133
+ for iv in v.imc:
134
+ pg0.append(iv.implicit)
135
+ if hasattr(v, 'imb'):
136
+ if hasattr(v.imb, 'implicit'):
137
+ pg0.append(v.imb.implicit)
138
+ else:
139
+ for iv in v.imb:
140
+ pg0.append(iv.implicit)
141
+ if hasattr(v, 'imo'):
142
+ if hasattr(v.imo, 'implicit'):
143
+ pg0.append(v.imo.implicit)
144
+ else:
145
+ for iv in v.imo:
146
+ pg0.append(iv.implicit)
147
+ if hasattr(v, 'ia'):
148
+ if hasattr(v.ia, 'implicit'):
149
+ pg0.append(v.ia.implicit)
150
+ else:
151
+ for iv in v.ia:
152
+ pg0.append(iv.implicit)
153
+ if hasattr(v, 'attn'):
154
+ if hasattr(v.attn, 'logit_scale'):
155
+ pg0.append(v.attn.logit_scale)
156
+ if hasattr(v.attn, 'q_bias'):
157
+ pg0.append(v.attn.q_bias)
158
+ if hasattr(v.attn, 'v_bias'):
159
+ pg0.append(v.attn.v_bias)
160
+ if hasattr(v.attn, 'relative_position_bias_table'):
161
+ pg0.append(v.attn.relative_position_bias_table)
162
+ if hasattr(v, 'rbr_dense'):
163
+ if hasattr(v.rbr_dense, 'weight_rbr_origin'):
164
+ pg0.append(v.rbr_dense.weight_rbr_origin)
165
+ if hasattr(v.rbr_dense, 'weight_rbr_avg_conv'):
166
+ pg0.append(v.rbr_dense.weight_rbr_avg_conv)
167
+ if hasattr(v.rbr_dense, 'weight_rbr_pfir_conv'):
168
+ pg0.append(v.rbr_dense.weight_rbr_pfir_conv)
169
+ if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_idconv1'):
170
+ pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_idconv1)
171
+ if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_conv2'):
172
+ pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_conv2)
173
+ if hasattr(v.rbr_dense, 'weight_rbr_gconv_dw'):
174
+ pg0.append(v.rbr_dense.weight_rbr_gconv_dw)
175
+ if hasattr(v.rbr_dense, 'weight_rbr_gconv_pw'):
176
+ pg0.append(v.rbr_dense.weight_rbr_gconv_pw)
177
+ if hasattr(v.rbr_dense, 'vector'):
178
+ pg0.append(v.rbr_dense.vector)
179
+
180
+ if opt.adam:
181
+ optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
182
+ else:
183
+ optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
184
+
185
+ optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
186
+ optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
187
+ logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
188
+ del pg0, pg1, pg2
189
+
190
+ # Scheduler https://arxiv.org/pdf/1812.01187.pdf
191
+ # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
192
+ if opt.linear_lr:
193
+ lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
194
+ else:
195
+ lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
196
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
197
+ # plot_lr_scheduler(optimizer, scheduler, epochs)
198
+
199
+ # EMA
200
+ ema = ModelEMA(model) if rank in [-1, 0] else None
201
+
202
+ # Resume
203
+ start_epoch, best_fitness = 0, 0.0
204
+ if pretrained:
205
+ # Optimizer
206
+ if ckpt['optimizer'] is not None:
207
+ optimizer.load_state_dict(ckpt['optimizer'])
208
+ best_fitness = ckpt['best_fitness']
209
+
210
+ # EMA
211
+ if ema and ckpt.get('ema'):
212
+ ema.ema.load_state_dict(ckpt['ema'].float().state_dict())
213
+ ema.updates = ckpt['updates']
214
+
215
+ # Results
216
+ if ckpt.get('training_results') is not None:
217
+ results_file.write_text(ckpt['training_results']) # write results.txt
218
+
219
+ # Epochs
220
+ start_epoch = ckpt['epoch'] + 1
221
+ if opt.resume:
222
+ assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs)
223
+ if epochs < start_epoch:
224
+ logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
225
+ (weights, ckpt['epoch'], epochs))
226
+ epochs += ckpt['epoch'] # finetune additional epochs
227
+
228
+ del ckpt, state_dict
229
+
230
+ # Image sizes
231
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
232
+ nl = model.model[-1].nl # number of detection layers (used for scaling hyp['obj'])
233
+ imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
234
+
235
+ # DP mode
236
+ if cuda and rank == -1 and torch.cuda.device_count() > 1:
237
+ model = torch.nn.DataParallel(model)
238
+
239
+ # SyncBatchNorm
240
+ if opt.sync_bn and cuda and rank != -1:
241
+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
242
+ logger.info('Using SyncBatchNorm()')
243
+
244
+ # Trainloader
245
+ dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt,
246
+ hyp=hyp, augment=True, cache=opt.cache_images, rect=opt.rect, rank=rank,
247
+ world_size=opt.world_size, workers=opt.workers,
248
+ image_weights=opt.image_weights, quad=opt.quad, prefix=colorstr('train: '))
249
+ mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
250
+ nb = len(dataloader) # number of batches
251
+ assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)
252
+
253
+ # Process 0
254
+ if rank in [-1, 0]:
255
+ testloader = create_dataloader(test_path, imgsz_test, batch_size * 2, gs, opt, # testloader
256
+ hyp=hyp, cache=opt.cache_images and not opt.notest, rect=True, rank=-1,
257
+ world_size=opt.world_size, workers=opt.workers,
258
+ pad=0.5, prefix=colorstr('val: '))[0]
259
+
260
+ if not opt.resume:
261
+ labels = np.concatenate(dataset.labels, 0)
262
+ c = torch.tensor(labels[:, 0]) # classes
263
+ # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
264
+ # model._initialize_biases(cf.to(device))
265
+ if plots:
266
+ #plot_labels(labels, names, save_dir, loggers)
267
+ if tb_writer:
268
+ tb_writer.add_histogram('classes', c, 0)
269
+
270
+ # Anchors
271
+ if not opt.noautoanchor:
272
+ check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
273
+ model.half().float() # pre-reduce anchor precision
274
+
275
+ # DDP mode
276
+ if cuda and rank != -1:
277
+ model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank,
278
+ # nn.MultiheadAttention incompatibility with DDP https://github.com/pytorch/pytorch/issues/26698
279
+ find_unused_parameters=any(isinstance(layer, nn.MultiheadAttention) for layer in model.modules()))
280
+
281
+ # Model parameters
282
+ hyp['box'] *= 3. / nl # scale to layers
283
+ hyp['cls'] *= nc / 80. * 3. / nl # scale to classes and layers
284
+ hyp['obj'] *= (imgsz / 640) ** 2 * 3. / nl # scale to image size and layers
285
+ hyp['label_smoothing'] = opt.label_smoothing
286
+ model.nc = nc # attach number of classes to model
287
+ model.hyp = hyp # attach hyperparameters to model
288
+ model.gr = 1.0 # iou loss ratio (obj_loss = 1.0 or iou)
289
+ model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
290
+ model.names = names
291
+
292
+ # Start training
293
+ t0 = time.time()
294
+ nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations)
295
+ # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
296
+ maps = np.zeros(nc) # mAP per class
297
+ results = (0, 0, 0, 0, 0, 0, 0) # P, R, [email protected], [email protected], val_loss(box, obj, cls)
298
+ scheduler.last_epoch = start_epoch - 1 # do not move
299
+ scaler = amp.GradScaler(enabled=cuda)
300
+ compute_loss_ota = ComputeLossAuxOTA(model) # init loss class
301
+ compute_loss = ComputeLoss(model) # init loss class
302
+ logger.info(f'Image sizes {imgsz} train, {imgsz_test} test\n'
303
+ f'Using {dataloader.num_workers} dataloader workers\n'
304
+ f'Logging results to {save_dir}\n'
305
+ f'Starting training for {epochs} epochs...')
306
+ torch.save(model, wdir / 'init.pt')
307
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
308
+ model.train()
309
+
310
+ # Update image weights (optional)
311
+ if opt.image_weights:
312
+ # Generate indices
313
+ if rank in [-1, 0]:
314
+ cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
315
+ iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
316
+ dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
317
+ # Broadcast if DDP
318
+ if rank != -1:
319
+ indices = (torch.tensor(dataset.indices) if rank == 0 else torch.zeros(dataset.n)).int()
320
+ dist.broadcast(indices, 0)
321
+ if rank != 0:
322
+ dataset.indices = indices.cpu().numpy()
323
+
324
+ # Update mosaic border
325
+ # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
326
+ # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
327
+
328
+ mloss = torch.zeros(4, device=device) # mean losses
329
+ if rank != -1:
330
+ dataloader.sampler.set_epoch(epoch)
331
+ pbar = enumerate(dataloader)
332
+ logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'labels', 'img_size'))
333
+ if rank in [-1, 0]:
334
+ pbar = tqdm(pbar, total=nb) # progress bar
335
+ optimizer.zero_grad()
336
+ for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
337
+ ni = i + nb * epoch # number integrated batches (since train start)
338
+ imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0
339
+
340
+ # Warmup
341
+ if ni <= nw:
342
+ xi = [0, nw] # x interp
343
+ # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
344
+ accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())
345
+ for j, x in enumerate(optimizer.param_groups):
346
+ # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
347
+ x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
348
+ if 'momentum' in x:
349
+ x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
350
+
351
+ # Multi-scale
352
+ if opt.multi_scale:
353
+ sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
354
+ sf = sz / max(imgs.shape[2:]) # scale factor
355
+ if sf != 1:
356
+ ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
357
+ imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
358
+
359
+ # Forward
360
+ with amp.autocast(enabled=cuda):
361
+ pred = model(imgs) # forward
362
+ loss, loss_items = compute_loss_ota(pred, targets.to(device), imgs) # loss scaled by batch_size
363
+ if rank != -1:
364
+ loss *= opt.world_size # gradient averaged between devices in DDP mode
365
+ if opt.quad:
366
+ loss *= 4.
367
+
368
+ # Backward
369
+ scaler.scale(loss).backward()
370
+
371
+ # Optimize
372
+ if ni % accumulate == 0:
373
+ scaler.step(optimizer) # optimizer.step
374
+ scaler.update()
375
+ optimizer.zero_grad()
376
+ if ema:
377
+ ema.update(model)
378
+
379
+ # Print
380
+ if rank in [-1, 0]:
381
+ mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
382
+ mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
383
+ s = ('%10s' * 2 + '%10.4g' * 6) % (
384
+ '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
385
+ pbar.set_description(s)
386
+
387
+ # Plot
388
+ if plots and ni < 10:
389
+ f = save_dir / f'train_batch{ni}.jpg' # filename
390
+ Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
391
+ # if tb_writer:
392
+ # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch)
393
+ # tb_writer.add_graph(torch.jit.trace(model, imgs, strict=False), []) # add model graph
394
+ elif plots and ni == 10 and wandb_logger.wandb:
395
+ wandb_logger.log({"Mosaics": [wandb_logger.wandb.Image(str(x), caption=x.name) for x in
396
+ save_dir.glob('train*.jpg') if x.exists()]})
397
+
398
+ # end batch ------------------------------------------------------------------------------------------------
399
+ # end epoch ----------------------------------------------------------------------------------------------------
400
+
401
+ # Scheduler
402
+ lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard
403
+ scheduler.step()
404
+
405
+ # DDP process 0 or single-GPU
406
+ if rank in [-1, 0]:
407
+ # mAP
408
+ ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride', 'class_weights'])
409
+ final_epoch = epoch + 1 == epochs
410
+ if not opt.notest or final_epoch: # Calculate mAP
411
+ wandb_logger.current_epoch = epoch + 1
412
+ results, maps, times = test.test(data_dict,
413
+ batch_size=batch_size * 2,
414
+ imgsz=imgsz_test,
415
+ model=ema.ema,
416
+ single_cls=opt.single_cls,
417
+ dataloader=testloader,
418
+ save_dir=save_dir,
419
+ verbose=nc < 50 and final_epoch,
420
+ plots=plots and final_epoch,
421
+ wandb_logger=wandb_logger,
422
+ compute_loss=compute_loss,
423
+ is_coco=is_coco,
424
+ v5_metric=opt.v5_metric)
425
+
426
+ # Write
427
+ with open(results_file, 'a') as f:
428
+ f.write(s + '%10.4g' * 7 % results + '\n') # append metrics, val_loss
429
+ if len(opt.name) and opt.bucket:
430
+ os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name))
431
+
432
+ # Log
433
+ tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
434
+ 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
435
+ 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
436
+ 'x/lr0', 'x/lr1', 'x/lr2'] # params
437
+ for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags):
438
+ if tb_writer:
439
+ tb_writer.add_scalar(tag, x, epoch) # tensorboard
440
+ if wandb_logger.wandb:
441
+ wandb_logger.log({tag: x}) # W&B
442
+
443
+ # Update best mAP
444
+ fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, [email protected], [email protected]]
445
+ if fi > best_fitness:
446
+ best_fitness = fi
447
+ wandb_logger.end_epoch(best_result=best_fitness == fi)
448
+
449
+ # Save model
450
+ if (not opt.nosave) or (final_epoch and not opt.evolve): # if save
451
+ ckpt = {'epoch': epoch,
452
+ 'best_fitness': best_fitness,
453
+ 'training_results': results_file.read_text(),
454
+ 'model': deepcopy(model.module if is_parallel(model) else model).half(),
455
+ 'ema': deepcopy(ema.ema).half(),
456
+ 'updates': ema.updates,
457
+ 'optimizer': optimizer.state_dict(),
458
+ 'wandb_id': wandb_logger.wandb_run.id if wandb_logger.wandb else None}
459
+
460
+ # Save last, best and delete
461
+ torch.save(ckpt, last)
462
+ if best_fitness == fi:
463
+ torch.save(ckpt, best)
464
+ if (best_fitness == fi) and (epoch >= 200):
465
+ torch.save(ckpt, wdir / 'best_{:03d}.pt'.format(epoch))
466
+ if epoch == 0:
467
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
468
+ elif ((epoch+1) % 25) == 0:
469
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
470
+ elif epoch >= (epochs-5):
471
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
472
+ if wandb_logger.wandb:
473
+ if ((epoch + 1) % opt.save_period == 0 and not final_epoch) and opt.save_period != -1:
474
+ wandb_logger.log_model(
475
+ last.parent, opt, epoch, fi, best_model=best_fitness == fi)
476
+ del ckpt
477
+
478
+ # end epoch ----------------------------------------------------------------------------------------------------
479
+ # end training
480
+ if rank in [-1, 0]:
481
+ # Plots
482
+ if plots:
483
+ plot_results(save_dir=save_dir) # save as results.png
484
+ if wandb_logger.wandb:
485
+ files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]]
486
+ wandb_logger.log({"Results": [wandb_logger.wandb.Image(str(save_dir / f), caption=f) for f in files
487
+ if (save_dir / f).exists()]})
488
+ # Test best.pt
489
+ logger.info('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
490
+ if opt.data.endswith('coco.yaml') and nc == 80: # if COCO
491
+ for m in (last, best) if best.exists() else (last): # speed, mAP tests
492
+ results, _, _ = test.test(opt.data,
493
+ batch_size=batch_size * 2,
494
+ imgsz=imgsz_test,
495
+ conf_thres=0.001,
496
+ iou_thres=0.7,
497
+ model=attempt_load(m, device).half(),
498
+ single_cls=opt.single_cls,
499
+ dataloader=testloader,
500
+ save_dir=save_dir,
501
+ save_json=True,
502
+ plots=False,
503
+ is_coco=is_coco,
504
+ v5_metric=opt.v5_metric)
505
+
506
+ # Strip optimizers
507
+ final = best if best.exists() else last # final model
508
+ for f in last, best:
509
+ if f.exists():
510
+ strip_optimizer(f) # strip optimizers
511
+ if opt.bucket:
512
+ os.system(f'gsutil cp {final} gs://{opt.bucket}/weights') # upload
513
+ if wandb_logger.wandb and not opt.evolve: # Log the stripped model
514
+ wandb_logger.wandb.log_artifact(str(final), type='model',
515
+ name='run_' + wandb_logger.wandb_run.id + '_model',
516
+ aliases=['last', 'best', 'stripped'])
517
+ wandb_logger.finish_run()
518
+ else:
519
+ dist.destroy_process_group()
520
+ torch.cuda.empty_cache()
521
+ return results
522
+
523
+
524
+ if __name__ == '__main__':
525
+ parser = argparse.ArgumentParser()
526
+ parser.add_argument('--weights', type=str, default='yolo7.pt', help='initial weights path')
527
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
528
+ parser.add_argument('--data', type=str, default='data/coco.yaml', help='data.yaml path')
529
+ parser.add_argument('--hyp', type=str, default='data/hyp.scratch.p5.yaml', help='hyperparameters path')
530
+ parser.add_argument('--epochs', type=int, default=300)
531
+ parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
532
+ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
533
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
534
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
535
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
536
+ parser.add_argument('--notest', action='store_true', help='only test final epoch')
537
+ parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
538
+ parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
539
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
540
+ parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
541
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
542
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
543
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
544
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
545
+ parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
546
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
547
+ parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
548
+ parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers')
549
+ parser.add_argument('--project', default='runs/train', help='save to project/name')
550
+ parser.add_argument('--entity', default=None, help='W&B entity')
551
+ parser.add_argument('--name', default='exp', help='save to project/name')
552
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
553
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
554
+ parser.add_argument('--linear-lr', action='store_true', help='linear LR')
555
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
556
+ parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table')
557
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B')
558
+ parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch')
559
+ parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used')
560
+ parser.add_argument('--v5-metric', action='store_true', help='assume maximum recall as 1.0 in AP calculation')
561
+ opt = parser.parse_args()
562
+
563
+ # Set DDP variables
564
+ opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1
565
+ opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1
566
+ set_logging(opt.global_rank)
567
+ #if opt.global_rank in [-1, 0]:
568
+ # check_git_status()
569
+ # check_requirements()
570
+
571
+ # Resume
572
+ wandb_run = check_wandb_resume(opt)
573
+ if opt.resume and not wandb_run: # resume an interrupted run
574
+ ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
575
+ assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
576
+ apriori = opt.global_rank, opt.local_rank
577
+ with open(Path(ckpt).parent.parent / 'opt.yaml') as f:
578
+ opt = argparse.Namespace(**yaml.load(f, Loader=yaml.SafeLoader)) # replace
579
+ opt.cfg, opt.weights, opt.resume, opt.batch_size, opt.global_rank, opt.local_rank = '', ckpt, True, opt.total_batch_size, *apriori # reinstate
580
+ logger.info('Resuming training from %s' % ckpt)
581
+ else:
582
+ # opt.hyp = opt.hyp or ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml')
583
+ opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
584
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
585
+ opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
586
+ opt.name = 'evolve' if opt.evolve else opt.name
587
+ opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve) # increment run
588
+
589
+ # DDP mode
590
+ opt.total_batch_size = opt.batch_size
591
+ device = select_device(opt.device, batch_size=opt.batch_size)
592
+ if opt.local_rank != -1:
593
+ assert torch.cuda.device_count() > opt.local_rank
594
+ torch.cuda.set_device(opt.local_rank)
595
+ device = torch.device('cuda', opt.local_rank)
596
+ dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
597
+ assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count'
598
+ opt.batch_size = opt.total_batch_size // opt.world_size
599
+
600
+ # Hyperparameters
601
+ with open(opt.hyp) as f:
602
+ hyp = yaml.load(f, Loader=yaml.SafeLoader) # load hyps
603
+
604
+ # Train
605
+ logger.info(opt)
606
+ if not opt.evolve:
607
+ tb_writer = None # init loggers
608
+ if opt.global_rank in [-1, 0]:
609
+ prefix = colorstr('tensorboard: ')
610
+ logger.info(f"{prefix}Start with 'tensorboard --logdir {opt.project}', view at http://localhost:6006/")
611
+ tb_writer = SummaryWriter(opt.save_dir) # Tensorboard
612
+ train(hyp, opt, device, tb_writer)
613
+
614
+ # Evolve hyperparameters (optional)
615
+ else:
616
+ # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
617
+ meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
618
+ 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
619
+ 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
620
+ 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
621
+ 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
622
+ 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
623
+ 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
624
+ 'box': (1, 0.02, 0.2), # box loss gain
625
+ 'cls': (1, 0.2, 4.0), # cls loss gain
626
+ 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
627
+ 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
628
+ 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
629
+ 'iou_t': (0, 0.1, 0.7), # IoU training threshold
630
+ 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
631
+ 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
632
+ 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
633
+ 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
634
+ 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
635
+ 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
636
+ 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
637
+ 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
638
+ 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
639
+ 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
640
+ 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
641
+ 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
642
+ 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
643
+ 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
644
+ 'mixup': (1, 0.0, 1.0)} # image mixup (probability)
645
+
646
+ with open(opt.hyp, errors='ignore') as f:
647
+ hyp = yaml.safe_load(f) # load hyps dict
648
+ if 'anchors' not in hyp: # anchors commented in hyp.yaml
649
+ hyp['anchors'] = 3
650
+
651
+ assert opt.local_rank == -1, 'DDP mode not implemented for --evolve'
652
+ opt.notest, opt.nosave = True, True # only test/save final epoch
653
+ # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
654
+ yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here
655
+ if opt.bucket:
656
+ os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
657
+
658
+ for _ in range(300): # generations to evolve
659
+ if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate
660
+ # Select parent(s)
661
+ parent = 'single' # parent selection method: 'single' or 'weighted'
662
+ x = np.loadtxt('evolve.txt', ndmin=2)
663
+ n = min(5, len(x)) # number of previous results to consider
664
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
665
+ w = fitness(x) - fitness(x).min() # weights
666
+ if parent == 'single' or len(x) == 1:
667
+ # x = x[random.randint(0, n - 1)] # random selection
668
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
669
+ elif parent == 'weighted':
670
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
671
+
672
+ # Mutate
673
+ mp, s = 0.8, 0.2 # mutation probability, sigma
674
+ npr = np.random
675
+ npr.seed(int(time.time()))
676
+ g = np.array([x[0] for x in meta.values()]) # gains 0-1
677
+ ng = len(meta)
678
+ v = np.ones(ng)
679
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
680
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
681
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
682
+ hyp[k] = float(x[i + 7] * v[i]) # mutate
683
+
684
+ # Constrain to limits
685
+ for k, v in meta.items():
686
+ hyp[k] = max(hyp[k], v[1]) # lower limit
687
+ hyp[k] = min(hyp[k], v[2]) # upper limit
688
+ hyp[k] = round(hyp[k], 5) # significant digits
689
+
690
+ # Train mutation
691
+ results = train(hyp.copy(), opt, device)
692
+
693
+ # Write mutation results
694
+ print_mutation(hyp.copy(), results, yaml_file, opt.bucket)
695
+
696
+ # Plot results
697
+ plot_evolution(yaml_file)
698
+ print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n'
699
+ f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}')
yolov7detect/utils/activations.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Activation functions
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
9
+ class SiLU(nn.Module): # export-friendly version of nn.SiLU()
10
+ @staticmethod
11
+ def forward(x):
12
+ return x * torch.sigmoid(x)
13
+
14
+
15
+ class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
16
+ @staticmethod
17
+ def forward(x):
18
+ # return x * F.hardsigmoid(x) # for torchscript and CoreML
19
+ return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
20
+
21
+
22
+ class MemoryEfficientSwish(nn.Module):
23
+ class F(torch.autograd.Function):
24
+ @staticmethod
25
+ def forward(ctx, x):
26
+ ctx.save_for_backward(x)
27
+ return x * torch.sigmoid(x)
28
+
29
+ @staticmethod
30
+ def backward(ctx, grad_output):
31
+ x = ctx.saved_tensors[0]
32
+ sx = torch.sigmoid(x)
33
+ return grad_output * (sx * (1 + x * (1 - sx)))
34
+
35
+ def forward(self, x):
36
+ return self.F.apply(x)
37
+
38
+
39
+ # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
40
+ class Mish(nn.Module):
41
+ @staticmethod
42
+ def forward(x):
43
+ return x * F.softplus(x).tanh()
44
+
45
+
46
+ class MemoryEfficientMish(nn.Module):
47
+ class F(torch.autograd.Function):
48
+ @staticmethod
49
+ def forward(ctx, x):
50
+ ctx.save_for_backward(x)
51
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
52
+
53
+ @staticmethod
54
+ def backward(ctx, grad_output):
55
+ x = ctx.saved_tensors[0]
56
+ sx = torch.sigmoid(x)
57
+ fx = F.softplus(x).tanh()
58
+ return grad_output * (fx + x * sx * (1 - fx * fx))
59
+
60
+ def forward(self, x):
61
+ return self.F.apply(x)
62
+
63
+
64
+ # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
65
+ class FReLU(nn.Module):
66
+ def __init__(self, c1, k=3): # ch_in, kernel
67
+ super().__init__()
68
+ self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
69
+ self.bn = nn.BatchNorm2d(c1)
70
+
71
+ def forward(self, x):
72
+ return torch.max(x, self.bn(self.conv(x)))
yolov7detect/utils/add_nms.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import onnx
3
+ from onnx import shape_inference
4
+ try:
5
+ import onnx_graphsurgeon as gs
6
+ except Exception as e:
7
+ print('Import onnx_graphsurgeon failure: %s' % e)
8
+
9
+ import logging
10
+
11
+ LOGGER = logging.getLogger(__name__)
12
+
13
+ class RegisterNMS(object):
14
+ def __init__(
15
+ self,
16
+ onnx_model_path: str,
17
+ precision: str = "fp32",
18
+ ):
19
+
20
+ self.graph = gs.import_onnx(onnx.load(onnx_model_path))
21
+ assert self.graph
22
+ LOGGER.info("ONNX graph created successfully")
23
+ # Fold constants via ONNX-GS that PyTorch2ONNX may have missed
24
+ self.graph.fold_constants()
25
+ self.precision = precision
26
+ self.batch_size = 1
27
+ def infer(self):
28
+ """
29
+ Sanitize the graph by cleaning any unconnected nodes, do a topological resort,
30
+ and fold constant inputs values. When possible, run shape inference on the
31
+ ONNX graph to determine tensor shapes.
32
+ """
33
+ for _ in range(3):
34
+ count_before = len(self.graph.nodes)
35
+
36
+ self.graph.cleanup().toposort()
37
+ try:
38
+ for node in self.graph.nodes:
39
+ for o in node.outputs:
40
+ o.shape = None
41
+ model = gs.export_onnx(self.graph)
42
+ model = shape_inference.infer_shapes(model)
43
+ self.graph = gs.import_onnx(model)
44
+ except Exception as e:
45
+ LOGGER.info(f"Shape inference could not be performed at this time:\n{e}")
46
+ try:
47
+ self.graph.fold_constants(fold_shapes=True)
48
+ except TypeError as e:
49
+ LOGGER.error(
50
+ "This version of ONNX GraphSurgeon does not support folding shapes, "
51
+ f"please upgrade your onnx_graphsurgeon module. Error:\n{e}"
52
+ )
53
+ raise
54
+
55
+ count_after = len(self.graph.nodes)
56
+ if count_before == count_after:
57
+ # No new folding occurred in this iteration, so we can stop for now.
58
+ break
59
+
60
+ def save(self, output_path):
61
+ """
62
+ Save the ONNX model to the given location.
63
+ Args:
64
+ output_path: Path pointing to the location where to write
65
+ out the updated ONNX model.
66
+ """
67
+ self.graph.cleanup().toposort()
68
+ model = gs.export_onnx(self.graph)
69
+ onnx.save(model, output_path)
70
+ LOGGER.info(f"Saved ONNX model to {output_path}")
71
+
72
+ def register_nms(
73
+ self,
74
+ *,
75
+ score_thresh: float = 0.25,
76
+ nms_thresh: float = 0.45,
77
+ detections_per_img: int = 100,
78
+ ):
79
+ """
80
+ Register the ``EfficientNMS_TRT`` plugin node.
81
+ NMS expects these shapes for its input tensors:
82
+ - box_net: [batch_size, number_boxes, 4]
83
+ - class_net: [batch_size, number_boxes, number_labels]
84
+ Args:
85
+ score_thresh (float): The scalar threshold for score (low scoring boxes are removed).
86
+ nms_thresh (float): The scalar threshold for IOU (new boxes that have high IOU
87
+ overlap with previously selected boxes are removed).
88
+ detections_per_img (int): Number of best detections to keep after NMS.
89
+ """
90
+
91
+ self.infer()
92
+ # Find the concat node at the end of the network
93
+ op_inputs = self.graph.outputs
94
+ op = "EfficientNMS_TRT"
95
+ attrs = {
96
+ "plugin_version": "1",
97
+ "background_class": -1, # no background class
98
+ "max_output_boxes": detections_per_img,
99
+ "score_threshold": score_thresh,
100
+ "iou_threshold": nms_thresh,
101
+ "score_activation": False,
102
+ "box_coding": 0,
103
+ }
104
+
105
+ if self.precision == "fp32":
106
+ dtype_output = np.float32
107
+ elif self.precision == "fp16":
108
+ dtype_output = np.float16
109
+ else:
110
+ raise NotImplementedError(f"Currently not supports precision: {self.precision}")
111
+
112
+ # NMS Outputs
113
+ output_num_detections = gs.Variable(
114
+ name="num_dets",
115
+ dtype=np.int32,
116
+ shape=[self.batch_size, 1],
117
+ ) # A scalar indicating the number of valid detections per batch image.
118
+ output_boxes = gs.Variable(
119
+ name="det_boxes",
120
+ dtype=dtype_output,
121
+ shape=[self.batch_size, detections_per_img, 4],
122
+ )
123
+ output_scores = gs.Variable(
124
+ name="det_scores",
125
+ dtype=dtype_output,
126
+ shape=[self.batch_size, detections_per_img],
127
+ )
128
+ output_labels = gs.Variable(
129
+ name="det_classes",
130
+ dtype=np.int32,
131
+ shape=[self.batch_size, detections_per_img],
132
+ )
133
+
134
+ op_outputs = [output_num_detections, output_boxes, output_scores, output_labels]
135
+
136
+ # Create the NMS Plugin node with the selected inputs. The outputs of the node will also
137
+ # become the final outputs of the graph.
138
+ self.graph.layer(op=op, name="batched_nms", inputs=op_inputs, outputs=op_outputs, attrs=attrs)
139
+ LOGGER.info(f"Created NMS plugin '{op}' with attributes: {attrs}")
140
+
141
+ self.graph.outputs = op_outputs
142
+
143
+ self.infer()
144
+
145
+ def save(self, output_path):
146
+ """
147
+ Save the ONNX model to the given location.
148
+ Args:
149
+ output_path: Path pointing to the location where to write
150
+ out the updated ONNX model.
151
+ """
152
+ self.graph.cleanup().toposort()
153
+ model = gs.export_onnx(self.graph)
154
+ onnx.save(model, output_path)
155
+ LOGGER.info(f"Saved ONNX model to {output_path}")
yolov7detect/utils/autoanchor.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-anchor utils
2
+
3
+ import numpy as np
4
+ import torch
5
+ import yaml
6
+ from scipy.cluster.vq import kmeans
7
+ from tqdm import tqdm
8
+
9
+ from yolov7.utils.general import colorstr
10
+
11
+
12
+ def check_anchor_order(m):
13
+ # Check anchor order against stride order for YOLO Detect() module m, and correct if necessary
14
+ a = m.anchor_grid.prod(-1).view(-1) # anchor area
15
+ da = a[-1] - a[0] # delta a
16
+ ds = m.stride[-1] - m.stride[0] # delta s
17
+ if da.sign() != ds.sign(): # same order
18
+ print('Reversing anchor order')
19
+ m.anchors[:] = m.anchors.flip(0)
20
+ m.anchor_grid[:] = m.anchor_grid.flip(0)
21
+
22
+
23
+ def check_anchors(dataset, model, thr=4.0, imgsz=640):
24
+ # Check anchor fit to data, recompute if necessary
25
+ prefix = colorstr('autoanchor: ')
26
+ print(f'\n{prefix}Analyzing anchors... ', end='')
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
+ anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
41
+ bpr, aat = metric(anchors)
42
+ print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
43
+ if bpr < 0.98: # threshold to recompute
44
+ print('. Attempting to improve anchors, please wait...')
45
+ na = m.anchor_grid.numel() // 2 # number of anchors
46
+ try:
47
+ anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
48
+ except Exception as e:
49
+ print(f'{prefix}ERROR: {e}')
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.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
54
+ check_anchor_order(m)
55
+ m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
56
+ print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
57
+ else:
58
+ print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
59
+ print('') # newline
60
+
61
+
62
+ def kmean_anchors(path='./data/coco.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
+ path: path to dataset *.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
+ thr = 1. / thr
80
+ prefix = colorstr('autoanchor: ')
81
+
82
+ def metric(k, wh): # compute metrics
83
+ r = wh[:, None] / k[None]
84
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
85
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
86
+ return x, x.max(1)[0] # x, best_x
87
+
88
+ def anchor_fitness(k): # mutation fitness
89
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
90
+ return (best * (best > thr).float()).mean() # fitness
91
+
92
+ def print_results(k):
93
+ k = k[np.argsort(k.prod(1))] # sort small to large
94
+ x, best = metric(k, wh0)
95
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
96
+ print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
97
+ print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
98
+ f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
99
+ for i, x in enumerate(k):
100
+ print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
101
+ return k
102
+
103
+ if isinstance(path, str): # *.yaml file
104
+ with open(path) as f:
105
+ data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict
106
+ from utils.datasets import LoadImagesAndLabels
107
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
108
+ else:
109
+ dataset = path # dataset
110
+
111
+ # Get label wh
112
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
113
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
114
+
115
+ # Filter
116
+ i = (wh0 < 3.0).any(1).sum()
117
+ if i:
118
+ print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
119
+ wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
120
+ # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
121
+
122
+ # Kmeans calculation
123
+ print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
124
+ s = wh.std(0) # sigmas for whitening
125
+ k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
126
+ assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
127
+ k *= s
128
+ wh = torch.tensor(wh, dtype=torch.float32) # filtered
129
+ wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
130
+ k = print_results(k)
131
+
132
+ # Plot
133
+ # k, d = [None] * 20, [None] * 20
134
+ # for i in tqdm(range(1, 21)):
135
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
136
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
137
+ # ax = ax.ravel()
138
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
139
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
140
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
141
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
142
+ # fig.savefig('wh.png', dpi=200)
143
+
144
+ # Evolve
145
+ npr = np.random
146
+ f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
147
+ pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
148
+ for _ in pbar:
149
+ v = np.ones(sh)
150
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
151
+ v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
152
+ kg = (k.copy() * v).clip(min=2.0)
153
+ fg = anchor_fitness(kg)
154
+ if fg > f:
155
+ f, k = fg, kg.copy()
156
+ pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
157
+ if verbose:
158
+ print_results(k)
159
+
160
+ return print_results(k)
yolov7detect/utils/aws/resume.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Resume all interrupted trainings in yolor/ dir including DDP trainings
2
+ # Usage: $ python utils/aws/resume.py
3
+
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ import yaml
10
+
11
+ sys.path.append('./') # to run '$ python *.py' files in subdirectories
12
+
13
+ port = 0 # --master_port
14
+ path = Path('').resolve()
15
+ for last in path.rglob('*/**/last.pt'):
16
+ ckpt = torch.load(last)
17
+ if ckpt['optimizer'] is None:
18
+ continue
19
+
20
+ # Load opt.yaml
21
+ with open(last.parent.parent / 'opt.yaml') as f:
22
+ opt = yaml.load(f, Loader=yaml.SafeLoader)
23
+
24
+ # Get device count
25
+ d = opt['device'].split(',') # devices
26
+ nd = len(d) # number of devices
27
+ ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel
28
+
29
+ if ddp: # multi-GPU
30
+ port += 1
31
+ cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}'
32
+ else: # single-GPU
33
+ cmd = f'python train.py --resume {last}'
34
+
35
+ cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread
36
+ print(cmd)
37
+ os.system(cmd)
yolov7detect/utils/datasets.py ADDED
@@ -0,0 +1,1320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset utils and dataloaders
2
+
3
+ import glob
4
+ import logging
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 ThreadPool
12
+ from pathlib import Path
13
+ from threading import Thread
14
+
15
+ import cv2
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from PIL import Image, ExifTags
20
+ from torch.utils.data import Dataset
21
+ from tqdm import tqdm
22
+
23
+ import pickle
24
+ from copy import deepcopy
25
+ #from pycocotools import mask as maskUtils
26
+ from torchvision.utils import save_image
27
+ from torchvision.ops import roi_pool, roi_align, ps_roi_pool, ps_roi_align
28
+
29
+ from yolov7.utils.general import check_requirements, xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, \
30
+ resample_segments, clean_str
31
+ from yolov7.utils.torch_utils import torch_distributed_zero_first
32
+
33
+ # Parameters
34
+ help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
35
+ img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
36
+ vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # Get orientation exif tag
40
+ for orientation in ExifTags.TAGS.keys():
41
+ if ExifTags.TAGS[orientation] == 'Orientation':
42
+ break
43
+
44
+
45
+ def get_hash(files):
46
+ # Returns a single hash value of a list of files
47
+ return sum(os.path.getsize(f) for f in files if os.path.isfile(f))
48
+
49
+
50
+ def exif_size(img):
51
+ # Returns exif-corrected PIL size
52
+ s = img.size # (width, height)
53
+ try:
54
+ rotation = dict(img._getexif().items())[orientation]
55
+ if rotation == 6: # rotation 270
56
+ s = (s[1], s[0])
57
+ elif rotation == 8: # rotation 90
58
+ s = (s[1], s[0])
59
+ except:
60
+ pass
61
+
62
+ return s
63
+
64
+
65
+ def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,
66
+ rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):
67
+ # Make sure only the first process in DDP process the dataset first, and the following others can use the cache
68
+ with torch_distributed_zero_first(rank):
69
+ dataset = LoadImagesAndLabels(path, imgsz, batch_size,
70
+ augment=augment, # augment images
71
+ hyp=hyp, # augmentation hyperparameters
72
+ rect=rect, # rectangular training
73
+ cache_images=cache,
74
+ single_cls=opt.single_cls,
75
+ stride=int(stride),
76
+ pad=pad,
77
+ image_weights=image_weights,
78
+ prefix=prefix)
79
+
80
+ batch_size = min(batch_size, len(dataset))
81
+ nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers
82
+ sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
83
+ loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
84
+ # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()
85
+ dataloader = loader(dataset,
86
+ batch_size=batch_size,
87
+ num_workers=nw,
88
+ sampler=sampler,
89
+ pin_memory=True,
90
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
91
+ return dataloader, dataset
92
+
93
+
94
+ class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
95
+ """ Dataloader that reuses workers
96
+
97
+ Uses same syntax as vanilla DataLoader
98
+ """
99
+
100
+ def __init__(self, *args, **kwargs):
101
+ super().__init__(*args, **kwargs)
102
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
103
+ self.iterator = super().__iter__()
104
+
105
+ def __len__(self):
106
+ return len(self.batch_sampler.sampler)
107
+
108
+ def __iter__(self):
109
+ for i in range(len(self)):
110
+ yield next(self.iterator)
111
+
112
+
113
+ class _RepeatSampler(object):
114
+ """ Sampler that repeats forever
115
+
116
+ Args:
117
+ sampler (Sampler)
118
+ """
119
+
120
+ def __init__(self, sampler):
121
+ self.sampler = sampler
122
+
123
+ def __iter__(self):
124
+ while True:
125
+ yield from iter(self.sampler)
126
+
127
+
128
+ class LoadImages: # for inference
129
+ def __init__(self, path, img_size=640, stride=32):
130
+ p = str(Path(path).absolute()) # os-agnostic absolute path
131
+ if '*' in p:
132
+ files = sorted(glob.glob(p, recursive=True)) # glob
133
+ elif os.path.isdir(p):
134
+ files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
135
+ elif os.path.isfile(p):
136
+ files = [p] # files
137
+ else:
138
+ raise Exception(f'ERROR: {p} does not exist')
139
+
140
+ images = [x for x in files if x.split('.')[-1].lower() in img_formats]
141
+ videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
142
+ ni, nv = len(images), len(videos)
143
+
144
+ self.img_size = img_size
145
+ self.stride = stride
146
+ self.files = images + videos
147
+ self.nf = ni + nv # number of files
148
+ self.video_flag = [False] * ni + [True] * nv
149
+ self.mode = 'image'
150
+ if any(videos):
151
+ self.new_video(videos[0]) # new video
152
+ else:
153
+ self.cap = None
154
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
155
+ f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
156
+
157
+ def __iter__(self):
158
+ self.count = 0
159
+ return self
160
+
161
+ def __next__(self):
162
+ if self.count == self.nf:
163
+ raise StopIteration
164
+ path = self.files[self.count]
165
+
166
+ if self.video_flag[self.count]:
167
+ # Read video
168
+ self.mode = 'video'
169
+ ret_val, img0 = self.cap.read()
170
+ if not ret_val:
171
+ self.count += 1
172
+ self.cap.release()
173
+ if self.count == self.nf: # last video
174
+ raise StopIteration
175
+ else:
176
+ path = self.files[self.count]
177
+ self.new_video(path)
178
+ ret_val, img0 = self.cap.read()
179
+
180
+ self.frame += 1
181
+ print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='')
182
+
183
+ else:
184
+ # Read image
185
+ self.count += 1
186
+ img0 = cv2.imread(path) # BGR
187
+ assert img0 is not None, 'Image Not Found ' + path
188
+ #print(f'image {self.count}/{self.nf} {path}: ', end='')
189
+
190
+ # Padded resize
191
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
192
+
193
+ # Convert
194
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
195
+ img = np.ascontiguousarray(img)
196
+
197
+ return path, img, img0, self.cap
198
+
199
+ def new_video(self, path):
200
+ self.frame = 0
201
+ self.cap = cv2.VideoCapture(path)
202
+ self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
203
+
204
+ def __len__(self):
205
+ return self.nf # number of files
206
+
207
+
208
+ class LoadWebcam: # for inference
209
+ def __init__(self, pipe='0', img_size=640, stride=32):
210
+ self.img_size = img_size
211
+ self.stride = stride
212
+
213
+ if pipe.isnumeric():
214
+ pipe = eval(pipe) # local camera
215
+ # pipe = 'rtsp://192.168.1.64/1' # IP camera
216
+ # pipe = 'rtsp://username:[email protected]/1' # IP camera with login
217
+ # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
218
+
219
+ self.pipe = pipe
220
+ self.cap = cv2.VideoCapture(pipe) # video capture object
221
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
222
+
223
+ def __iter__(self):
224
+ self.count = -1
225
+ return self
226
+
227
+ def __next__(self):
228
+ self.count += 1
229
+ if cv2.waitKey(1) == ord('q'): # q to quit
230
+ self.cap.release()
231
+ cv2.destroyAllWindows()
232
+ raise StopIteration
233
+
234
+ # Read frame
235
+ if self.pipe == 0: # local camera
236
+ ret_val, img0 = self.cap.read()
237
+ img0 = cv2.flip(img0, 1) # flip left-right
238
+ else: # IP camera
239
+ n = 0
240
+ while True:
241
+ n += 1
242
+ self.cap.grab()
243
+ if n % 30 == 0: # skip frames
244
+ ret_val, img0 = self.cap.retrieve()
245
+ if ret_val:
246
+ break
247
+
248
+ # Print
249
+ assert ret_val, f'Camera Error {self.pipe}'
250
+ img_path = 'webcam.jpg'
251
+ print(f'webcam {self.count}: ', end='')
252
+
253
+ # Padded resize
254
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
255
+
256
+ # Convert
257
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
258
+ img = np.ascontiguousarray(img)
259
+
260
+ return img_path, img, img0, None
261
+
262
+ def __len__(self):
263
+ return 0
264
+
265
+
266
+ class LoadStreams: # multiple IP or RTSP cameras
267
+ def __init__(self, sources='streams.txt', img_size=640, stride=32):
268
+ self.mode = 'stream'
269
+ self.img_size = img_size
270
+ self.stride = stride
271
+
272
+ if os.path.isfile(sources):
273
+ with open(sources, 'r') as f:
274
+ sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
275
+ else:
276
+ sources = [sources]
277
+
278
+ n = len(sources)
279
+ self.imgs = [None] * n
280
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
281
+ for i, s in enumerate(sources):
282
+ # Start the thread to read frames from the video stream
283
+ print(f'{i + 1}/{n}: {s}... ', end='')
284
+ url = eval(s) if s.isnumeric() else s
285
+ if 'youtube.com/' in str(url) or 'youtu.be/' in str(url): # if source is YouTube video
286
+ check_requirements(('pafy', 'youtube_dl'))
287
+ import pafy
288
+ url = pafy.new(url).getbest(preftype="mp4").url
289
+ cap = cv2.VideoCapture(url)
290
+ assert cap.isOpened(), f'Failed to open {s}'
291
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
292
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
293
+ self.fps = cap.get(cv2.CAP_PROP_FPS) % 100
294
+
295
+ _, self.imgs[i] = cap.read() # guarantee first frame
296
+ thread = Thread(target=self.update, args=([i, cap]), daemon=True)
297
+ print(f' success ({w}x{h} at {self.fps:.2f} FPS).')
298
+ thread.start()
299
+ print('') # newline
300
+
301
+ # check for common shapes
302
+ s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes
303
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
304
+ if not self.rect:
305
+ print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
306
+
307
+ def update(self, index, cap):
308
+ # Read next stream frame in a daemon thread
309
+ n = 0
310
+ while cap.isOpened():
311
+ n += 1
312
+ # _, self.imgs[index] = cap.read()
313
+ cap.grab()
314
+ if n == 4: # read every 4th frame
315
+ success, im = cap.retrieve()
316
+ self.imgs[index] = im if success else self.imgs[index] * 0
317
+ n = 0
318
+ time.sleep(1 / self.fps) # wait time
319
+
320
+ def __iter__(self):
321
+ self.count = -1
322
+ return self
323
+
324
+ def __next__(self):
325
+ self.count += 1
326
+ img0 = self.imgs.copy()
327
+ if cv2.waitKey(1) == ord('q'): # q to quit
328
+ cv2.destroyAllWindows()
329
+ raise StopIteration
330
+
331
+ # Letterbox
332
+ img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
333
+
334
+ # Stack
335
+ img = np.stack(img, 0)
336
+
337
+ # Convert
338
+ img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
339
+ img = np.ascontiguousarray(img)
340
+
341
+ return self.sources, img, img0, None
342
+
343
+ def __len__(self):
344
+ return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
345
+
346
+
347
+ def img2label_paths(img_paths):
348
+ # Define label paths as a function of image paths
349
+ sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
350
+ return ['txt'.join(x.replace(sa, sb, 1).rsplit(x.split('.')[-1], 1)) for x in img_paths]
351
+
352
+
353
+ class LoadImagesAndLabels(Dataset): # for training/testing
354
+ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
355
+ cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
356
+ self.img_size = img_size
357
+ self.augment = augment
358
+ self.hyp = hyp
359
+ self.image_weights = image_weights
360
+ self.rect = False if image_weights else rect
361
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
362
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
363
+ self.stride = stride
364
+ self.path = path
365
+ #self.albumentations = Albumentations() if augment else None
366
+
367
+ try:
368
+ f = [] # image files
369
+ for p in path if isinstance(path, list) else [path]:
370
+ p = Path(p) # os-agnostic
371
+ if p.is_dir(): # dir
372
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
373
+ # f = list(p.rglob('**/*.*')) # pathlib
374
+ elif p.is_file(): # file
375
+ with open(p, 'r') as t:
376
+ t = t.read().strip().splitlines()
377
+ parent = str(p.parent) + os.sep
378
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
379
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
380
+ else:
381
+ raise Exception(f'{prefix}{p} does not exist')
382
+ self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])
383
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
384
+ assert self.img_files, f'{prefix}No images found'
385
+ except Exception as e:
386
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}')
387
+
388
+ # Check cache
389
+ self.label_files = img2label_paths(self.img_files) # labels
390
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels
391
+ if cache_path.is_file():
392
+ cache, exists = torch.load(cache_path), True # load
393
+ #if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed
394
+ # cache, exists = self.cache_labels(cache_path, prefix), False # re-cache
395
+ else:
396
+ cache, exists = self.cache_labels(cache_path, prefix), False # cache
397
+
398
+ # Display cache
399
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
400
+ if exists:
401
+ d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
402
+ tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
403
+ assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'
404
+
405
+ # Read cache
406
+ cache.pop('hash') # remove hash
407
+ cache.pop('version') # remove version
408
+ labels, shapes, self.segments = zip(*cache.values())
409
+ self.labels = list(labels)
410
+ self.shapes = np.array(shapes, dtype=np.float64)
411
+ self.img_files = list(cache.keys()) # update
412
+ self.label_files = img2label_paths(cache.keys()) # update
413
+ if single_cls:
414
+ for x in self.labels:
415
+ x[:, 0] = 0
416
+
417
+ n = len(shapes) # number of images
418
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
419
+ nb = bi[-1] + 1 # number of batches
420
+ self.batch = bi # batch index of image
421
+ self.n = n
422
+ self.indices = range(n)
423
+
424
+ # Rectangular Training
425
+ if self.rect:
426
+ # Sort by aspect ratio
427
+ s = self.shapes # wh
428
+ ar = s[:, 1] / s[:, 0] # aspect ratio
429
+ irect = ar.argsort()
430
+ self.img_files = [self.img_files[i] for i in irect]
431
+ self.label_files = [self.label_files[i] for i in irect]
432
+ self.labels = [self.labels[i] for i in irect]
433
+ self.shapes = s[irect] # wh
434
+ ar = ar[irect]
435
+
436
+ # Set training image shapes
437
+ shapes = [[1, 1]] * nb
438
+ for i in range(nb):
439
+ ari = ar[bi == i]
440
+ mini, maxi = ari.min(), ari.max()
441
+ if maxi < 1:
442
+ shapes[i] = [maxi, 1]
443
+ elif mini > 1:
444
+ shapes[i] = [1, 1 / mini]
445
+
446
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
447
+
448
+ # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
449
+ self.imgs = [None] * n
450
+ if cache_images:
451
+ if cache_images == 'disk':
452
+ self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy')
453
+ self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files]
454
+ self.im_cache_dir.mkdir(parents=True, exist_ok=True)
455
+ gb = 0 # Gigabytes of cached images
456
+ self.img_hw0, self.img_hw = [None] * n, [None] * n
457
+ results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
458
+ pbar = tqdm(enumerate(results), total=n)
459
+ for i, x in pbar:
460
+ if cache_images == 'disk':
461
+ if not self.img_npy[i].exists():
462
+ np.save(self.img_npy[i].as_posix(), x[0])
463
+ gb += self.img_npy[i].stat().st_size
464
+ else:
465
+ self.imgs[i], self.img_hw0[i], self.img_hw[i] = x
466
+ gb += self.imgs[i].nbytes
467
+ pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'
468
+ pbar.close()
469
+
470
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
471
+ # Cache dataset labels, check images and read shapes
472
+ x = {} # dict
473
+ nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate
474
+ pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
475
+ for i, (im_file, lb_file) in enumerate(pbar):
476
+ try:
477
+ # verify images
478
+ im = Image.open(im_file)
479
+ im.verify() # PIL verify
480
+ shape = exif_size(im) # image size
481
+ segments = [] # instance segments
482
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
483
+ assert im.format.lower() in img_formats, f'invalid image format {im.format}'
484
+
485
+ # verify labels
486
+ if os.path.isfile(lb_file):
487
+ nf += 1 # label found
488
+ with open(lb_file, 'r') as f:
489
+ l = [x.split() for x in f.read().strip().splitlines()]
490
+ if any([len(x) > 8 for x in l]): # is segment
491
+ classes = np.array([x[0] for x in l], dtype=np.float32)
492
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
493
+ l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
494
+ l = np.array(l, dtype=np.float32)
495
+ if len(l):
496
+ assert l.shape[1] == 5, 'labels require 5 columns each'
497
+ assert (l >= 0).all(), 'negative labels'
498
+ assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
499
+ assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
500
+ else:
501
+ ne += 1 # label empty
502
+ l = np.zeros((0, 5), dtype=np.float32)
503
+ else:
504
+ nm += 1 # label missing
505
+ l = np.zeros((0, 5), dtype=np.float32)
506
+ x[im_file] = [l, shape, segments]
507
+ except Exception as e:
508
+ nc += 1
509
+ print(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')
510
+
511
+ pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels... " \
512
+ f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
513
+ pbar.close()
514
+
515
+ if nf == 0:
516
+ print(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
517
+
518
+ x['hash'] = get_hash(self.label_files + self.img_files)
519
+ x['results'] = nf, nm, ne, nc, i + 1
520
+ x['version'] = 0.1 # cache version
521
+ torch.save(x, path) # save for next time
522
+ logging.info(f'{prefix}New cache created: {path}')
523
+ return x
524
+
525
+ def __len__(self):
526
+ return len(self.img_files)
527
+
528
+ # def __iter__(self):
529
+ # self.count = -1
530
+ # print('ran dataset iter')
531
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
532
+ # return self
533
+
534
+ def __getitem__(self, index):
535
+ index = self.indices[index] # linear, shuffled, or image_weights
536
+
537
+ hyp = self.hyp
538
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
539
+ if mosaic:
540
+ # Load mosaic
541
+ if random.random() < 0.8:
542
+ img, labels = load_mosaic(self, index)
543
+ else:
544
+ img, labels = load_mosaic9(self, index)
545
+ shapes = None
546
+
547
+ # MixUp https://arxiv.org/pdf/1710.09412.pdf
548
+ if random.random() < hyp['mixup']:
549
+ if random.random() < 0.8:
550
+ img2, labels2 = load_mosaic(self, random.randint(0, len(self.labels) - 1))
551
+ else:
552
+ img2, labels2 = load_mosaic9(self, random.randint(0, len(self.labels) - 1))
553
+ r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
554
+ img = (img * r + img2 * (1 - r)).astype(np.uint8)
555
+ labels = np.concatenate((labels, labels2), 0)
556
+
557
+ else:
558
+ # Load image
559
+ img, (h0, w0), (h, w) = load_image(self, index)
560
+
561
+ # Letterbox
562
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
563
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
564
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
565
+
566
+ labels = self.labels[index].copy()
567
+ if labels.size: # normalized xywh to pixel xyxy format
568
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
569
+
570
+ if self.augment:
571
+ # Augment imagespace
572
+ if not mosaic:
573
+ img, labels = random_perspective(img, labels,
574
+ degrees=hyp['degrees'],
575
+ translate=hyp['translate'],
576
+ scale=hyp['scale'],
577
+ shear=hyp['shear'],
578
+ perspective=hyp['perspective'])
579
+
580
+
581
+ #img, labels = self.albumentations(img, labels)
582
+
583
+ # Augment colorspace
584
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
585
+
586
+ # Apply cutouts
587
+ # if random.random() < 0.9:
588
+ # labels = cutout(img, labels)
589
+
590
+ if random.random() < hyp['paste_in']:
591
+ sample_labels, sample_images, sample_masks = [], [], []
592
+ while len(sample_labels) < 30:
593
+ sample_labels_, sample_images_, sample_masks_ = load_samples(self, random.randint(0, len(self.labels) - 1))
594
+ sample_labels += sample_labels_
595
+ sample_images += sample_images_
596
+ sample_masks += sample_masks_
597
+ #print(len(sample_labels))
598
+ if len(sample_labels) == 0:
599
+ break
600
+ labels = pastein(img, labels, sample_labels, sample_images, sample_masks)
601
+
602
+ nL = len(labels) # number of labels
603
+ if nL:
604
+ labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
605
+ labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
606
+ labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
607
+
608
+ if self.augment:
609
+ # flip up-down
610
+ if random.random() < hyp['flipud']:
611
+ img = np.flipud(img)
612
+ if nL:
613
+ labels[:, 2] = 1 - labels[:, 2]
614
+
615
+ # flip left-right
616
+ if random.random() < hyp['fliplr']:
617
+ img = np.fliplr(img)
618
+ if nL:
619
+ labels[:, 1] = 1 - labels[:, 1]
620
+
621
+ labels_out = torch.zeros((nL, 6))
622
+ if nL:
623
+ labels_out[:, 1:] = torch.from_numpy(labels)
624
+
625
+ # Convert
626
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
627
+ img = np.ascontiguousarray(img)
628
+
629
+ return torch.from_numpy(img), labels_out, self.img_files[index], shapes
630
+
631
+ @staticmethod
632
+ def collate_fn(batch):
633
+ img, label, path, shapes = zip(*batch) # transposed
634
+ for i, l in enumerate(label):
635
+ l[:, 0] = i # add target image index for build_targets()
636
+ return torch.stack(img, 0), torch.cat(label, 0), path, shapes
637
+
638
+ @staticmethod
639
+ def collate_fn4(batch):
640
+ img, label, path, shapes = zip(*batch) # transposed
641
+ n = len(shapes) // 4
642
+ img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
643
+
644
+ ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
645
+ wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
646
+ s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
647
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
648
+ i *= 4
649
+ if random.random() < 0.5:
650
+ im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
651
+ 0].type(img[i].type())
652
+ l = label[i]
653
+ else:
654
+ im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
655
+ l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
656
+ img4.append(im)
657
+ label4.append(l)
658
+
659
+ for i, l in enumerate(label4):
660
+ l[:, 0] = i # add target image index for build_targets()
661
+
662
+ return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
663
+
664
+
665
+ # Ancillary functions --------------------------------------------------------------------------------------------------
666
+ def load_image(self, index):
667
+ # loads 1 image from dataset, returns img, original hw, resized hw
668
+ img = self.imgs[index]
669
+ if img is None: # not cached
670
+ path = self.img_files[index]
671
+ img = cv2.imread(path) # BGR
672
+ assert img is not None, 'Image Not Found ' + path
673
+ h0, w0 = img.shape[:2] # orig hw
674
+ r = self.img_size / max(h0, w0) # resize image to img_size
675
+ if r != 1: # always resize down, only resize up if training with augmentation
676
+ interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
677
+ img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
678
+ return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
679
+ else:
680
+ return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
681
+
682
+
683
+ def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
684
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
685
+ hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
686
+ dtype = img.dtype # uint8
687
+
688
+ x = np.arange(0, 256, dtype=np.int16)
689
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
690
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
691
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
692
+
693
+ img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
694
+ cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
695
+
696
+
697
+ def hist_equalize(img, clahe=True, bgr=False):
698
+ # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255
699
+ yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
700
+ if clahe:
701
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
702
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
703
+ else:
704
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
705
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
706
+
707
+
708
+ def load_mosaic(self, index):
709
+ # loads images in a 4-mosaic
710
+
711
+ labels4, segments4 = [], []
712
+ s = self.img_size
713
+ yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
714
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
715
+ for i, index in enumerate(indices):
716
+ # Load image
717
+ img, _, (h, w) = load_image(self, index)
718
+
719
+ # place img in img4
720
+ if i == 0: # top left
721
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
722
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
723
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
724
+ elif i == 1: # top right
725
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
726
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
727
+ elif i == 2: # bottom left
728
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
729
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
730
+ elif i == 3: # bottom right
731
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
732
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
733
+
734
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
735
+ padw = x1a - x1b
736
+ padh = y1a - y1b
737
+
738
+ # Labels
739
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
740
+ if labels.size:
741
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
742
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
743
+ labels4.append(labels)
744
+ segments4.extend(segments)
745
+
746
+ # Concat/clip labels
747
+ labels4 = np.concatenate(labels4, 0)
748
+ for x in (labels4[:, 1:], *segments4):
749
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
750
+ # img4, labels4 = replicate(img4, labels4) # replicate
751
+
752
+ # Augment
753
+ #img4, labels4, segments4 = remove_background(img4, labels4, segments4)
754
+ #sample_segments(img4, labels4, segments4, probability=self.hyp['copy_paste'])
755
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, probability=self.hyp['copy_paste'])
756
+ img4, labels4 = random_perspective(img4, labels4, segments4,
757
+ degrees=self.hyp['degrees'],
758
+ translate=self.hyp['translate'],
759
+ scale=self.hyp['scale'],
760
+ shear=self.hyp['shear'],
761
+ perspective=self.hyp['perspective'],
762
+ border=self.mosaic_border) # border to remove
763
+
764
+ return img4, labels4
765
+
766
+
767
+ def load_mosaic9(self, index):
768
+ # loads images in a 9-mosaic
769
+
770
+ labels9, segments9 = [], []
771
+ s = self.img_size
772
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
773
+ for i, index in enumerate(indices):
774
+ # Load image
775
+ img, _, (h, w) = load_image(self, index)
776
+
777
+ # place img in img9
778
+ if i == 0: # center
779
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
780
+ h0, w0 = h, w
781
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
782
+ elif i == 1: # top
783
+ c = s, s - h, s + w, s
784
+ elif i == 2: # top right
785
+ c = s + wp, s - h, s + wp + w, s
786
+ elif i == 3: # right
787
+ c = s + w0, s, s + w0 + w, s + h
788
+ elif i == 4: # bottom right
789
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
790
+ elif i == 5: # bottom
791
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
792
+ elif i == 6: # bottom left
793
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
794
+ elif i == 7: # left
795
+ c = s - w, s + h0 - h, s, s + h0
796
+ elif i == 8: # top left
797
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
798
+
799
+ padx, pady = c[:2]
800
+ x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
801
+
802
+ # Labels
803
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
804
+ if labels.size:
805
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
806
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
807
+ labels9.append(labels)
808
+ segments9.extend(segments)
809
+
810
+ # Image
811
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
812
+ hp, wp = h, w # height, width previous
813
+
814
+ # Offset
815
+ yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
816
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
817
+
818
+ # Concat/clip labels
819
+ labels9 = np.concatenate(labels9, 0)
820
+ labels9[:, [1, 3]] -= xc
821
+ labels9[:, [2, 4]] -= yc
822
+ c = np.array([xc, yc]) # centers
823
+ segments9 = [x - c for x in segments9]
824
+
825
+ for x in (labels9[:, 1:], *segments9):
826
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
827
+ # img9, labels9 = replicate(img9, labels9) # replicate
828
+
829
+ # Augment
830
+ #img9, labels9, segments9 = remove_background(img9, labels9, segments9)
831
+ img9, labels9, segments9 = copy_paste(img9, labels9, segments9, probability=self.hyp['copy_paste'])
832
+ img9, labels9 = random_perspective(img9, labels9, segments9,
833
+ degrees=self.hyp['degrees'],
834
+ translate=self.hyp['translate'],
835
+ scale=self.hyp['scale'],
836
+ shear=self.hyp['shear'],
837
+ perspective=self.hyp['perspective'],
838
+ border=self.mosaic_border) # border to remove
839
+
840
+ return img9, labels9
841
+
842
+
843
+ def load_samples(self, index):
844
+ # loads images in a 4-mosaic
845
+
846
+ labels4, segments4 = [], []
847
+ s = self.img_size
848
+ yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
849
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
850
+ for i, index in enumerate(indices):
851
+ # Load image
852
+ img, _, (h, w) = load_image(self, index)
853
+
854
+ # place img in img4
855
+ if i == 0: # top left
856
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
857
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
858
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
859
+ elif i == 1: # top right
860
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
861
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
862
+ elif i == 2: # bottom left
863
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
864
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
865
+ elif i == 3: # bottom right
866
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
867
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
868
+
869
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
870
+ padw = x1a - x1b
871
+ padh = y1a - y1b
872
+
873
+ # Labels
874
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
875
+ if labels.size:
876
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
877
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
878
+ labels4.append(labels)
879
+ segments4.extend(segments)
880
+
881
+ # Concat/clip labels
882
+ labels4 = np.concatenate(labels4, 0)
883
+ for x in (labels4[:, 1:], *segments4):
884
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
885
+ # img4, labels4 = replicate(img4, labels4) # replicate
886
+
887
+ # Augment
888
+ #img4, labels4, segments4 = remove_background(img4, labels4, segments4)
889
+ sample_labels, sample_images, sample_masks = sample_segments(img4, labels4, segments4, probability=0.5)
890
+
891
+ return sample_labels, sample_images, sample_masks
892
+
893
+
894
+ def copy_paste(img, labels, segments, probability=0.5):
895
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
896
+ n = len(segments)
897
+ if probability and n:
898
+ h, w, c = img.shape # height, width, channels
899
+ im_new = np.zeros(img.shape, np.uint8)
900
+ for j in random.sample(range(n), k=round(probability * n)):
901
+ l, s = labels[j], segments[j]
902
+ box = w - l[3], l[2], w - l[1], l[4]
903
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
904
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
905
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
906
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
907
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
908
+
909
+ result = cv2.bitwise_and(src1=img, src2=im_new)
910
+ result = cv2.flip(result, 1) # augment segments (flip left-right)
911
+ i = result > 0 # pixels to replace
912
+ # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
913
+ img[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
914
+
915
+ return img, labels, segments
916
+
917
+
918
+ def remove_background(img, labels, segments):
919
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
920
+ n = len(segments)
921
+ h, w, c = img.shape # height, width, channels
922
+ im_new = np.zeros(img.shape, np.uint8)
923
+ img_new = np.ones(img.shape, np.uint8) * 114
924
+ for j in range(n):
925
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
926
+
927
+ result = cv2.bitwise_and(src1=img, src2=im_new)
928
+
929
+ i = result > 0 # pixels to replace
930
+ img_new[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
931
+
932
+ return img_new, labels, segments
933
+
934
+
935
+ def sample_segments(img, labels, segments, probability=0.5):
936
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
937
+ n = len(segments)
938
+ sample_labels = []
939
+ sample_images = []
940
+ sample_masks = []
941
+ if probability and n:
942
+ h, w, c = img.shape # height, width, channels
943
+ for j in random.sample(range(n), k=round(probability * n)):
944
+ l, s = labels[j], segments[j]
945
+ box = l[1].astype(int).clip(0,w-1), l[2].astype(int).clip(0,h-1), l[3].astype(int).clip(0,w-1), l[4].astype(int).clip(0,h-1)
946
+
947
+ #print(box)
948
+ if (box[2] <= box[0]) or (box[3] <= box[1]):
949
+ continue
950
+
951
+ sample_labels.append(l[0])
952
+
953
+ mask = np.zeros(img.shape, np.uint8)
954
+
955
+ cv2.drawContours(mask, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
956
+ sample_masks.append(mask[box[1]:box[3],box[0]:box[2],:])
957
+
958
+ result = cv2.bitwise_and(src1=img, src2=mask)
959
+ i = result > 0 # pixels to replace
960
+ mask[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
961
+ #print(box)
962
+ sample_images.append(mask[box[1]:box[3],box[0]:box[2],:])
963
+
964
+ return sample_labels, sample_images, sample_masks
965
+
966
+
967
+ def replicate(img, labels):
968
+ # Replicate labels
969
+ h, w = img.shape[:2]
970
+ boxes = labels[:, 1:].astype(int)
971
+ x1, y1, x2, y2 = boxes.T
972
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
973
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
974
+ x1b, y1b, x2b, y2b = boxes[i]
975
+ bh, bw = y2b - y1b, x2b - x1b
976
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
977
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
978
+ img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
979
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
980
+
981
+ return img, labels
982
+
983
+
984
+ def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
985
+ # Resize and pad image while meeting stride-multiple constraints
986
+ shape = img.shape[:2] # current shape [height, width]
987
+ if isinstance(new_shape, int):
988
+ new_shape = (new_shape, new_shape)
989
+
990
+ # Scale ratio (new / old)
991
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
992
+ if not scaleup: # only scale down, do not scale up (for better test mAP)
993
+ r = min(r, 1.0)
994
+
995
+ # Compute padding
996
+ ratio = r, r # width, height ratios
997
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
998
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
999
+ if auto: # minimum rectangle
1000
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
1001
+ elif scaleFill: # stretch
1002
+ dw, dh = 0.0, 0.0
1003
+ new_unpad = (new_shape[1], new_shape[0])
1004
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
1005
+
1006
+ dw /= 2 # divide padding into 2 sides
1007
+ dh /= 2
1008
+
1009
+ if shape[::-1] != new_unpad: # resize
1010
+ img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
1011
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
1012
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
1013
+ img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
1014
+ return img, ratio, (dw, dh)
1015
+
1016
+
1017
+ def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
1018
+ border=(0, 0)):
1019
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
1020
+ # targets = [cls, xyxy]
1021
+
1022
+ height = img.shape[0] + border[0] * 2 # shape(h,w,c)
1023
+ width = img.shape[1] + border[1] * 2
1024
+
1025
+ # Center
1026
+ C = np.eye(3)
1027
+ C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
1028
+ C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
1029
+
1030
+ # Perspective
1031
+ P = np.eye(3)
1032
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
1033
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
1034
+
1035
+ # Rotation and Scale
1036
+ R = np.eye(3)
1037
+ a = random.uniform(-degrees, degrees)
1038
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
1039
+ s = random.uniform(1 - scale, 1.1 + scale)
1040
+ # s = 2 ** random.uniform(-scale, scale)
1041
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
1042
+
1043
+ # Shear
1044
+ S = np.eye(3)
1045
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
1046
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
1047
+
1048
+ # Translation
1049
+ T = np.eye(3)
1050
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
1051
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
1052
+
1053
+ # Combined rotation matrix
1054
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
1055
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
1056
+ if perspective:
1057
+ img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
1058
+ else: # affine
1059
+ img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
1060
+
1061
+ # Visualize
1062
+ # import matplotlib.pyplot as plt
1063
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
1064
+ # ax[0].imshow(img[:, :, ::-1]) # base
1065
+ # ax[1].imshow(img2[:, :, ::-1]) # warped
1066
+
1067
+ # Transform label coordinates
1068
+ n = len(targets)
1069
+ if n:
1070
+ use_segments = any(x.any() for x in segments)
1071
+ new = np.zeros((n, 4))
1072
+ if use_segments: # warp segments
1073
+ segments = resample_segments(segments) # upsample
1074
+ for i, segment in enumerate(segments):
1075
+ xy = np.ones((len(segment), 3))
1076
+ xy[:, :2] = segment
1077
+ xy = xy @ M.T # transform
1078
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
1079
+
1080
+ # clip
1081
+ new[i] = segment2box(xy, width, height)
1082
+
1083
+ else: # warp boxes
1084
+ xy = np.ones((n * 4, 3))
1085
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
1086
+ xy = xy @ M.T # transform
1087
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
1088
+
1089
+ # create new boxes
1090
+ x = xy[:, [0, 2, 4, 6]]
1091
+ y = xy[:, [1, 3, 5, 7]]
1092
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
1093
+
1094
+ # clip
1095
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
1096
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
1097
+
1098
+ # filter candidates
1099
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
1100
+ targets = targets[i]
1101
+ targets[:, 1:5] = new[i]
1102
+
1103
+ return img, targets
1104
+
1105
+
1106
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
1107
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
1108
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
1109
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
1110
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
1111
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
1112
+
1113
+
1114
+ def bbox_ioa(box1, box2):
1115
+ # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
1116
+ box2 = box2.transpose()
1117
+
1118
+ # Get the coordinates of bounding boxes
1119
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
1120
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
1121
+
1122
+ # Intersection area
1123
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
1124
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
1125
+
1126
+ # box2 area
1127
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
1128
+
1129
+ # Intersection over box2 area
1130
+ return inter_area / box2_area
1131
+
1132
+
1133
+ def cutout(image, labels):
1134
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
1135
+ h, w = image.shape[:2]
1136
+
1137
+ # create random masks
1138
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
1139
+ for s in scales:
1140
+ mask_h = random.randint(1, int(h * s))
1141
+ mask_w = random.randint(1, int(w * s))
1142
+
1143
+ # box
1144
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
1145
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
1146
+ xmax = min(w, xmin + mask_w)
1147
+ ymax = min(h, ymin + mask_h)
1148
+
1149
+ # apply random color mask
1150
+ image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
1151
+
1152
+ # return unobscured labels
1153
+ if len(labels) and s > 0.03:
1154
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
1155
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
1156
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
1157
+
1158
+ return labels
1159
+
1160
+
1161
+ def pastein(image, labels, sample_labels, sample_images, sample_masks):
1162
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
1163
+ h, w = image.shape[:2]
1164
+
1165
+ # create random masks
1166
+ scales = [0.75] * 2 + [0.5] * 4 + [0.25] * 4 + [0.125] * 4 + [0.0625] * 6 # image size fraction
1167
+ for s in scales:
1168
+ if random.random() < 0.2:
1169
+ continue
1170
+ mask_h = random.randint(1, int(h * s))
1171
+ mask_w = random.randint(1, int(w * s))
1172
+
1173
+ # box
1174
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
1175
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
1176
+ xmax = min(w, xmin + mask_w)
1177
+ ymax = min(h, ymin + mask_h)
1178
+
1179
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
1180
+ if len(labels):
1181
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
1182
+ else:
1183
+ ioa = np.zeros(1)
1184
+
1185
+ if (ioa < 0.30).all() and len(sample_labels) and (xmax > xmin+20) and (ymax > ymin+20): # allow 30% obscuration of existing labels
1186
+ sel_ind = random.randint(0, len(sample_labels)-1)
1187
+ #print(len(sample_labels))
1188
+ #print(sel_ind)
1189
+ #print((xmax-xmin, ymax-ymin))
1190
+ #print(image[ymin:ymax, xmin:xmax].shape)
1191
+ #print([[sample_labels[sel_ind], *box]])
1192
+ #print(labels.shape)
1193
+ hs, ws, cs = sample_images[sel_ind].shape
1194
+ r_scale = min((ymax-ymin)/hs, (xmax-xmin)/ws)
1195
+ r_w = int(ws*r_scale)
1196
+ r_h = int(hs*r_scale)
1197
+
1198
+ if (r_w > 10) and (r_h > 10):
1199
+ r_mask = cv2.resize(sample_masks[sel_ind], (r_w, r_h))
1200
+ r_image = cv2.resize(sample_images[sel_ind], (r_w, r_h))
1201
+ temp_crop = image[ymin:ymin+r_h, xmin:xmin+r_w]
1202
+ m_ind = r_mask > 0
1203
+ if m_ind.astype(np.int).sum() > 60:
1204
+ temp_crop[m_ind] = r_image[m_ind]
1205
+ #print(sample_labels[sel_ind])
1206
+ #print(sample_images[sel_ind].shape)
1207
+ #print(temp_crop.shape)
1208
+ box = np.array([xmin, ymin, xmin+r_w, ymin+r_h], dtype=np.float32)
1209
+ if len(labels):
1210
+ labels = np.concatenate((labels, [[sample_labels[sel_ind], *box]]), 0)
1211
+ else:
1212
+ labels = np.array([[sample_labels[sel_ind], *box]])
1213
+
1214
+ image[ymin:ymin+r_h, xmin:xmin+r_w] = temp_crop
1215
+
1216
+ return labels
1217
+
1218
+ class Albumentations:
1219
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
1220
+ def __init__(self):
1221
+ self.transform = None
1222
+ import albumentations as A
1223
+
1224
+ self.transform = A.Compose([
1225
+ A.CLAHE(p=0.01),
1226
+ A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.01),
1227
+ A.RandomGamma(gamma_limit=[80, 120], p=0.01),
1228
+ A.Blur(p=0.01),
1229
+ A.MedianBlur(p=0.01),
1230
+ A.ToGray(p=0.01),
1231
+ A.ImageCompression(quality_lower=75, p=0.01),],
1232
+ bbox_params=A.BboxParams(format='pascal_voc', label_fields=['class_labels']))
1233
+
1234
+ #logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
1235
+
1236
+ def __call__(self, im, labels, p=1.0):
1237
+ if self.transform and random.random() < p:
1238
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
1239
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
1240
+ return im, labels
1241
+
1242
+
1243
+ def create_folder(path='./new'):
1244
+ # Create folder
1245
+ if os.path.exists(path):
1246
+ shutil.rmtree(path) # delete output folder
1247
+ os.makedirs(path) # make new output folder
1248
+
1249
+
1250
+ def flatten_recursive(path='../coco'):
1251
+ # Flatten a recursive directory by bringing all files to top level
1252
+ new_path = Path(path + '_flat')
1253
+ create_folder(new_path)
1254
+ for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
1255
+ shutil.copyfile(file, new_path / Path(file).name)
1256
+
1257
+
1258
+ def extract_boxes(path='../coco/'): # from utils.datasets import *; extract_boxes('../coco128')
1259
+ # Convert detection dataset into classification dataset, with one directory per class
1260
+
1261
+ path = Path(path) # images dir
1262
+ shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
1263
+ files = list(path.rglob('*.*'))
1264
+ n = len(files) # number of files
1265
+ for im_file in tqdm(files, total=n):
1266
+ if im_file.suffix[1:] in img_formats:
1267
+ # image
1268
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
1269
+ h, w = im.shape[:2]
1270
+
1271
+ # labels
1272
+ lb_file = Path(img2label_paths([str(im_file)])[0])
1273
+ if Path(lb_file).exists():
1274
+ with open(lb_file, 'r') as f:
1275
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
1276
+
1277
+ for j, x in enumerate(lb):
1278
+ c = int(x[0]) # class
1279
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
1280
+ if not f.parent.is_dir():
1281
+ f.parent.mkdir(parents=True)
1282
+
1283
+ b = x[1:] * [w, h, w, h] # box
1284
+ # b[2:] = b[2:].max() # rectangle to square
1285
+ b[2:] = b[2:] * 1.2 + 3 # pad
1286
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
1287
+
1288
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
1289
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
1290
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
1291
+
1292
+
1293
+ def autosplit(path='../coco', weights=(0.9, 0.1, 0.0), annotated_only=False):
1294
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
1295
+ Usage: from utils.datasets import *; autosplit('../coco')
1296
+ Arguments
1297
+ path: Path to images directory
1298
+ weights: Train, val, test weights (list)
1299
+ annotated_only: Only use images with an annotated txt file
1300
+ """
1301
+ path = Path(path) # images dir
1302
+ files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], []) # image files only
1303
+ n = len(files) # number of files
1304
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
1305
+
1306
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
1307
+ [(path / x).unlink() for x in txt if (path / x).exists()] # remove existing
1308
+
1309
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
1310
+ for i, img in tqdm(zip(indices, files), total=n):
1311
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
1312
+ with open(path / txt[i], 'a') as f:
1313
+ f.write(str(img) + '\n') # add image to txt file
1314
+
1315
+
1316
+ def load_segmentations(self, index):
1317
+ key = '/work/handsomejw66/coco17/' + self.img_files[index]
1318
+ #print(key)
1319
+ # /work/handsomejw66/coco17/
1320
+ return self.segs[key]
yolov7detect/utils/general.py ADDED
@@ -0,0 +1,892 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOR general utils
2
+
3
+ import glob
4
+ import logging
5
+ import math
6
+ import os
7
+ import platform
8
+ import random
9
+ import re
10
+ import subprocess
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import pandas as pd
17
+ import torch
18
+ import torchvision
19
+ import yaml
20
+
21
+ from yolov7.utils.google_utils import gsutil_getsize
22
+ from yolov7.utils.metrics import fitness
23
+ from yolov7.utils.torch_utils import init_torch_seeds
24
+
25
+ # Settings
26
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
27
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
28
+ pd.options.display.max_columns = 10
29
+ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
30
+ os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads
31
+
32
+
33
+ def set_logging(rank=-1):
34
+ logging.basicConfig(
35
+ format="%(message)s",
36
+ level=logging.INFO if rank in [-1, 0] else logging.WARN)
37
+
38
+
39
+ def init_seeds(seed=0):
40
+ # Initialize random number generator (RNG) seeds
41
+ random.seed(seed)
42
+ np.random.seed(seed)
43
+ init_torch_seeds(seed)
44
+
45
+
46
+ def get_latest_run(search_dir='.'):
47
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
48
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
49
+ return max(last_list, key=os.path.getctime) if last_list else ''
50
+
51
+
52
+ def isdocker():
53
+ # Is environment a Docker container
54
+ return Path('/workspace').exists() # or Path('/.dockerenv').exists()
55
+
56
+
57
+ def emojis(str=''):
58
+ # Return platform-dependent emoji-safe version of string
59
+ return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
60
+
61
+
62
+ def check_online():
63
+ # Check internet connectivity
64
+ import socket
65
+ try:
66
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accesability
67
+ return True
68
+ except OSError:
69
+ return False
70
+
71
+
72
+ def check_git_status():
73
+ # Recommend 'git pull' if code is out of date
74
+ print(colorstr('github: '), end='')
75
+ try:
76
+ assert Path('.git').exists(), 'skipping check (not a git repository)'
77
+ assert not isdocker(), 'skipping check (Docker image)'
78
+ assert check_online(), 'skipping check (offline)'
79
+
80
+ cmd = 'git fetch && git config --get remote.origin.url'
81
+ url = subprocess.check_output(cmd, shell=True).decode().strip().rstrip('.git') # github repo url
82
+ branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out
83
+ n = int(subprocess.check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind
84
+ if n > 0:
85
+ s = f"⚠️ WARNING: code is out of date by {n} commit{'s' * (n > 1)}. " \
86
+ f"Use 'git pull' to update or 'git clone {url}' to download latest."
87
+ else:
88
+ s = f'up to date with {url} ✅'
89
+ print(emojis(s)) # emoji-safe
90
+ except Exception as e:
91
+ print(e)
92
+
93
+
94
+ def check_requirements(requirements='requirements.txt', exclude=()):
95
+ # Check installed dependencies meet requirements (pass *.txt file or list of packages)
96
+ import pkg_resources as pkg
97
+ prefix = colorstr('red', 'bold', 'requirements:')
98
+ if isinstance(requirements, (str, Path)): # requirements.txt file
99
+ file = Path(requirements)
100
+ if not file.exists():
101
+ print(f"{prefix} {file.resolve()} not found, check failed.")
102
+ return
103
+ requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(file.open()) if x.name not in exclude]
104
+ else: # list or tuple of packages
105
+ requirements = [x for x in requirements if x not in exclude]
106
+
107
+ n = 0 # number of packages updates
108
+ for r in requirements:
109
+ try:
110
+ pkg.require(r)
111
+ except Exception as e: # DistributionNotFound or VersionConflict if requirements not met
112
+ n += 1
113
+ print(f"{prefix} {e.req} not found and is required by YOLOR, attempting auto-update...")
114
+ print(subprocess.check_output(f"pip install '{e.req}'", shell=True).decode())
115
+
116
+ if n: # if packages updated
117
+ source = file.resolve() if 'file' in locals() else requirements
118
+ s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
119
+ f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
120
+ print(emojis(s)) # emoji-safe
121
+
122
+
123
+ def check_img_size(img_size, s=32):
124
+ # Verify img_size is a multiple of stride s
125
+ new_size = make_divisible(img_size, int(s)) # ceil gs-multiple
126
+ if new_size != img_size:
127
+ print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size))
128
+ return new_size
129
+
130
+
131
+ def check_imshow():
132
+ # Check if environment supports image displays
133
+ try:
134
+ assert not isdocker(), 'cv2.imshow() is disabled in Docker environments'
135
+ cv2.imshow('test', np.zeros((1, 1, 3)))
136
+ cv2.waitKey(1)
137
+ cv2.destroyAllWindows()
138
+ cv2.waitKey(1)
139
+ return True
140
+ except Exception as e:
141
+ print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}')
142
+ return False
143
+
144
+
145
+ def check_file(file):
146
+ # Search for file if not found
147
+ if Path(file).is_file() or file == '':
148
+ return file
149
+ else:
150
+ files = glob.glob('./**/' + file, recursive=True) # find file
151
+ assert len(files), f'File Not Found: {file}' # assert file was found
152
+ assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
153
+ return files[0] # return file
154
+
155
+
156
+ def check_dataset(dict):
157
+ # Download dataset if not found locally
158
+ val, s = dict.get('val'), dict.get('download')
159
+ if val and len(val):
160
+ val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
161
+ if not all(x.exists() for x in val):
162
+ print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()])
163
+ if s and len(s): # download script
164
+ print('Downloading %s ...' % s)
165
+ if s.startswith('http') and s.endswith('.zip'): # URL
166
+ f = Path(s).name # filename
167
+ torch.hub.download_url_to_file(s, f)
168
+ r = os.system('unzip -q %s -d ../ && rm %s' % (f, f)) # unzip
169
+ else: # bash script
170
+ r = os.system(s)
171
+ print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value
172
+ else:
173
+ raise Exception('Dataset not found.')
174
+
175
+
176
+ def make_divisible(x, divisor):
177
+ # Returns x evenly divisible by divisor
178
+ return math.ceil(x / divisor) * divisor
179
+
180
+
181
+ def clean_str(s):
182
+ # Cleans a string by replacing special characters with underscore _
183
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
184
+
185
+
186
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
187
+ # lambda function for sinusoidal ramp from y1 to y2
188
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
189
+
190
+
191
+ def colorstr(*input):
192
+ # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
193
+ *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
194
+ colors = {'black': '\033[30m', # basic colors
195
+ 'red': '\033[31m',
196
+ 'green': '\033[32m',
197
+ 'yellow': '\033[33m',
198
+ 'blue': '\033[34m',
199
+ 'magenta': '\033[35m',
200
+ 'cyan': '\033[36m',
201
+ 'white': '\033[37m',
202
+ 'bright_black': '\033[90m', # bright colors
203
+ 'bright_red': '\033[91m',
204
+ 'bright_green': '\033[92m',
205
+ 'bright_yellow': '\033[93m',
206
+ 'bright_blue': '\033[94m',
207
+ 'bright_magenta': '\033[95m',
208
+ 'bright_cyan': '\033[96m',
209
+ 'bright_white': '\033[97m',
210
+ 'end': '\033[0m', # misc
211
+ 'bold': '\033[1m',
212
+ 'underline': '\033[4m'}
213
+ return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
214
+
215
+
216
+ def labels_to_class_weights(labels, nc=80):
217
+ # Get class weights (inverse frequency) from training labels
218
+ if labels[0] is None: # no labels loaded
219
+ return torch.Tensor()
220
+
221
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
222
+ classes = labels[:, 0].astype(np.int) # labels = [class xywh]
223
+ weights = np.bincount(classes, minlength=nc) # occurrences per class
224
+
225
+ # Prepend gridpoint count (for uCE training)
226
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
227
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
228
+
229
+ weights[weights == 0] = 1 # replace empty bins with 1
230
+ weights = 1 / weights # number of targets per class
231
+ weights /= weights.sum() # normalize
232
+ return torch.from_numpy(weights)
233
+
234
+
235
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
236
+ # Produces image weights based on class_weights and image contents
237
+ class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])
238
+ image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
239
+ # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
240
+ return image_weights
241
+
242
+
243
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
244
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
245
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
246
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
247
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
248
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
249
+ x = [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,
250
+ 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,
251
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
252
+ return x
253
+
254
+
255
+ def xyxy2xywh(x):
256
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
257
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
258
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
259
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
260
+ y[:, 2] = x[:, 2] - x[:, 0] # width
261
+ y[:, 3] = x[:, 3] - x[:, 1] # height
262
+ return y
263
+
264
+
265
+ def xywh2xyxy(x):
266
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
267
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
268
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
269
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
270
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
271
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
272
+ return y
273
+
274
+
275
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
276
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
277
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
278
+ y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x
279
+ y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y
280
+ y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x
281
+ y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y
282
+ return y
283
+
284
+
285
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
286
+ # Convert normalized segments into pixel segments, shape (n,2)
287
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
288
+ y[:, 0] = w * x[:, 0] + padw # top left x
289
+ y[:, 1] = h * x[:, 1] + padh # top left y
290
+ return y
291
+
292
+
293
+ def segment2box(segment, width=640, height=640):
294
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
295
+ x, y = segment.T # segment xy
296
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
297
+ x, y, = x[inside], y[inside]
298
+ return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
299
+
300
+
301
+ def segments2boxes(segments):
302
+ # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
303
+ boxes = []
304
+ for s in segments:
305
+ x, y = s.T # segment xy
306
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
307
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
308
+
309
+
310
+ def resample_segments(segments, n=1000):
311
+ # Up-sample an (n,2) segment
312
+ for i, s in enumerate(segments):
313
+ s = np.concatenate((s, s[0:1, :]), axis=0)
314
+ x = np.linspace(0, len(s) - 1, n)
315
+ xp = np.arange(len(s))
316
+ segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
317
+ return segments
318
+
319
+
320
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
321
+ # Rescale coords (xyxy) from img1_shape to img0_shape
322
+ if ratio_pad is None: # calculate from img0_shape
323
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
324
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
325
+ else:
326
+ gain = ratio_pad[0][0]
327
+ pad = ratio_pad[1]
328
+
329
+ coords[:, [0, 2]] -= pad[0] # x padding
330
+ coords[:, [1, 3]] -= pad[1] # y padding
331
+ coords[:, :4] /= gain
332
+ clip_coords(coords, img0_shape)
333
+ return coords
334
+
335
+
336
+ def clip_coords(boxes, img_shape):
337
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
338
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
339
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
340
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
341
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
342
+
343
+
344
+ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
345
+ # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
346
+ box2 = box2.T
347
+
348
+ # Get the coordinates of bounding boxes
349
+ if x1y1x2y2: # x1, y1, x2, y2 = box1
350
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
351
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
352
+ else: # transform from xywh to xyxy
353
+ b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
354
+ b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
355
+ b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
356
+ b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
357
+
358
+ # Intersection area
359
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
360
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
361
+
362
+ # Union Area
363
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
364
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
365
+ union = w1 * h1 + w2 * h2 - inter + eps
366
+
367
+ iou = inter / union
368
+
369
+ if GIoU or DIoU or CIoU:
370
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
371
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
372
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
373
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
374
+ rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
375
+ (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared
376
+ if DIoU:
377
+ return iou - rho2 / c2 # DIoU
378
+ elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
379
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / (h2 + eps)) - torch.atan(w1 / (h1 + eps)), 2)
380
+ with torch.no_grad():
381
+ alpha = v / (v - iou + (1 + eps))
382
+ return iou - (rho2 / c2 + v * alpha) # CIoU
383
+ else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
384
+ c_area = cw * ch + eps # convex area
385
+ return iou - (c_area - union) / c_area # GIoU
386
+ else:
387
+ return iou # IoU
388
+
389
+
390
+
391
+
392
+ def bbox_alpha_iou(box1, box2, x1y1x2y2=False, GIoU=False, DIoU=False, CIoU=False, alpha=2, eps=1e-9):
393
+ # Returns tsqrt_he IoU of box1 to box2. box1 is 4, box2 is nx4
394
+ box2 = box2.T
395
+
396
+ # Get the coordinates of bounding boxes
397
+ if x1y1x2y2: # x1, y1, x2, y2 = box1
398
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
399
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
400
+ else: # transform from xywh to xyxy
401
+ b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
402
+ b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
403
+ b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
404
+ b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
405
+
406
+ # Intersection area
407
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
408
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
409
+
410
+ # Union Area
411
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
412
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
413
+ union = w1 * h1 + w2 * h2 - inter + eps
414
+
415
+ # change iou into pow(iou+eps)
416
+ # iou = inter / union
417
+ iou = torch.pow(inter/union + eps, alpha)
418
+ # beta = 2 * alpha
419
+ if GIoU or DIoU or CIoU:
420
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
421
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
422
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
423
+ c2 = (cw ** 2 + ch ** 2) ** alpha + eps # convex diagonal
424
+ rho_x = torch.abs(b2_x1 + b2_x2 - b1_x1 - b1_x2)
425
+ rho_y = torch.abs(b2_y1 + b2_y2 - b1_y1 - b1_y2)
426
+ rho2 = ((rho_x ** 2 + rho_y ** 2) / 4) ** alpha # center distance
427
+ if DIoU:
428
+ return iou - rho2 / c2 # DIoU
429
+ elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
430
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
431
+ with torch.no_grad():
432
+ alpha_ciou = v / ((1 + eps) - inter / union + v)
433
+ # return iou - (rho2 / c2 + v * alpha_ciou) # CIoU
434
+ return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)) # CIoU
435
+ else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
436
+ # c_area = cw * ch + eps # convex area
437
+ # return iou - (c_area - union) / c_area # GIoU
438
+ c_area = torch.max(cw * ch + eps, union) # convex area
439
+ return iou - torch.pow((c_area - union) / c_area + eps, alpha) # GIoU
440
+ else:
441
+ return iou # torch.log(iou+eps) or iou
442
+
443
+
444
+ def box_iou(box1, box2):
445
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
446
+ """
447
+ Return intersection-over-union (Jaccard index) of boxes.
448
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
449
+ Arguments:
450
+ box1 (Tensor[N, 4])
451
+ box2 (Tensor[M, 4])
452
+ Returns:
453
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
454
+ IoU values for every element in boxes1 and boxes2
455
+ """
456
+
457
+ def box_area(box):
458
+ # box = 4xn
459
+ return (box[2] - box[0]) * (box[3] - box[1])
460
+
461
+ area1 = box_area(box1.T)
462
+ area2 = box_area(box2.T)
463
+
464
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
465
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
466
+ return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
467
+
468
+
469
+ def wh_iou(wh1, wh2):
470
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
471
+ wh1 = wh1[:, None] # [N,1,2]
472
+ wh2 = wh2[None] # [1,M,2]
473
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
474
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
475
+
476
+
477
+ def box_giou(box1, box2):
478
+ """
479
+ Return generalized intersection-over-union (Jaccard index) between two sets of boxes.
480
+ Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
481
+ ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
482
+ Args:
483
+ boxes1 (Tensor[N, 4]): first set of boxes
484
+ boxes2 (Tensor[M, 4]): second set of boxes
485
+ Returns:
486
+ Tensor[N, M]: the NxM matrix containing the pairwise generalized IoU values
487
+ for every element in boxes1 and boxes2
488
+ """
489
+
490
+ def box_area(box):
491
+ # box = 4xn
492
+ return (box[2] - box[0]) * (box[3] - box[1])
493
+
494
+ area1 = box_area(box1.T)
495
+ area2 = box_area(box2.T)
496
+
497
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
498
+ union = (area1[:, None] + area2 - inter)
499
+
500
+ iou = inter / union
501
+
502
+ lti = torch.min(box1[:, None, :2], box2[:, :2])
503
+ rbi = torch.max(box1[:, None, 2:], box2[:, 2:])
504
+
505
+ whi = (rbi - lti).clamp(min=0) # [N,M,2]
506
+ areai = whi[:, :, 0] * whi[:, :, 1]
507
+
508
+ return iou - (areai - union) / areai
509
+
510
+
511
+ def box_ciou(box1, box2, eps: float = 1e-7):
512
+ """
513
+ Return complete intersection-over-union (Jaccard index) between two sets of boxes.
514
+ Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
515
+ ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
516
+ Args:
517
+ boxes1 (Tensor[N, 4]): first set of boxes
518
+ boxes2 (Tensor[M, 4]): second set of boxes
519
+ eps (float, optional): small number to prevent division by zero. Default: 1e-7
520
+ Returns:
521
+ Tensor[N, M]: the NxM matrix containing the pairwise complete IoU values
522
+ for every element in boxes1 and boxes2
523
+ """
524
+
525
+ def box_area(box):
526
+ # box = 4xn
527
+ return (box[2] - box[0]) * (box[3] - box[1])
528
+
529
+ area1 = box_area(box1.T)
530
+ area2 = box_area(box2.T)
531
+
532
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
533
+ union = (area1[:, None] + area2 - inter)
534
+
535
+ iou = inter / union
536
+
537
+ lti = torch.min(box1[:, None, :2], box2[:, :2])
538
+ rbi = torch.max(box1[:, None, 2:], box2[:, 2:])
539
+
540
+ whi = (rbi - lti).clamp(min=0) # [N,M,2]
541
+ diagonal_distance_squared = (whi[:, :, 0] ** 2) + (whi[:, :, 1] ** 2) + eps
542
+
543
+ # centers of boxes
544
+ x_p = (box1[:, None, 0] + box1[:, None, 2]) / 2
545
+ y_p = (box1[:, None, 1] + box1[:, None, 3]) / 2
546
+ x_g = (box2[:, 0] + box2[:, 2]) / 2
547
+ y_g = (box2[:, 1] + box2[:, 3]) / 2
548
+ # The distance between boxes' centers squared.
549
+ centers_distance_squared = (x_p - x_g) ** 2 + (y_p - y_g) ** 2
550
+
551
+ w_pred = box1[:, None, 2] - box1[:, None, 0]
552
+ h_pred = box1[:, None, 3] - box1[:, None, 1]
553
+
554
+ w_gt = box2[:, 2] - box2[:, 0]
555
+ h_gt = box2[:, 3] - box2[:, 1]
556
+
557
+ v = (4 / (torch.pi ** 2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2)
558
+ with torch.no_grad():
559
+ alpha = v / (1 - iou + v + eps)
560
+ return iou - (centers_distance_squared / diagonal_distance_squared) - alpha * v
561
+
562
+
563
+ def box_diou(box1, box2, eps: float = 1e-7):
564
+ """
565
+ Return distance intersection-over-union (Jaccard index) between two sets of boxes.
566
+ Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
567
+ ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
568
+ Args:
569
+ boxes1 (Tensor[N, 4]): first set of boxes
570
+ boxes2 (Tensor[M, 4]): second set of boxes
571
+ eps (float, optional): small number to prevent division by zero. Default: 1e-7
572
+ Returns:
573
+ Tensor[N, M]: the NxM matrix containing the pairwise distance IoU values
574
+ for every element in boxes1 and boxes2
575
+ """
576
+
577
+ def box_area(box):
578
+ # box = 4xn
579
+ return (box[2] - box[0]) * (box[3] - box[1])
580
+
581
+ area1 = box_area(box1.T)
582
+ area2 = box_area(box2.T)
583
+
584
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
585
+ union = (area1[:, None] + area2 - inter)
586
+
587
+ iou = inter / union
588
+
589
+ lti = torch.min(box1[:, None, :2], box2[:, :2])
590
+ rbi = torch.max(box1[:, None, 2:], box2[:, 2:])
591
+
592
+ whi = (rbi - lti).clamp(min=0) # [N,M,2]
593
+ diagonal_distance_squared = (whi[:, :, 0] ** 2) + (whi[:, :, 1] ** 2) + eps
594
+
595
+ # centers of boxes
596
+ x_p = (box1[:, None, 0] + box1[:, None, 2]) / 2
597
+ y_p = (box1[:, None, 1] + box1[:, None, 3]) / 2
598
+ x_g = (box2[:, 0] + box2[:, 2]) / 2
599
+ y_g = (box2[:, 1] + box2[:, 3]) / 2
600
+ # The distance between boxes' centers squared.
601
+ centers_distance_squared = (x_p - x_g) ** 2 + (y_p - y_g) ** 2
602
+
603
+ # The distance IoU is the IoU penalized by a normalized
604
+ # distance between boxes' centers squared.
605
+ return iou - (centers_distance_squared / diagonal_distance_squared)
606
+
607
+
608
+ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
609
+ labels=()):
610
+ """Runs Non-Maximum Suppression (NMS) on inference results
611
+
612
+ Returns:
613
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
614
+ """
615
+
616
+ nc = prediction.shape[2] - 5 # number of classes
617
+ xc = prediction[..., 4] > conf_thres # candidates
618
+
619
+ # Settings
620
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
621
+ max_det = 300 # maximum number of detections per image
622
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
623
+ time_limit = 10.0 # seconds to quit after
624
+ redundant = True # require redundant detections
625
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
626
+ merge = False # use merge-NMS
627
+
628
+ t = time.time()
629
+ output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
630
+ for xi, x in enumerate(prediction): # image index, image inference
631
+ # Apply constraints
632
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
633
+ x = x[xc[xi]] # confidence
634
+
635
+ # Cat apriori labels if autolabelling
636
+ if labels and len(labels[xi]):
637
+ l = labels[xi]
638
+ v = torch.zeros((len(l), nc + 5), device=x.device)
639
+ v[:, :4] = l[:, 1:5] # box
640
+ v[:, 4] = 1.0 # conf
641
+ v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
642
+ x = torch.cat((x, v), 0)
643
+
644
+ # If none remain process next image
645
+ if not x.shape[0]:
646
+ continue
647
+
648
+ # Compute conf
649
+ if nc == 1:
650
+ x[:, 5:] = x[:, 4:5] # for models with one class, cls_loss is 0 and cls_conf is always 0.5,
651
+ # so there is no need to multiplicate.
652
+ else:
653
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
654
+
655
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
656
+ box = xywh2xyxy(x[:, :4])
657
+
658
+ # Detections matrix nx6 (xyxy, conf, cls)
659
+ if multi_label:
660
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
661
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
662
+ else: # best class only
663
+ conf, j = x[:, 5:].max(1, keepdim=True)
664
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
665
+
666
+ # Filter by class
667
+ if classes is not None:
668
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
669
+
670
+ # Apply finite constraint
671
+ # if not torch.isfinite(x).all():
672
+ # x = x[torch.isfinite(x).all(1)]
673
+
674
+ # Check shape
675
+ n = x.shape[0] # number of boxes
676
+ if not n: # no boxes
677
+ continue
678
+ elif n > max_nms: # excess boxes
679
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
680
+
681
+ # Batched NMS
682
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
683
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
684
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
685
+ if i.shape[0] > max_det: # limit detections
686
+ i = i[:max_det]
687
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
688
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
689
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
690
+ weights = iou * scores[None] # box weights
691
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
692
+ if redundant:
693
+ i = i[iou.sum(1) > 1] # require redundancy
694
+
695
+ output[xi] = x[i]
696
+ if (time.time() - t) > time_limit:
697
+ print(f'WARNING: NMS time limit {time_limit}s exceeded')
698
+ break # time limit exceeded
699
+
700
+ return output
701
+
702
+
703
+ def non_max_suppression_kpt(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
704
+ labels=(), kpt_label=False, nc=None, nkpt=None):
705
+ """Runs Non-Maximum Suppression (NMS) on inference results
706
+
707
+ Returns:
708
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
709
+ """
710
+ if nc is None:
711
+ nc = prediction.shape[2] - 5 if not kpt_label else prediction.shape[2] - 56 # number of classes
712
+ xc = prediction[..., 4] > conf_thres # candidates
713
+
714
+ # Settings
715
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
716
+ max_det = 300 # maximum number of detections per image
717
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
718
+ time_limit = 10.0 # seconds to quit after
719
+ redundant = True # require redundant detections
720
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
721
+ merge = False # use merge-NMS
722
+
723
+ t = time.time()
724
+ output = [torch.zeros((0,6), device=prediction.device)] * prediction.shape[0]
725
+ for xi, x in enumerate(prediction): # image index, image inference
726
+ # Apply constraints
727
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
728
+ x = x[xc[xi]] # confidence
729
+
730
+ # Cat apriori labels if autolabelling
731
+ if labels and len(labels[xi]):
732
+ l = labels[xi]
733
+ v = torch.zeros((len(l), nc + 5), device=x.device)
734
+ v[:, :4] = l[:, 1:5] # box
735
+ v[:, 4] = 1.0 # conf
736
+ v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
737
+ x = torch.cat((x, v), 0)
738
+
739
+ # If none remain process next image
740
+ if not x.shape[0]:
741
+ continue
742
+
743
+ # Compute conf
744
+ x[:, 5:5+nc] *= x[:, 4:5] # conf = obj_conf * cls_conf
745
+
746
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
747
+ box = xywh2xyxy(x[:, :4])
748
+
749
+ # Detections matrix nx6 (xyxy, conf, cls)
750
+ if multi_label:
751
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
752
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
753
+ else: # best class only
754
+ if not kpt_label:
755
+ conf, j = x[:, 5:].max(1, keepdim=True)
756
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
757
+ else:
758
+ kpts = x[:, 6:]
759
+ conf, j = x[:, 5:6].max(1, keepdim=True)
760
+ x = torch.cat((box, conf, j.float(), kpts), 1)[conf.view(-1) > conf_thres]
761
+
762
+
763
+ # Filter by class
764
+ if classes is not None:
765
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
766
+
767
+ # Apply finite constraint
768
+ # if not torch.isfinite(x).all():
769
+ # x = x[torch.isfinite(x).all(1)]
770
+
771
+ # Check shape
772
+ n = x.shape[0] # number of boxes
773
+ if not n: # no boxes
774
+ continue
775
+ elif n > max_nms: # excess boxes
776
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
777
+
778
+ # Batched NMS
779
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
780
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
781
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
782
+ if i.shape[0] > max_det: # limit detections
783
+ i = i[:max_det]
784
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
785
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
786
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
787
+ weights = iou * scores[None] # box weights
788
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
789
+ if redundant:
790
+ i = i[iou.sum(1) > 1] # require redundancy
791
+
792
+ output[xi] = x[i]
793
+ if (time.time() - t) > time_limit:
794
+ print(f'WARNING: NMS time limit {time_limit}s exceeded')
795
+ break # time limit exceeded
796
+
797
+ return output
798
+
799
+
800
+ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
801
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
802
+ x = torch.load(f, map_location=torch.device('cpu'))
803
+ if x.get('ema'):
804
+ x['model'] = x['ema'] # replace model with ema
805
+ for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys
806
+ x[k] = None
807
+ x['epoch'] = -1
808
+ x['model'].half() # to FP16
809
+ for p in x['model'].parameters():
810
+ p.requires_grad = False
811
+ torch.save(x, s or f)
812
+ mb = os.path.getsize(s or f) / 1E6 # filesize
813
+ print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB")
814
+
815
+
816
+ def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):
817
+ # Print mutation results to evolve.txt (for use with train.py --evolve)
818
+ a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
819
+ b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
820
+ c = '%10.4g' * len(results) % results # results (P, R, [email protected], [email protected]:0.95, val_losses x 3)
821
+ print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
822
+
823
+ if bucket:
824
+ url = 'gs://%s/evolve.txt' % bucket
825
+ if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0):
826
+ os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local
827
+
828
+ with open('evolve.txt', 'a') as f: # append result
829
+ f.write(c + b + '\n')
830
+ x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
831
+ x = x[np.argsort(-fitness(x))] # sort
832
+ np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness
833
+
834
+ # Save yaml
835
+ for i, k in enumerate(hyp.keys()):
836
+ hyp[k] = float(x[0, i + 7])
837
+ with open(yaml_file, 'w') as f:
838
+ results = tuple(x[0, :7])
839
+ c = '%10.4g' * len(results) % results # results (P, R, [email protected], [email protected]:0.95, val_losses x 3)
840
+ f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n')
841
+ yaml.dump(hyp, f, sort_keys=False)
842
+
843
+ if bucket:
844
+ os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload
845
+
846
+
847
+ def apply_classifier(x, model, img, im0):
848
+ # applies a second stage classifier to yolo outputs
849
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
850
+ for i, d in enumerate(x): # per image
851
+ if d is not None and len(d):
852
+ d = d.clone()
853
+
854
+ # Reshape and pad cutouts
855
+ b = xyxy2xywh(d[:, :4]) # boxes
856
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
857
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
858
+ d[:, :4] = xywh2xyxy(b).long()
859
+
860
+ # Rescale boxes from img_size to im0 size
861
+ scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
862
+
863
+ # Classes
864
+ pred_cls1 = d[:, 5].long()
865
+ ims = []
866
+ for j, a in enumerate(d): # per item
867
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
868
+ im = cv2.resize(cutout, (224, 224)) # BGR
869
+ # cv2.imwrite('test%i.jpg' % j, cutout)
870
+
871
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
872
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
873
+ im /= 255.0 # 0 - 255 to 0.0 - 1.0
874
+ ims.append(im)
875
+
876
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
877
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
878
+
879
+ return x
880
+
881
+
882
+ def increment_path(path, exist_ok=True, sep=''):
883
+ # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc.
884
+ path = Path(path) # os-agnostic
885
+ if (path.exists() and exist_ok) or (not path.exists()):
886
+ return str(path)
887
+ else:
888
+ dirs = glob.glob(f"{path}{sep}*") # similar paths
889
+ matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
890
+ i = [int(m.groups()[0]) for m in matches if m] # indices
891
+ n = max(i) + 1 if i else 2 # increment number
892
+ return f"{path}{sep}{n}" # update path
yolov7detect/utils/google_utils.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Google utils: https://cloud.google.com/storage/docs/reference/libraries
2
+
3
+ import os
4
+ import platform
5
+ import subprocess
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import requests
10
+ import torch
11
+
12
+
13
+ def attempt_download_from_hub(repo_id, hf_token=None):
14
+ # https://github.com/fcakyon/yolov5-pip/blob/main/yolov5/utils/downloads.py
15
+ from huggingface_hub import hf_hub_download, list_repo_files
16
+ from huggingface_hub.utils._errors import RepositoryNotFoundError
17
+ from huggingface_hub.utils._validators import HFValidationError
18
+ try:
19
+ repo_files = list_repo_files(repo_id=repo_id, repo_type='model', token=hf_token)
20
+ model_file = [f for f in repo_files if f.endswith('.pt')][0]
21
+ file = hf_hub_download(
22
+ repo_id=repo_id,
23
+ filename=model_file,
24
+ repo_type='model',
25
+ token=hf_token,
26
+ )
27
+ return file
28
+ except (RepositoryNotFoundError, HFValidationError):
29
+ return None
30
+
31
+ def gsutil_getsize(url=''):
32
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
33
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
34
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
35
+
36
+ """ The attempt_download function has been fixed by @kadirnar.
37
+ tag = subprocess.check_output('git tag', shell=True).decode().split()[-1]
38
+ IndexError: list index out of range
39
+ """
40
+ def attempt_download(file, repo="WongKinYiu/yolov7"):
41
+ # Attempt file download if does not exist
42
+ file = Path(str(file).strip().replace("'", "").lower())
43
+ if not file.exists():
44
+ # Set default assets
45
+ assets = [
46
+ "yolov7.pt",
47
+ "yolov7-tiny.pt",
48
+ "yolov7x.pt",
49
+ "yolov7-d6.pt",
50
+ "yolov7-e6.pt",
51
+ "yolov7-e6e.pt",
52
+ "yolov7-w6.pt",
53
+ ]
54
+ try:
55
+ response = requests.get(f"https://api.github.com/repos/{repo}/releases").json() # github api
56
+ if len(response) > 0:
57
+ release_assets = response[0] # get dictionary of assets
58
+ # Get names of assets if it rleases exists
59
+ assets = [release_asset["name"] for release_asset in release_assets["assets"]]
60
+ # Get first tag which is the latest tag
61
+ tag = release_assets.get("tag_name")
62
+ except KeyError: # fallback plan
63
+ tag = subprocess.check_output("git tag", shell=True).decode().split()[-1]
64
+ except subprocess.CalledProcessError: # fallback to default release if can't get tag
65
+ tag = "v0.1"
66
+
67
+ name = file.name
68
+ if name in assets:
69
+ msg = f"{file} missing, try downloading from https://github.com/{repo}/releases/"
70
+ redundant = False # second download option
71
+ try: # GitHub
72
+ url = f"https://github.com/{repo}/releases/download/{tag}/{name}"
73
+ print(f"Downloading {url} to {file}...")
74
+ torch.hub.download_url_to_file(url, file)
75
+ assert file.exists() and file.stat().st_size > 1e6 # check
76
+ except Exception as e: # GCP
77
+ print(f"Download error: {e}")
78
+ assert redundant, "No secondary mirror"
79
+ url = f"https://storage.googleapis.com/{repo}/ckpt/{name}"
80
+ print(f"Downloading {url} to {file}...")
81
+ # torch.hub.download_url_to_file(url, weights)
82
+ os.system(f"curl -L {url} -o {file}")
83
+ finally:
84
+ if not file.exists() or file.stat().st_size < 1e6: # check
85
+ file.unlink(missing_ok=True) # remove partial downloads
86
+ print(f"ERROR: Download failure: {msg}")
87
+ print("")
88
+ return file
89
+ return str(file) # return file
90
+
91
+ def gdrive_download(id='', file='tmp.zip'):
92
+ # Downloads a file from Google Drive. from yolov7.utils.google_utils import *; gdrive_download()
93
+ t = time.time()
94
+ file = Path(file)
95
+ cookie = Path('cookie') # gdrive cookie
96
+ print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
97
+ file.unlink(missing_ok=True) # remove existing file
98
+ cookie.unlink(missing_ok=True) # remove existing cookie
99
+
100
+ # Attempt file download
101
+ out = "NUL" if platform.system() == "Windows" else "/dev/null"
102
+ os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
103
+ if os.path.exists('cookie'): # large file
104
+ s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
105
+ else: # small file
106
+ s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
107
+ r = os.system(s) # execute, capture return
108
+ cookie.unlink(missing_ok=True) # remove existing cookie
109
+
110
+ # Error check
111
+ if r != 0:
112
+ file.unlink(missing_ok=True) # remove partial
113
+ print('Download error ') # raise Exception('Download error')
114
+ return r
115
+
116
+ # Unzip if archive
117
+ if file.suffix == '.zip':
118
+ print('unzipping... ', end='')
119
+ os.system(f'unzip -q {file}') # unzip
120
+ file.unlink() # remove zip to free space
121
+
122
+ print(f'Done ({time.time() - t:.1f}s)')
123
+ return r
124
+
125
+
126
+ def get_token(cookie="./cookie"):
127
+ with open(cookie) as f:
128
+ for line in f:
129
+ if "download" in line:
130
+ return line.split()[-1]
131
+ return ""
132
+
133
+ # def upload_blob(bucket_name, source_file_name, destination_blob_name):
134
+ # # Uploads a file to a bucket
135
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
136
+ #
137
+ # storage_client = storage.Client()
138
+ # bucket = storage_client.get_bucket(bucket_name)
139
+ # blob = bucket.blob(destination_blob_name)
140
+ #
141
+ # blob.upload_from_filename(source_file_name)
142
+ #
143
+ # print('File {} uploaded to {}.'.format(
144
+ # source_file_name,
145
+ # destination_blob_name))
146
+ #
147
+ #
148
+ # def download_blob(bucket_name, source_blob_name, destination_file_name):
149
+ # # Uploads a blob from a bucket
150
+ # storage_client = storage.Client()
151
+ # bucket = storage_client.get_bucket(bucket_name)
152
+ # blob = bucket.blob(source_blob_name)
153
+ #
154
+ # blob.download_to_filename(destination_file_name)
155
+ #
156
+ # print('Blob {} downloaded to {}.'.format(
157
+ # source_blob_name,
158
+ # destination_file_name))
yolov7detect/utils/loss.py ADDED
@@ -0,0 +1,1697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Loss functions
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from yolov7.utils.general import bbox_iou, bbox_alpha_iou, box_iou, box_giou, box_diou, box_ciou, xywh2xyxy
8
+ from yolov7.utils.torch_utils import is_parallel
9
+
10
+
11
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
12
+ # return positive, negative label smoothing BCE targets
13
+ return 1.0 - 0.5 * eps, 0.5 * eps
14
+
15
+
16
+ class BCEBlurWithLogitsLoss(nn.Module):
17
+ # BCEwithLogitLoss() with reduced missing label effects.
18
+ def __init__(self, alpha=0.05):
19
+ super(BCEBlurWithLogitsLoss, self).__init__()
20
+ self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
21
+ self.alpha = alpha
22
+
23
+ def forward(self, pred, true):
24
+ loss = self.loss_fcn(pred, true)
25
+ pred = torch.sigmoid(pred) # prob from logits
26
+ dx = pred - true # reduce only missing label effects
27
+ # dx = (pred - true).abs() # reduce missing label and false label effects
28
+ alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
29
+ loss *= alpha_factor
30
+ return loss.mean()
31
+
32
+
33
+ class SigmoidBin(nn.Module):
34
+ stride = None # strides computed during build
35
+ export = False # onnx export
36
+
37
+ def __init__(self, bin_count=10, min=0.0, max=1.0, reg_scale = 2.0, use_loss_regression=True, use_fw_regression=True, BCE_weight=1.0, smooth_eps=0.0):
38
+ super(SigmoidBin, self).__init__()
39
+
40
+ self.bin_count = bin_count
41
+ self.length = bin_count + 1
42
+ self.min = min
43
+ self.max = max
44
+ self.scale = float(max - min)
45
+ self.shift = self.scale / 2.0
46
+
47
+ self.use_loss_regression = use_loss_regression
48
+ self.use_fw_regression = use_fw_regression
49
+ self.reg_scale = reg_scale
50
+ self.BCE_weight = BCE_weight
51
+
52
+ start = min + (self.scale/2.0) / self.bin_count
53
+ end = max - (self.scale/2.0) / self.bin_count
54
+ step = self.scale / self.bin_count
55
+ self.step = step
56
+ #print(f" start = {start}, end = {end}, step = {step} ")
57
+
58
+ bins = torch.range(start, end + 0.0001, step).float()
59
+ self.register_buffer('bins', bins)
60
+
61
+
62
+ self.cp = 1.0 - 0.5 * smooth_eps
63
+ self.cn = 0.5 * smooth_eps
64
+
65
+ self.BCEbins = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([BCE_weight]))
66
+ self.MSELoss = nn.MSELoss()
67
+
68
+ def get_length(self):
69
+ return self.length
70
+
71
+ def forward(self, pred):
72
+ assert pred.shape[-1] == self.length, 'pred.shape[-1]=%d is not equal to self.length=%d' % (pred.shape[-1], self.length)
73
+
74
+ pred_reg = (pred[..., 0] * self.reg_scale - self.reg_scale/2.0) * self.step
75
+ pred_bin = pred[..., 1:(1+self.bin_count)]
76
+
77
+ _, bin_idx = torch.max(pred_bin, dim=-1)
78
+ bin_bias = self.bins[bin_idx]
79
+
80
+ if self.use_fw_regression:
81
+ result = pred_reg + bin_bias
82
+ else:
83
+ result = bin_bias
84
+ result = result.clamp(min=self.min, max=self.max)
85
+
86
+ return result
87
+
88
+
89
+ def training_loss(self, pred, target):
90
+ assert pred.shape[-1] == self.length, 'pred.shape[-1]=%d is not equal to self.length=%d' % (pred.shape[-1], self.length)
91
+ assert pred.shape[0] == target.shape[0], 'pred.shape=%d is not equal to the target.shape=%d' % (pred.shape[0], target.shape[0])
92
+ device = pred.device
93
+
94
+ pred_reg = (pred[..., 0].sigmoid() * self.reg_scale - self.reg_scale/2.0) * self.step
95
+ pred_bin = pred[..., 1:(1+self.bin_count)]
96
+
97
+ diff_bin_target = torch.abs(target[..., None] - self.bins)
98
+ _, bin_idx = torch.min(diff_bin_target, dim=-1)
99
+
100
+ bin_bias = self.bins[bin_idx]
101
+ bin_bias.requires_grad = False
102
+ result = pred_reg + bin_bias
103
+
104
+ target_bins = torch.full_like(pred_bin, self.cn, device=device) # targets
105
+ n = pred.shape[0]
106
+ target_bins[range(n), bin_idx] = self.cp
107
+
108
+ loss_bin = self.BCEbins(pred_bin, target_bins) # BCE
109
+
110
+ if self.use_loss_regression:
111
+ loss_regression = self.MSELoss(result, target) # MSE
112
+ loss = loss_bin + loss_regression
113
+ else:
114
+ loss = loss_bin
115
+
116
+ out_result = result.clamp(min=self.min, max=self.max)
117
+
118
+ return loss, out_result
119
+
120
+
121
+ class FocalLoss(nn.Module):
122
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
123
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
124
+ super(FocalLoss, self).__init__()
125
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
126
+ self.gamma = gamma
127
+ self.alpha = alpha
128
+ self.reduction = loss_fcn.reduction
129
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
130
+
131
+ def forward(self, pred, true):
132
+ loss = self.loss_fcn(pred, true)
133
+ # p_t = torch.exp(-loss)
134
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
135
+
136
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
137
+ pred_prob = torch.sigmoid(pred) # prob from logits
138
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
139
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
140
+ modulating_factor = (1.0 - p_t) ** self.gamma
141
+ loss *= alpha_factor * modulating_factor
142
+
143
+ if self.reduction == 'mean':
144
+ return loss.mean()
145
+ elif self.reduction == 'sum':
146
+ return loss.sum()
147
+ else: # 'none'
148
+ return loss
149
+
150
+
151
+ class QFocalLoss(nn.Module):
152
+ # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
153
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
154
+ super(QFocalLoss, self).__init__()
155
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
156
+ self.gamma = gamma
157
+ self.alpha = alpha
158
+ self.reduction = loss_fcn.reduction
159
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
160
+
161
+ def forward(self, pred, true):
162
+ loss = self.loss_fcn(pred, true)
163
+
164
+ pred_prob = torch.sigmoid(pred) # prob from logits
165
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
166
+ modulating_factor = torch.abs(true - pred_prob) ** self.gamma
167
+ loss *= alpha_factor * modulating_factor
168
+
169
+ if self.reduction == 'mean':
170
+ return loss.mean()
171
+ elif self.reduction == 'sum':
172
+ return loss.sum()
173
+ else: # 'none'
174
+ return loss
175
+
176
+ class RankSort(torch.autograd.Function):
177
+ @staticmethod
178
+ def forward(ctx, logits, targets, delta_RS=0.50, eps=1e-10):
179
+
180
+ classification_grads=torch.zeros(logits.shape).cuda()
181
+
182
+ #Filter fg logits
183
+ fg_labels = (targets > 0.)
184
+ fg_logits = logits[fg_labels]
185
+ fg_targets = targets[fg_labels]
186
+ fg_num = len(fg_logits)
187
+
188
+ #Do not use bg with scores less than minimum fg logit
189
+ #since changing its score does not have an effect on precision
190
+ threshold_logit = torch.min(fg_logits)-delta_RS
191
+ relevant_bg_labels=((targets==0) & (logits>=threshold_logit))
192
+
193
+ relevant_bg_logits = logits[relevant_bg_labels]
194
+ relevant_bg_grad=torch.zeros(len(relevant_bg_logits)).cuda()
195
+ sorting_error=torch.zeros(fg_num).cuda()
196
+ ranking_error=torch.zeros(fg_num).cuda()
197
+ fg_grad=torch.zeros(fg_num).cuda()
198
+
199
+ #sort the fg logits
200
+ order=torch.argsort(fg_logits)
201
+ #Loops over each positive following the order
202
+ for ii in order:
203
+ # Difference Transforms (x_ij)
204
+ fg_relations=fg_logits-fg_logits[ii]
205
+ bg_relations=relevant_bg_logits-fg_logits[ii]
206
+
207
+ if delta_RS > 0:
208
+ fg_relations=torch.clamp(fg_relations/(2*delta_RS)+0.5,min=0,max=1)
209
+ bg_relations=torch.clamp(bg_relations/(2*delta_RS)+0.5,min=0,max=1)
210
+ else:
211
+ fg_relations = (fg_relations >= 0).float()
212
+ bg_relations = (bg_relations >= 0).float()
213
+
214
+ # Rank of ii among pos and false positive number (bg with larger scores)
215
+ rank_pos=torch.sum(fg_relations)
216
+ FP_num=torch.sum(bg_relations)
217
+
218
+ # Rank of ii among all examples
219
+ rank=rank_pos+FP_num
220
+
221
+ # Ranking error of example ii. target_ranking_error is always 0. (Eq. 7)
222
+ ranking_error[ii]=FP_num/rank
223
+
224
+ # Current sorting error of example ii. (Eq. 7)
225
+ current_sorting_error = torch.sum(fg_relations*(1-fg_targets))/rank_pos
226
+
227
+ #Find examples in the target sorted order for example ii
228
+ iou_relations = (fg_targets >= fg_targets[ii])
229
+ target_sorted_order = iou_relations * fg_relations
230
+
231
+ #The rank of ii among positives in sorted order
232
+ rank_pos_target = torch.sum(target_sorted_order)
233
+
234
+ #Compute target sorting error. (Eq. 8)
235
+ #Since target ranking error is 0, this is also total target error
236
+ target_sorting_error= torch.sum(target_sorted_order*(1-fg_targets))/rank_pos_target
237
+
238
+ #Compute sorting error on example ii
239
+ sorting_error[ii] = current_sorting_error - target_sorting_error
240
+
241
+ #Identity Update for Ranking Error
242
+ if FP_num > eps:
243
+ #For ii the update is the ranking error
244
+ fg_grad[ii] -= ranking_error[ii]
245
+ #For negatives, distribute error via ranking pmf (i.e. bg_relations/FP_num)
246
+ relevant_bg_grad += (bg_relations*(ranking_error[ii]/FP_num))
247
+
248
+ #Find the positives that are misranked (the cause of the error)
249
+ #These are the ones with smaller IoU but larger logits
250
+ missorted_examples = (~ iou_relations) * fg_relations
251
+
252
+ #Denominotor of sorting pmf
253
+ sorting_pmf_denom = torch.sum(missorted_examples)
254
+
255
+ #Identity Update for Sorting Error
256
+ if sorting_pmf_denom > eps:
257
+ #For ii the update is the sorting error
258
+ fg_grad[ii] -= sorting_error[ii]
259
+ #For positives, distribute error via sorting pmf (i.e. missorted_examples/sorting_pmf_denom)
260
+ fg_grad += (missorted_examples*(sorting_error[ii]/sorting_pmf_denom))
261
+
262
+ #Normalize gradients by number of positives
263
+ classification_grads[fg_labels]= (fg_grad/fg_num)
264
+ classification_grads[relevant_bg_labels]= (relevant_bg_grad/fg_num)
265
+
266
+ ctx.save_for_backward(classification_grads)
267
+
268
+ return ranking_error.mean(), sorting_error.mean()
269
+
270
+ @staticmethod
271
+ def backward(ctx, out_grad1, out_grad2):
272
+ g1, =ctx.saved_tensors
273
+ return g1*out_grad1, None, None, None
274
+
275
+ class aLRPLoss(torch.autograd.Function):
276
+ @staticmethod
277
+ def forward(ctx, logits, targets, regression_losses, delta=1., eps=1e-5):
278
+ classification_grads=torch.zeros(logits.shape).cuda()
279
+
280
+ #Filter fg logits
281
+ fg_labels = (targets == 1)
282
+ fg_logits = logits[fg_labels]
283
+ fg_num = len(fg_logits)
284
+
285
+ #Do not use bg with scores less than minimum fg logit
286
+ #since changing its score does not have an effect on precision
287
+ threshold_logit = torch.min(fg_logits)-delta
288
+
289
+ #Get valid bg logits
290
+ relevant_bg_labels=((targets==0)&(logits>=threshold_logit))
291
+ relevant_bg_logits=logits[relevant_bg_labels]
292
+ relevant_bg_grad=torch.zeros(len(relevant_bg_logits)).cuda()
293
+ rank=torch.zeros(fg_num).cuda()
294
+ prec=torch.zeros(fg_num).cuda()
295
+ fg_grad=torch.zeros(fg_num).cuda()
296
+
297
+ max_prec=0
298
+ #sort the fg logits
299
+ order=torch.argsort(fg_logits)
300
+ #Loops over each positive following the order
301
+ for ii in order:
302
+ #x_ij s as score differences with fgs
303
+ fg_relations=fg_logits-fg_logits[ii]
304
+ #Apply piecewise linear function and determine relations with fgs
305
+ fg_relations=torch.clamp(fg_relations/(2*delta)+0.5,min=0,max=1)
306
+ #Discard i=j in the summation in rank_pos
307
+ fg_relations[ii]=0
308
+
309
+ #x_ij s as score differences with bgs
310
+ bg_relations=relevant_bg_logits-fg_logits[ii]
311
+ #Apply piecewise linear function and determine relations with bgs
312
+ bg_relations=torch.clamp(bg_relations/(2*delta)+0.5,min=0,max=1)
313
+
314
+ #Compute the rank of the example within fgs and number of bgs with larger scores
315
+ rank_pos=1+torch.sum(fg_relations)
316
+ FP_num=torch.sum(bg_relations)
317
+ #Store the total since it is normalizer also for aLRP Regression error
318
+ rank[ii]=rank_pos+FP_num
319
+
320
+ #Compute precision for this example to compute classification loss
321
+ prec[ii]=rank_pos/rank[ii]
322
+ #For stability, set eps to a infinitesmall value (e.g. 1e-6), then compute grads
323
+ if FP_num > eps:
324
+ fg_grad[ii] = -(torch.sum(fg_relations*regression_losses)+FP_num)/rank[ii]
325
+ relevant_bg_grad += (bg_relations*(-fg_grad[ii]/FP_num))
326
+
327
+ #aLRP with grad formulation fg gradient
328
+ classification_grads[fg_labels]= fg_grad
329
+ #aLRP with grad formulation bg gradient
330
+ classification_grads[relevant_bg_labels]= relevant_bg_grad
331
+
332
+ classification_grads /= (fg_num)
333
+
334
+ cls_loss=1-prec.mean()
335
+ ctx.save_for_backward(classification_grads)
336
+
337
+ return cls_loss, rank, order
338
+
339
+ @staticmethod
340
+ def backward(ctx, out_grad1, out_grad2, out_grad3):
341
+ g1, =ctx.saved_tensors
342
+ return g1*out_grad1, None, None, None, None
343
+
344
+
345
+ class APLoss(torch.autograd.Function):
346
+ @staticmethod
347
+ def forward(ctx, logits, targets, delta=1.):
348
+ classification_grads=torch.zeros(logits.shape).cuda()
349
+
350
+ #Filter fg logits
351
+ fg_labels = (targets == 1)
352
+ fg_logits = logits[fg_labels]
353
+ fg_num = len(fg_logits)
354
+
355
+ #Do not use bg with scores less than minimum fg logit
356
+ #since changing its score does not have an effect on precision
357
+ threshold_logit = torch.min(fg_logits)-delta
358
+
359
+ #Get valid bg logits
360
+ relevant_bg_labels=((targets==0)&(logits>=threshold_logit))
361
+ relevant_bg_logits=logits[relevant_bg_labels]
362
+ relevant_bg_grad=torch.zeros(len(relevant_bg_logits)).cuda()
363
+ rank=torch.zeros(fg_num).cuda()
364
+ prec=torch.zeros(fg_num).cuda()
365
+ fg_grad=torch.zeros(fg_num).cuda()
366
+
367
+ max_prec=0
368
+ #sort the fg logits
369
+ order=torch.argsort(fg_logits)
370
+ #Loops over each positive following the order
371
+ for ii in order:
372
+ #x_ij s as score differences with fgs
373
+ fg_relations=fg_logits-fg_logits[ii]
374
+ #Apply piecewise linear function and determine relations with fgs
375
+ fg_relations=torch.clamp(fg_relations/(2*delta)+0.5,min=0,max=1)
376
+ #Discard i=j in the summation in rank_pos
377
+ fg_relations[ii]=0
378
+
379
+ #x_ij s as score differences with bgs
380
+ bg_relations=relevant_bg_logits-fg_logits[ii]
381
+ #Apply piecewise linear function and determine relations with bgs
382
+ bg_relations=torch.clamp(bg_relations/(2*delta)+0.5,min=0,max=1)
383
+
384
+ #Compute the rank of the example within fgs and number of bgs with larger scores
385
+ rank_pos=1+torch.sum(fg_relations)
386
+ FP_num=torch.sum(bg_relations)
387
+ #Store the total since it is normalizer also for aLRP Regression error
388
+ rank[ii]=rank_pos+FP_num
389
+
390
+ #Compute precision for this example
391
+ current_prec=rank_pos/rank[ii]
392
+
393
+ #Compute interpolated AP and store gradients for relevant bg examples
394
+ if (max_prec<=current_prec):
395
+ max_prec=current_prec
396
+ relevant_bg_grad += (bg_relations/rank[ii])
397
+ else:
398
+ relevant_bg_grad += (bg_relations/rank[ii])*(((1-max_prec)/(1-current_prec)))
399
+
400
+ #Store fg gradients
401
+ fg_grad[ii]=-(1-max_prec)
402
+ prec[ii]=max_prec
403
+
404
+ #aLRP with grad formulation fg gradient
405
+ classification_grads[fg_labels]= fg_grad
406
+ #aLRP with grad formulation bg gradient
407
+ classification_grads[relevant_bg_labels]= relevant_bg_grad
408
+
409
+ classification_grads /= fg_num
410
+
411
+ cls_loss=1-prec.mean()
412
+ ctx.save_for_backward(classification_grads)
413
+
414
+ return cls_loss
415
+
416
+ @staticmethod
417
+ def backward(ctx, out_grad1):
418
+ g1, =ctx.saved_tensors
419
+ return g1*out_grad1, None, None
420
+
421
+
422
+ class ComputeLoss:
423
+ # Compute losses
424
+ def __init__(self, model, autobalance=False):
425
+ super(ComputeLoss, self).__init__()
426
+ device = next(model.parameters()).device # get model device
427
+ h = model.hyp # hyperparameters
428
+
429
+ # Define criteria
430
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
431
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
432
+
433
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
434
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
435
+
436
+ # Focal loss
437
+ g = h['fl_gamma'] # focal loss gamma
438
+ if g > 0:
439
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
440
+
441
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
442
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
443
+ #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.1, .05]) # P3-P7
444
+ #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.5, 0.4, .1]) # P3-P7
445
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
446
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
447
+ for k in 'na', 'nc', 'nl', 'anchors':
448
+ setattr(self, k, getattr(det, k))
449
+
450
+ def __call__(self, p, targets): # predictions, targets, model
451
+ device = targets.device
452
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
453
+ tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
454
+
455
+ # Losses
456
+ for i, pi in enumerate(p): # layer index, layer predictions
457
+ b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
458
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
459
+
460
+ n = b.shape[0] # number of targets
461
+ if n:
462
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
463
+
464
+ # Regression
465
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
466
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
467
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
468
+ iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
469
+ lbox += (1.0 - iou).mean() # iou loss
470
+
471
+ # Objectness
472
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
473
+
474
+ # Classification
475
+ if self.nc > 1: # cls loss (only if multiple classes)
476
+ t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
477
+ t[range(n), tcls[i]] = self.cp
478
+ #t[t==self.cp] = iou.detach().clamp(0).type(t.dtype)
479
+ lcls += self.BCEcls(ps[:, 5:], t) # BCE
480
+
481
+ # Append targets to text file
482
+ # with open('targets.txt', 'a') as file:
483
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
484
+
485
+ obji = self.BCEobj(pi[..., 4], tobj)
486
+ lobj += obji * self.balance[i] # obj loss
487
+ if self.autobalance:
488
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
489
+
490
+ if self.autobalance:
491
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
492
+ lbox *= self.hyp['box']
493
+ lobj *= self.hyp['obj']
494
+ lcls *= self.hyp['cls']
495
+ bs = tobj.shape[0] # batch size
496
+
497
+ loss = lbox + lobj + lcls
498
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
499
+
500
+ def build_targets(self, p, targets):
501
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
502
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
503
+ tcls, tbox, indices, anch = [], [], [], []
504
+ gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain
505
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
506
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
507
+
508
+ g = 0.5 # bias
509
+ off = torch.tensor([[0, 0],
510
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
511
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
512
+ ], device=targets.device).float() * g # offsets
513
+
514
+ for i in range(self.nl):
515
+ anchors = self.anchors[i]
516
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
517
+
518
+ # Match targets to anchors
519
+ t = targets * gain
520
+ if nt:
521
+ # Matches
522
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
523
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
524
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
525
+ t = t[j] # filter
526
+
527
+ # Offsets
528
+ gxy = t[:, 2:4] # grid xy
529
+ gxi = gain[[2, 3]] - gxy # inverse
530
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
531
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
532
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
533
+ t = t.repeat((5, 1, 1))[j]
534
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
535
+ else:
536
+ t = targets[0]
537
+ offsets = 0
538
+
539
+ # Define
540
+ b, c = t[:, :2].long().T # image, class
541
+ gxy = t[:, 2:4] # grid xy
542
+ gwh = t[:, 4:6] # grid wh
543
+ gij = (gxy - offsets).long()
544
+ gi, gj = gij.T # grid xy indices
545
+
546
+ # Append
547
+ a = t[:, 6].long() # anchor indices
548
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
549
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
550
+ anch.append(anchors[a]) # anchors
551
+ tcls.append(c) # class
552
+
553
+ return tcls, tbox, indices, anch
554
+
555
+
556
+ class ComputeLossOTA:
557
+ # Compute losses
558
+ def __init__(self, model, autobalance=False):
559
+ super(ComputeLossOTA, self).__init__()
560
+ device = next(model.parameters()).device # get model device
561
+ h = model.hyp # hyperparameters
562
+
563
+ # Define criteria
564
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
565
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
566
+
567
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
568
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
569
+
570
+ # Focal loss
571
+ g = h['fl_gamma'] # focal loss gamma
572
+ if g > 0:
573
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
574
+
575
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
576
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
577
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
578
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
579
+ for k in 'na', 'nc', 'nl', 'anchors', 'stride':
580
+ setattr(self, k, getattr(det, k))
581
+
582
+ def __call__(self, p, targets, imgs): # predictions, targets, model
583
+ device = targets.device
584
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
585
+ bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs)
586
+ pre_gen_gains = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p]
587
+
588
+
589
+ # Losses
590
+ for i, pi in enumerate(p): # layer index, layer predictions
591
+ b, a, gj, gi = bs[i], as_[i], gjs[i], gis[i] # image, anchor, gridy, gridx
592
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
593
+
594
+ n = b.shape[0] # number of targets
595
+ if n:
596
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
597
+
598
+ # Regression
599
+ grid = torch.stack([gi, gj], dim=1)
600
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
601
+ #pxy = ps[:, :2].sigmoid() * 3. - 1.
602
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
603
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
604
+ selected_tbox = targets[i][:, 2:6] * pre_gen_gains[i]
605
+ selected_tbox[:, :2] -= grid
606
+ iou = bbox_iou(pbox.T, selected_tbox, x1y1x2y2=False, CIoU=True) # iou(prediction, target)
607
+ lbox += (1.0 - iou).mean() # iou loss
608
+
609
+ # Objectness
610
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
611
+
612
+ # Classification
613
+ selected_tcls = targets[i][:, 1].long()
614
+ if self.nc > 1: # cls loss (only if multiple classes)
615
+ t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
616
+ t[range(n), selected_tcls] = self.cp
617
+ lcls += self.BCEcls(ps[:, 5:], t) # BCE
618
+
619
+ # Append targets to text file
620
+ # with open('targets.txt', 'a') as file:
621
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
622
+
623
+ obji = self.BCEobj(pi[..., 4], tobj)
624
+ lobj += obji * self.balance[i] # obj loss
625
+ if self.autobalance:
626
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
627
+
628
+ if self.autobalance:
629
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
630
+ lbox *= self.hyp['box']
631
+ lobj *= self.hyp['obj']
632
+ lcls *= self.hyp['cls']
633
+ bs = tobj.shape[0] # batch size
634
+
635
+ loss = lbox + lobj + lcls
636
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
637
+
638
+ def build_targets(self, p, targets, imgs):
639
+
640
+ #indices, anch = self.find_positive(p, targets)
641
+ indices, anch = self.find_3_positive(p, targets)
642
+ #indices, anch = self.find_4_positive(p, targets)
643
+ #indices, anch = self.find_5_positive(p, targets)
644
+ #indices, anch = self.find_9_positive(p, targets)
645
+ device = torch.device(targets.device)
646
+ matching_bs = [[] for pp in p]
647
+ matching_as = [[] for pp in p]
648
+ matching_gjs = [[] for pp in p]
649
+ matching_gis = [[] for pp in p]
650
+ matching_targets = [[] for pp in p]
651
+ matching_anchs = [[] for pp in p]
652
+
653
+ nl = len(p)
654
+
655
+ for batch_idx in range(p[0].shape[0]):
656
+
657
+ b_idx = targets[:, 0]==batch_idx
658
+ this_target = targets[b_idx]
659
+ if this_target.shape[0] == 0:
660
+ continue
661
+
662
+ txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]
663
+ txyxy = xywh2xyxy(txywh)
664
+
665
+ pxyxys = []
666
+ p_cls = []
667
+ p_obj = []
668
+ from_which_layer = []
669
+ all_b = []
670
+ all_a = []
671
+ all_gj = []
672
+ all_gi = []
673
+ all_anch = []
674
+
675
+ for i, pi in enumerate(p):
676
+
677
+ b, a, gj, gi = indices[i]
678
+ idx = (b == batch_idx)
679
+ b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx]
680
+ all_b.append(b)
681
+ all_a.append(a)
682
+ all_gj.append(gj)
683
+ all_gi.append(gi)
684
+ all_anch.append(anch[i][idx])
685
+ from_which_layer.append((torch.ones(size=(len(b),)) * i).to(device))
686
+
687
+ fg_pred = pi[b, a, gj, gi]
688
+ p_obj.append(fg_pred[:, 4:5])
689
+ p_cls.append(fg_pred[:, 5:])
690
+
691
+ grid = torch.stack([gi, gj], dim=1)
692
+ pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.
693
+ #pxy = (fg_pred[:, :2].sigmoid() * 3. - 1. + grid) * self.stride[i]
694
+ pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.
695
+ pxywh = torch.cat([pxy, pwh], dim=-1)
696
+ pxyxy = xywh2xyxy(pxywh)
697
+ pxyxys.append(pxyxy)
698
+
699
+ pxyxys = torch.cat(pxyxys, dim=0)
700
+ if pxyxys.shape[0] == 0:
701
+ continue
702
+ p_obj = torch.cat(p_obj, dim=0)
703
+ p_cls = torch.cat(p_cls, dim=0)
704
+ from_which_layer = torch.cat(from_which_layer, dim=0)
705
+ all_b = torch.cat(all_b, dim=0)
706
+ all_a = torch.cat(all_a, dim=0)
707
+ all_gj = torch.cat(all_gj, dim=0)
708
+ all_gi = torch.cat(all_gi, dim=0)
709
+ all_anch = torch.cat(all_anch, dim=0)
710
+
711
+ pair_wise_iou = box_iou(txyxy, pxyxys)
712
+
713
+ pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)
714
+
715
+ top_k, _ = torch.topk(pair_wise_iou, min(10, pair_wise_iou.shape[1]), dim=1)
716
+ dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)
717
+
718
+ gt_cls_per_image = (
719
+ F.one_hot(this_target[:, 1].to(torch.int64), self.nc)
720
+ .float()
721
+ .unsqueeze(1)
722
+ .repeat(1, pxyxys.shape[0], 1)
723
+ )
724
+
725
+ num_gt = this_target.shape[0]
726
+ cls_preds_ = (
727
+ p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
728
+ * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
729
+ )
730
+
731
+ y = cls_preds_.sqrt_()
732
+ pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
733
+ torch.log(y/(1-y)) , gt_cls_per_image, reduction="none"
734
+ ).sum(-1)
735
+ del cls_preds_
736
+
737
+ cost = (
738
+ pair_wise_cls_loss
739
+ + 3.0 * pair_wise_iou_loss
740
+ )
741
+
742
+ matching_matrix = torch.zeros_like(cost, device=device)
743
+
744
+ for gt_idx in range(num_gt):
745
+ _, pos_idx = torch.topk(
746
+ cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
747
+ )
748
+ matching_matrix[gt_idx][pos_idx] = 1.0
749
+
750
+ del top_k, dynamic_ks
751
+ anchor_matching_gt = matching_matrix.sum(0)
752
+ if (anchor_matching_gt > 1).sum() > 0:
753
+ _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
754
+ matching_matrix[:, anchor_matching_gt > 1] *= 0.0
755
+ matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
756
+ fg_mask_inboxes = (matching_matrix.sum(0) > 0.0).to(device)
757
+ matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
758
+
759
+ from_which_layer = from_which_layer[fg_mask_inboxes]
760
+ all_b = all_b[fg_mask_inboxes]
761
+ all_a = all_a[fg_mask_inboxes]
762
+ all_gj = all_gj[fg_mask_inboxes]
763
+ all_gi = all_gi[fg_mask_inboxes]
764
+ all_anch = all_anch[fg_mask_inboxes]
765
+
766
+ this_target = this_target[matched_gt_inds]
767
+
768
+ for i in range(nl):
769
+ layer_idx = from_which_layer == i
770
+ matching_bs[i].append(all_b[layer_idx])
771
+ matching_as[i].append(all_a[layer_idx])
772
+ matching_gjs[i].append(all_gj[layer_idx])
773
+ matching_gis[i].append(all_gi[layer_idx])
774
+ matching_targets[i].append(this_target[layer_idx])
775
+ matching_anchs[i].append(all_anch[layer_idx])
776
+
777
+ for i in range(nl):
778
+ if matching_targets[i] != []:
779
+ matching_bs[i] = torch.cat(matching_bs[i], dim=0)
780
+ matching_as[i] = torch.cat(matching_as[i], dim=0)
781
+ matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)
782
+ matching_gis[i] = torch.cat(matching_gis[i], dim=0)
783
+ matching_targets[i] = torch.cat(matching_targets[i], dim=0)
784
+ matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)
785
+ else:
786
+ matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
787
+ matching_as[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
788
+ matching_gjs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
789
+ matching_gis[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
790
+ matching_targets[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
791
+ matching_anchs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
792
+
793
+ return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs
794
+
795
+ def find_3_positive(self, p, targets):
796
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
797
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
798
+ indices, anch = [], []
799
+ gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain
800
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
801
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
802
+
803
+ g = 0.5 # bias
804
+ off = torch.tensor([[0, 0],
805
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
806
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
807
+ ], device=targets.device).float() * g # offsets
808
+
809
+ for i in range(self.nl):
810
+ anchors = self.anchors[i]
811
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
812
+
813
+ # Match targets to anchors
814
+ t = targets * gain
815
+ if nt:
816
+ # Matches
817
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
818
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
819
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
820
+ t = t[j] # filter
821
+
822
+ # Offsets
823
+ gxy = t[:, 2:4] # grid xy
824
+ gxi = gain[[2, 3]] - gxy # inverse
825
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
826
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
827
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
828
+ t = t.repeat((5, 1, 1))[j]
829
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
830
+ else:
831
+ t = targets[0]
832
+ offsets = 0
833
+
834
+ # Define
835
+ b, c = t[:, :2].long().T # image, class
836
+ gxy = t[:, 2:4] # grid xy
837
+ gwh = t[:, 4:6] # grid wh
838
+ gij = (gxy - offsets).long()
839
+ gi, gj = gij.T # grid xy indices
840
+
841
+ # Append
842
+ a = t[:, 6].long() # anchor indices
843
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
844
+ anch.append(anchors[a]) # anchors
845
+
846
+ return indices, anch
847
+
848
+
849
+ class ComputeLossBinOTA:
850
+ # Compute losses
851
+ def __init__(self, model, autobalance=False):
852
+ super(ComputeLossBinOTA, self).__init__()
853
+ device = next(model.parameters()).device # get model device
854
+ h = model.hyp # hyperparameters
855
+
856
+ # Define criteria
857
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
858
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
859
+ #MSEangle = nn.MSELoss().to(device)
860
+
861
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
862
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
863
+
864
+ # Focal loss
865
+ g = h['fl_gamma'] # focal loss gamma
866
+ if g > 0:
867
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
868
+
869
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
870
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
871
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
872
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
873
+ for k in 'na', 'nc', 'nl', 'anchors', 'stride', 'bin_count':
874
+ setattr(self, k, getattr(det, k))
875
+
876
+ #xy_bin_sigmoid = SigmoidBin(bin_count=11, min=-0.5, max=1.5, use_loss_regression=False).to(device)
877
+ wh_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0, use_loss_regression=False).to(device)
878
+ #angle_bin_sigmoid = SigmoidBin(bin_count=31, min=-1.1, max=1.1, use_loss_regression=False).to(device)
879
+ self.wh_bin_sigmoid = wh_bin_sigmoid
880
+
881
+ def __call__(self, p, targets, imgs): # predictions, targets, model
882
+ device = targets.device
883
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
884
+ bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs)
885
+ pre_gen_gains = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p]
886
+
887
+
888
+ # Losses
889
+ for i, pi in enumerate(p): # layer index, layer predictions
890
+ b, a, gj, gi = bs[i], as_[i], gjs[i], gis[i] # image, anchor, gridy, gridx
891
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
892
+
893
+ obj_idx = self.wh_bin_sigmoid.get_length()*2 + 2 # x,y, w-bce, h-bce # xy_bin_sigmoid.get_length()*2
894
+
895
+ n = b.shape[0] # number of targets
896
+ if n:
897
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
898
+
899
+ # Regression
900
+ grid = torch.stack([gi, gj], dim=1)
901
+ selected_tbox = targets[i][:, 2:6] * pre_gen_gains[i]
902
+ selected_tbox[:, :2] -= grid
903
+
904
+ #pxy = ps[:, :2].sigmoid() * 2. - 0.5
905
+ ##pxy = ps[:, :2].sigmoid() * 3. - 1.
906
+ #pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
907
+ #pbox = torch.cat((pxy, pwh), 1) # predicted box
908
+
909
+ #x_loss, px = xy_bin_sigmoid.training_loss(ps[..., 0:12], tbox[i][..., 0])
910
+ #y_loss, py = xy_bin_sigmoid.training_loss(ps[..., 12:24], tbox[i][..., 1])
911
+ w_loss, pw = self.wh_bin_sigmoid.training_loss(ps[..., 2:(3+self.bin_count)], selected_tbox[..., 2] / anchors[i][..., 0])
912
+ h_loss, ph = self.wh_bin_sigmoid.training_loss(ps[..., (3+self.bin_count):obj_idx], selected_tbox[..., 3] / anchors[i][..., 1])
913
+
914
+ pw *= anchors[i][..., 0]
915
+ ph *= anchors[i][..., 1]
916
+
917
+ px = ps[:, 0].sigmoid() * 2. - 0.5
918
+ py = ps[:, 1].sigmoid() * 2. - 0.5
919
+
920
+ lbox += w_loss + h_loss # + x_loss + y_loss
921
+
922
+ #print(f"\n px = {px.shape}, py = {py.shape}, pw = {pw.shape}, ph = {ph.shape} \n")
923
+
924
+ pbox = torch.cat((px.unsqueeze(1), py.unsqueeze(1), pw.unsqueeze(1), ph.unsqueeze(1)), 1).to(device) # predicted box
925
+
926
+
927
+
928
+
929
+ iou = bbox_iou(pbox.T, selected_tbox, x1y1x2y2=False, CIoU=True) # iou(prediction, target)
930
+ lbox += (1.0 - iou).mean() # iou loss
931
+
932
+ # Objectness
933
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
934
+
935
+ # Classification
936
+ selected_tcls = targets[i][:, 1].long()
937
+ if self.nc > 1: # cls loss (only if multiple classes)
938
+ t = torch.full_like(ps[:, (1+obj_idx):], self.cn, device=device) # targets
939
+ t[range(n), selected_tcls] = self.cp
940
+ lcls += self.BCEcls(ps[:, (1+obj_idx):], t) # BCE
941
+
942
+ # Append targets to text file
943
+ # with open('targets.txt', 'a') as file:
944
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
945
+
946
+ obji = self.BCEobj(pi[..., obj_idx], tobj)
947
+ lobj += obji * self.balance[i] # obj loss
948
+ if self.autobalance:
949
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
950
+
951
+ if self.autobalance:
952
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
953
+ lbox *= self.hyp['box']
954
+ lobj *= self.hyp['obj']
955
+ lcls *= self.hyp['cls']
956
+ bs = tobj.shape[0] # batch size
957
+
958
+ loss = lbox + lobj + lcls
959
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
960
+
961
+ def build_targets(self, p, targets, imgs):
962
+
963
+ #indices, anch = self.find_positive(p, targets)
964
+ indices, anch = self.find_3_positive(p, targets)
965
+ #indices, anch = self.find_4_positive(p, targets)
966
+ #indices, anch = self.find_5_positive(p, targets)
967
+ #indices, anch = self.find_9_positive(p, targets)
968
+
969
+ matching_bs = [[] for pp in p]
970
+ matching_as = [[] for pp in p]
971
+ matching_gjs = [[] for pp in p]
972
+ matching_gis = [[] for pp in p]
973
+ matching_targets = [[] for pp in p]
974
+ matching_anchs = [[] for pp in p]
975
+
976
+ nl = len(p)
977
+
978
+ for batch_idx in range(p[0].shape[0]):
979
+
980
+ b_idx = targets[:, 0]==batch_idx
981
+ this_target = targets[b_idx]
982
+ if this_target.shape[0] == 0:
983
+ continue
984
+
985
+ txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]
986
+ txyxy = xywh2xyxy(txywh)
987
+
988
+ pxyxys = []
989
+ p_cls = []
990
+ p_obj = []
991
+ from_which_layer = []
992
+ all_b = []
993
+ all_a = []
994
+ all_gj = []
995
+ all_gi = []
996
+ all_anch = []
997
+
998
+ for i, pi in enumerate(p):
999
+
1000
+ obj_idx = self.wh_bin_sigmoid.get_length()*2 + 2
1001
+
1002
+ b, a, gj, gi = indices[i]
1003
+ idx = (b == batch_idx)
1004
+ b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx]
1005
+ all_b.append(b)
1006
+ all_a.append(a)
1007
+ all_gj.append(gj)
1008
+ all_gi.append(gi)
1009
+ all_anch.append(anch[i][idx])
1010
+ from_which_layer.append(torch.ones(size=(len(b),)) * i)
1011
+
1012
+ fg_pred = pi[b, a, gj, gi]
1013
+ p_obj.append(fg_pred[:, obj_idx:(obj_idx+1)])
1014
+ p_cls.append(fg_pred[:, (obj_idx+1):])
1015
+
1016
+ grid = torch.stack([gi, gj], dim=1)
1017
+ pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.
1018
+ #pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.
1019
+ pw = self.wh_bin_sigmoid.forward(fg_pred[..., 2:(3+self.bin_count)].sigmoid()) * anch[i][idx][:, 0] * self.stride[i]
1020
+ ph = self.wh_bin_sigmoid.forward(fg_pred[..., (3+self.bin_count):obj_idx].sigmoid()) * anch[i][idx][:, 1] * self.stride[i]
1021
+
1022
+ pxywh = torch.cat([pxy, pw.unsqueeze(1), ph.unsqueeze(1)], dim=-1)
1023
+ pxyxy = xywh2xyxy(pxywh)
1024
+ pxyxys.append(pxyxy)
1025
+
1026
+ pxyxys = torch.cat(pxyxys, dim=0)
1027
+ if pxyxys.shape[0] == 0:
1028
+ continue
1029
+ p_obj = torch.cat(p_obj, dim=0)
1030
+ p_cls = torch.cat(p_cls, dim=0)
1031
+ from_which_layer = torch.cat(from_which_layer, dim=0)
1032
+ all_b = torch.cat(all_b, dim=0)
1033
+ all_a = torch.cat(all_a, dim=0)
1034
+ all_gj = torch.cat(all_gj, dim=0)
1035
+ all_gi = torch.cat(all_gi, dim=0)
1036
+ all_anch = torch.cat(all_anch, dim=0)
1037
+
1038
+ pair_wise_iou = box_iou(txyxy, pxyxys)
1039
+
1040
+ pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)
1041
+
1042
+ top_k, _ = torch.topk(pair_wise_iou, min(10, pair_wise_iou.shape[1]), dim=1)
1043
+ dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)
1044
+
1045
+ gt_cls_per_image = (
1046
+ F.one_hot(this_target[:, 1].to(torch.int64), self.nc)
1047
+ .float()
1048
+ .unsqueeze(1)
1049
+ .repeat(1, pxyxys.shape[0], 1)
1050
+ )
1051
+
1052
+ num_gt = this_target.shape[0]
1053
+ cls_preds_ = (
1054
+ p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1055
+ * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1056
+ )
1057
+
1058
+ y = cls_preds_.sqrt_()
1059
+ pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
1060
+ torch.log(y/(1-y)) , gt_cls_per_image, reduction="none"
1061
+ ).sum(-1)
1062
+ del cls_preds_
1063
+
1064
+ cost = (
1065
+ pair_wise_cls_loss
1066
+ + 3.0 * pair_wise_iou_loss
1067
+ )
1068
+
1069
+ matching_matrix = torch.zeros_like(cost)
1070
+
1071
+ for gt_idx in range(num_gt):
1072
+ _, pos_idx = torch.topk(
1073
+ cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
1074
+ )
1075
+ matching_matrix[gt_idx][pos_idx] = 1.0
1076
+
1077
+ del top_k, dynamic_ks
1078
+ anchor_matching_gt = matching_matrix.sum(0)
1079
+ if (anchor_matching_gt > 1).sum() > 0:
1080
+ _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
1081
+ matching_matrix[:, anchor_matching_gt > 1] *= 0.0
1082
+ matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
1083
+ fg_mask_inboxes = matching_matrix.sum(0) > 0.0
1084
+ matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
1085
+
1086
+ from_which_layer = from_which_layer[fg_mask_inboxes]
1087
+ all_b = all_b[fg_mask_inboxes]
1088
+ all_a = all_a[fg_mask_inboxes]
1089
+ all_gj = all_gj[fg_mask_inboxes]
1090
+ all_gi = all_gi[fg_mask_inboxes]
1091
+ all_anch = all_anch[fg_mask_inboxes]
1092
+
1093
+ this_target = this_target[matched_gt_inds]
1094
+
1095
+ for i in range(nl):
1096
+ layer_idx = from_which_layer == i
1097
+ matching_bs[i].append(all_b[layer_idx])
1098
+ matching_as[i].append(all_a[layer_idx])
1099
+ matching_gjs[i].append(all_gj[layer_idx])
1100
+ matching_gis[i].append(all_gi[layer_idx])
1101
+ matching_targets[i].append(this_target[layer_idx])
1102
+ matching_anchs[i].append(all_anch[layer_idx])
1103
+
1104
+ for i in range(nl):
1105
+ if matching_targets[i] != []:
1106
+ matching_bs[i] = torch.cat(matching_bs[i], dim=0)
1107
+ matching_as[i] = torch.cat(matching_as[i], dim=0)
1108
+ matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)
1109
+ matching_gis[i] = torch.cat(matching_gis[i], dim=0)
1110
+ matching_targets[i] = torch.cat(matching_targets[i], dim=0)
1111
+ matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)
1112
+ else:
1113
+ matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1114
+ matching_as[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1115
+ matching_gjs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1116
+ matching_gis[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1117
+ matching_targets[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1118
+ matching_anchs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1119
+
1120
+ return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs
1121
+
1122
+ def find_3_positive(self, p, targets):
1123
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
1124
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
1125
+ indices, anch = [], []
1126
+ gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain
1127
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
1128
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
1129
+
1130
+ g = 0.5 # bias
1131
+ off = torch.tensor([[0, 0],
1132
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
1133
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
1134
+ ], device=targets.device).float() * g # offsets
1135
+
1136
+ for i in range(self.nl):
1137
+ anchors = self.anchors[i]
1138
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
1139
+
1140
+ # Match targets to anchors
1141
+ t = targets * gain
1142
+ if nt:
1143
+ # Matches
1144
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
1145
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
1146
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
1147
+ t = t[j] # filter
1148
+
1149
+ # Offsets
1150
+ gxy = t[:, 2:4] # grid xy
1151
+ gxi = gain[[2, 3]] - gxy # inverse
1152
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
1153
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
1154
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
1155
+ t = t.repeat((5, 1, 1))[j]
1156
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
1157
+ else:
1158
+ t = targets[0]
1159
+ offsets = 0
1160
+
1161
+ # Define
1162
+ b, c = t[:, :2].long().T # image, class
1163
+ gxy = t[:, 2:4] # grid xy
1164
+ gwh = t[:, 4:6] # grid wh
1165
+ gij = (gxy - offsets).long()
1166
+ gi, gj = gij.T # grid xy indices
1167
+
1168
+ # Append
1169
+ a = t[:, 6].long() # anchor indices
1170
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
1171
+ anch.append(anchors[a]) # anchors
1172
+
1173
+ return indices, anch
1174
+
1175
+
1176
+ class ComputeLossAuxOTA:
1177
+ # Compute losses
1178
+ def __init__(self, model, autobalance=False):
1179
+ super(ComputeLossAuxOTA, self).__init__()
1180
+ device = next(model.parameters()).device # get model device
1181
+ h = model.hyp # hyperparameters
1182
+
1183
+ # Define criteria
1184
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
1185
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
1186
+
1187
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
1188
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
1189
+
1190
+ # Focal loss
1191
+ g = h['fl_gamma'] # focal loss gamma
1192
+ if g > 0:
1193
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
1194
+
1195
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
1196
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
1197
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
1198
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
1199
+ for k in 'na', 'nc', 'nl', 'anchors', 'stride':
1200
+ setattr(self, k, getattr(det, k))
1201
+
1202
+ def __call__(self, p, targets, imgs): # predictions, targets, model
1203
+ device = targets.device
1204
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
1205
+ bs_aux, as_aux_, gjs_aux, gis_aux, targets_aux, anchors_aux = self.build_targets2(p[:self.nl], targets, imgs)
1206
+ bs, as_, gjs, gis, targets, anchors = self.build_targets(p[:self.nl], targets, imgs)
1207
+ pre_gen_gains_aux = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p[:self.nl]]
1208
+ pre_gen_gains = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p[:self.nl]]
1209
+
1210
+
1211
+ # Losses
1212
+ for i in range(self.nl): # layer index, layer predictions
1213
+ pi = p[i]
1214
+ pi_aux = p[i+self.nl]
1215
+ b, a, gj, gi = bs[i], as_[i], gjs[i], gis[i] # image, anchor, gridy, gridx
1216
+ b_aux, a_aux, gj_aux, gi_aux = bs_aux[i], as_aux_[i], gjs_aux[i], gis_aux[i] # image, anchor, gridy, gridx
1217
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
1218
+ tobj_aux = torch.zeros_like(pi_aux[..., 0], device=device) # target obj
1219
+
1220
+ n = b.shape[0] # number of targets
1221
+ if n:
1222
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
1223
+
1224
+ # Regression
1225
+ grid = torch.stack([gi, gj], dim=1)
1226
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
1227
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
1228
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
1229
+ selected_tbox = targets[i][:, 2:6] * pre_gen_gains[i]
1230
+ selected_tbox[:, :2] -= grid
1231
+ iou = bbox_iou(pbox.T, selected_tbox, x1y1x2y2=False, CIoU=True) # iou(prediction, target)
1232
+ lbox += (1.0 - iou).mean() # iou loss
1233
+
1234
+ # Objectness
1235
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
1236
+
1237
+ # Classification
1238
+ selected_tcls = targets[i][:, 1].long()
1239
+ if self.nc > 1: # cls loss (only if multiple classes)
1240
+ t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
1241
+ t[range(n), selected_tcls] = self.cp
1242
+ lcls += self.BCEcls(ps[:, 5:], t) # BCE
1243
+
1244
+ # Append targets to text file
1245
+ # with open('targets.txt', 'a') as file:
1246
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
1247
+
1248
+ n_aux = b_aux.shape[0] # number of targets
1249
+ if n_aux:
1250
+ ps_aux = pi_aux[b_aux, a_aux, gj_aux, gi_aux] # prediction subset corresponding to targets
1251
+ grid_aux = torch.stack([gi_aux, gj_aux], dim=1)
1252
+ pxy_aux = ps_aux[:, :2].sigmoid() * 2. - 0.5
1253
+ #pxy_aux = ps_aux[:, :2].sigmoid() * 3. - 1.
1254
+ pwh_aux = (ps_aux[:, 2:4].sigmoid() * 2) ** 2 * anchors_aux[i]
1255
+ pbox_aux = torch.cat((pxy_aux, pwh_aux), 1) # predicted box
1256
+ selected_tbox_aux = targets_aux[i][:, 2:6] * pre_gen_gains_aux[i]
1257
+ selected_tbox_aux[:, :2] -= grid_aux
1258
+ iou_aux = bbox_iou(pbox_aux.T, selected_tbox_aux, x1y1x2y2=False, CIoU=True) # iou(prediction, target)
1259
+ lbox += 0.25 * (1.0 - iou_aux).mean() # iou loss
1260
+
1261
+ # Objectness
1262
+ tobj_aux[b_aux, a_aux, gj_aux, gi_aux] = (1.0 - self.gr) + self.gr * iou_aux.detach().clamp(0).type(tobj_aux.dtype) # iou ratio
1263
+
1264
+ # Classification
1265
+ selected_tcls_aux = targets_aux[i][:, 1].long()
1266
+ if self.nc > 1: # cls loss (only if multiple classes)
1267
+ t_aux = torch.full_like(ps_aux[:, 5:], self.cn, device=device) # targets
1268
+ t_aux[range(n_aux), selected_tcls_aux] = self.cp
1269
+ lcls += 0.25 * self.BCEcls(ps_aux[:, 5:], t_aux) # BCE
1270
+
1271
+ obji = self.BCEobj(pi[..., 4], tobj)
1272
+ obji_aux = self.BCEobj(pi_aux[..., 4], tobj_aux)
1273
+ lobj += obji * self.balance[i] + 0.25 * obji_aux * self.balance[i] # obj loss
1274
+ if self.autobalance:
1275
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
1276
+
1277
+ if self.autobalance:
1278
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
1279
+ lbox *= self.hyp['box']
1280
+ lobj *= self.hyp['obj']
1281
+ lcls *= self.hyp['cls']
1282
+ bs = tobj.shape[0] # batch size
1283
+
1284
+ loss = lbox + lobj + lcls
1285
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
1286
+
1287
+ def build_targets(self, p, targets, imgs):
1288
+
1289
+ indices, anch = self.find_3_positive(p, targets)
1290
+
1291
+ matching_bs = [[] for pp in p]
1292
+ matching_as = [[] for pp in p]
1293
+ matching_gjs = [[] for pp in p]
1294
+ matching_gis = [[] for pp in p]
1295
+ matching_targets = [[] for pp in p]
1296
+ matching_anchs = [[] for pp in p]
1297
+
1298
+ nl = len(p)
1299
+
1300
+ for batch_idx in range(p[0].shape[0]):
1301
+
1302
+ b_idx = targets[:, 0]==batch_idx
1303
+ this_target = targets[b_idx]
1304
+ if this_target.shape[0] == 0:
1305
+ continue
1306
+
1307
+ txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]
1308
+ txyxy = xywh2xyxy(txywh)
1309
+
1310
+ pxyxys = []
1311
+ p_cls = []
1312
+ p_obj = []
1313
+ from_which_layer = []
1314
+ all_b = []
1315
+ all_a = []
1316
+ all_gj = []
1317
+ all_gi = []
1318
+ all_anch = []
1319
+
1320
+ for i, pi in enumerate(p):
1321
+
1322
+ b, a, gj, gi = indices[i]
1323
+ idx = (b == batch_idx)
1324
+ b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx]
1325
+ all_b.append(b)
1326
+ all_a.append(a)
1327
+ all_gj.append(gj)
1328
+ all_gi.append(gi)
1329
+ all_anch.append(anch[i][idx])
1330
+ from_which_layer.append(torch.ones(size=(len(b),)) * i)
1331
+
1332
+ fg_pred = pi[b, a, gj, gi]
1333
+ p_obj.append(fg_pred[:, 4:5])
1334
+ p_cls.append(fg_pred[:, 5:])
1335
+
1336
+ grid = torch.stack([gi, gj], dim=1)
1337
+ pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.
1338
+ #pxy = (fg_pred[:, :2].sigmoid() * 3. - 1. + grid) * self.stride[i]
1339
+ pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.
1340
+ pxywh = torch.cat([pxy, pwh], dim=-1)
1341
+ pxyxy = xywh2xyxy(pxywh)
1342
+ pxyxys.append(pxyxy)
1343
+
1344
+ pxyxys = torch.cat(pxyxys, dim=0)
1345
+ if pxyxys.shape[0] == 0:
1346
+ continue
1347
+ p_obj = torch.cat(p_obj, dim=0)
1348
+ p_cls = torch.cat(p_cls, dim=0)
1349
+ from_which_layer = torch.cat(from_which_layer, dim=0)
1350
+ all_b = torch.cat(all_b, dim=0)
1351
+ all_a = torch.cat(all_a, dim=0)
1352
+ all_gj = torch.cat(all_gj, dim=0)
1353
+ all_gi = torch.cat(all_gi, dim=0)
1354
+ all_anch = torch.cat(all_anch, dim=0)
1355
+
1356
+ pair_wise_iou = box_iou(txyxy, pxyxys)
1357
+
1358
+ pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)
1359
+
1360
+ top_k, _ = torch.topk(pair_wise_iou, min(20, pair_wise_iou.shape[1]), dim=1)
1361
+ dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)
1362
+
1363
+ gt_cls_per_image = (
1364
+ F.one_hot(this_target[:, 1].to(torch.int64), self.nc)
1365
+ .float()
1366
+ .unsqueeze(1)
1367
+ .repeat(1, pxyxys.shape[0], 1)
1368
+ )
1369
+
1370
+ num_gt = this_target.shape[0]
1371
+ cls_preds_ = (
1372
+ p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1373
+ * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1374
+ )
1375
+
1376
+ y = cls_preds_.sqrt_()
1377
+ pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
1378
+ torch.log(y/(1-y)) , gt_cls_per_image, reduction="none"
1379
+ ).sum(-1)
1380
+ del cls_preds_
1381
+
1382
+ cost = (
1383
+ pair_wise_cls_loss
1384
+ + 3.0 * pair_wise_iou_loss
1385
+ )
1386
+
1387
+ matching_matrix = torch.zeros_like(cost)
1388
+
1389
+ for gt_idx in range(num_gt):
1390
+ _, pos_idx = torch.topk(
1391
+ cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
1392
+ )
1393
+ matching_matrix[gt_idx][pos_idx] = 1.0
1394
+
1395
+ del top_k, dynamic_ks
1396
+ anchor_matching_gt = matching_matrix.sum(0)
1397
+ if (anchor_matching_gt > 1).sum() > 0:
1398
+ _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
1399
+ matching_matrix[:, anchor_matching_gt > 1] *= 0.0
1400
+ matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
1401
+ fg_mask_inboxes = matching_matrix.sum(0) > 0.0
1402
+ matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
1403
+
1404
+ from_which_layer = from_which_layer[fg_mask_inboxes]
1405
+ all_b = all_b[fg_mask_inboxes]
1406
+ all_a = all_a[fg_mask_inboxes]
1407
+ all_gj = all_gj[fg_mask_inboxes]
1408
+ all_gi = all_gi[fg_mask_inboxes]
1409
+ all_anch = all_anch[fg_mask_inboxes]
1410
+
1411
+ this_target = this_target[matched_gt_inds]
1412
+
1413
+ for i in range(nl):
1414
+ layer_idx = from_which_layer == i
1415
+ matching_bs[i].append(all_b[layer_idx])
1416
+ matching_as[i].append(all_a[layer_idx])
1417
+ matching_gjs[i].append(all_gj[layer_idx])
1418
+ matching_gis[i].append(all_gi[layer_idx])
1419
+ matching_targets[i].append(this_target[layer_idx])
1420
+ matching_anchs[i].append(all_anch[layer_idx])
1421
+
1422
+ for i in range(nl):
1423
+ if matching_targets[i] != []:
1424
+ matching_bs[i] = torch.cat(matching_bs[i], dim=0)
1425
+ matching_as[i] = torch.cat(matching_as[i], dim=0)
1426
+ matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)
1427
+ matching_gis[i] = torch.cat(matching_gis[i], dim=0)
1428
+ matching_targets[i] = torch.cat(matching_targets[i], dim=0)
1429
+ matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)
1430
+ else:
1431
+ matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1432
+ matching_as[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1433
+ matching_gjs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1434
+ matching_gis[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1435
+ matching_targets[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1436
+ matching_anchs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1437
+
1438
+ return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs
1439
+
1440
+ def build_targets2(self, p, targets, imgs):
1441
+
1442
+ indices, anch = self.find_5_positive(p, targets)
1443
+
1444
+ matching_bs = [[] for pp in p]
1445
+ matching_as = [[] for pp in p]
1446
+ matching_gjs = [[] for pp in p]
1447
+ matching_gis = [[] for pp in p]
1448
+ matching_targets = [[] for pp in p]
1449
+ matching_anchs = [[] for pp in p]
1450
+
1451
+ nl = len(p)
1452
+
1453
+ for batch_idx in range(p[0].shape[0]):
1454
+
1455
+ b_idx = targets[:, 0]==batch_idx
1456
+ this_target = targets[b_idx]
1457
+ if this_target.shape[0] == 0:
1458
+ continue
1459
+
1460
+ txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]
1461
+ txyxy = xywh2xyxy(txywh)
1462
+
1463
+ pxyxys = []
1464
+ p_cls = []
1465
+ p_obj = []
1466
+ from_which_layer = []
1467
+ all_b = []
1468
+ all_a = []
1469
+ all_gj = []
1470
+ all_gi = []
1471
+ all_anch = []
1472
+
1473
+ for i, pi in enumerate(p):
1474
+
1475
+ b, a, gj, gi = indices[i]
1476
+ idx = (b == batch_idx)
1477
+ b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx]
1478
+ all_b.append(b)
1479
+ all_a.append(a)
1480
+ all_gj.append(gj)
1481
+ all_gi.append(gi)
1482
+ all_anch.append(anch[i][idx])
1483
+ from_which_layer.append(torch.ones(size=(len(b),)) * i)
1484
+
1485
+ fg_pred = pi[b, a, gj, gi]
1486
+ p_obj.append(fg_pred[:, 4:5])
1487
+ p_cls.append(fg_pred[:, 5:])
1488
+
1489
+ grid = torch.stack([gi, gj], dim=1)
1490
+ pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.
1491
+ #pxy = (fg_pred[:, :2].sigmoid() * 3. - 1. + grid) * self.stride[i]
1492
+ pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.
1493
+ pxywh = torch.cat([pxy, pwh], dim=-1)
1494
+ pxyxy = xywh2xyxy(pxywh)
1495
+ pxyxys.append(pxyxy)
1496
+
1497
+ pxyxys = torch.cat(pxyxys, dim=0)
1498
+ if pxyxys.shape[0] == 0:
1499
+ continue
1500
+ p_obj = torch.cat(p_obj, dim=0)
1501
+ p_cls = torch.cat(p_cls, dim=0)
1502
+ from_which_layer = torch.cat(from_which_layer, dim=0)
1503
+ all_b = torch.cat(all_b, dim=0)
1504
+ all_a = torch.cat(all_a, dim=0)
1505
+ all_gj = torch.cat(all_gj, dim=0)
1506
+ all_gi = torch.cat(all_gi, dim=0)
1507
+ all_anch = torch.cat(all_anch, dim=0)
1508
+
1509
+ pair_wise_iou = box_iou(txyxy, pxyxys)
1510
+
1511
+ pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)
1512
+
1513
+ top_k, _ = torch.topk(pair_wise_iou, min(20, pair_wise_iou.shape[1]), dim=1)
1514
+ dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)
1515
+
1516
+ gt_cls_per_image = (
1517
+ F.one_hot(this_target[:, 1].to(torch.int64), self.nc)
1518
+ .float()
1519
+ .unsqueeze(1)
1520
+ .repeat(1, pxyxys.shape[0], 1)
1521
+ )
1522
+
1523
+ num_gt = this_target.shape[0]
1524
+ cls_preds_ = (
1525
+ p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1526
+ * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1527
+ )
1528
+
1529
+ y = cls_preds_.sqrt_()
1530
+ pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
1531
+ torch.log(y/(1-y)) , gt_cls_per_image, reduction="none"
1532
+ ).sum(-1)
1533
+ del cls_preds_
1534
+
1535
+ cost = (
1536
+ pair_wise_cls_loss
1537
+ + 3.0 * pair_wise_iou_loss
1538
+ )
1539
+
1540
+ matching_matrix = torch.zeros_like(cost)
1541
+
1542
+ for gt_idx in range(num_gt):
1543
+ _, pos_idx = torch.topk(
1544
+ cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
1545
+ )
1546
+ matching_matrix[gt_idx][pos_idx] = 1.0
1547
+
1548
+ del top_k, dynamic_ks
1549
+ anchor_matching_gt = matching_matrix.sum(0)
1550
+ if (anchor_matching_gt > 1).sum() > 0:
1551
+ _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
1552
+ matching_matrix[:, anchor_matching_gt > 1] *= 0.0
1553
+ matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
1554
+ fg_mask_inboxes = matching_matrix.sum(0) > 0.0
1555
+ matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
1556
+
1557
+ from_which_layer = from_which_layer[fg_mask_inboxes]
1558
+ all_b = all_b[fg_mask_inboxes]
1559
+ all_a = all_a[fg_mask_inboxes]
1560
+ all_gj = all_gj[fg_mask_inboxes]
1561
+ all_gi = all_gi[fg_mask_inboxes]
1562
+ all_anch = all_anch[fg_mask_inboxes]
1563
+
1564
+ this_target = this_target[matched_gt_inds]
1565
+
1566
+ for i in range(nl):
1567
+ layer_idx = from_which_layer == i
1568
+ matching_bs[i].append(all_b[layer_idx])
1569
+ matching_as[i].append(all_a[layer_idx])
1570
+ matching_gjs[i].append(all_gj[layer_idx])
1571
+ matching_gis[i].append(all_gi[layer_idx])
1572
+ matching_targets[i].append(this_target[layer_idx])
1573
+ matching_anchs[i].append(all_anch[layer_idx])
1574
+
1575
+ for i in range(nl):
1576
+ if matching_targets[i] != []:
1577
+ matching_bs[i] = torch.cat(matching_bs[i], dim=0)
1578
+ matching_as[i] = torch.cat(matching_as[i], dim=0)
1579
+ matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)
1580
+ matching_gis[i] = torch.cat(matching_gis[i], dim=0)
1581
+ matching_targets[i] = torch.cat(matching_targets[i], dim=0)
1582
+ matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)
1583
+ else:
1584
+ matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1585
+ matching_as[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1586
+ matching_gjs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1587
+ matching_gis[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1588
+ matching_targets[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1589
+ matching_anchs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
1590
+
1591
+ return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs
1592
+
1593
+ def find_5_positive(self, p, targets):
1594
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
1595
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
1596
+ indices, anch = [], []
1597
+ gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain
1598
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
1599
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
1600
+
1601
+ g = 1.0 # bias
1602
+ off = torch.tensor([[0, 0],
1603
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
1604
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
1605
+ ], device=targets.device).float() * g # offsets
1606
+
1607
+ for i in range(self.nl):
1608
+ anchors = self.anchors[i]
1609
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
1610
+
1611
+ # Match targets to anchors
1612
+ t = targets * gain
1613
+ if nt:
1614
+ # Matches
1615
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
1616
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
1617
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
1618
+ t = t[j] # filter
1619
+
1620
+ # Offsets
1621
+ gxy = t[:, 2:4] # grid xy
1622
+ gxi = gain[[2, 3]] - gxy # inverse
1623
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
1624
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
1625
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
1626
+ t = t.repeat((5, 1, 1))[j]
1627
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
1628
+ else:
1629
+ t = targets[0]
1630
+ offsets = 0
1631
+
1632
+ # Define
1633
+ b, c = t[:, :2].long().T # image, class
1634
+ gxy = t[:, 2:4] # grid xy
1635
+ gwh = t[:, 4:6] # grid wh
1636
+ gij = (gxy - offsets).long()
1637
+ gi, gj = gij.T # grid xy indices
1638
+
1639
+ # Append
1640
+ a = t[:, 6].long() # anchor indices
1641
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
1642
+ anch.append(anchors[a]) # anchors
1643
+
1644
+ return indices, anch
1645
+
1646
+ def find_3_positive(self, p, targets):
1647
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
1648
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
1649
+ indices, anch = [], []
1650
+ gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain
1651
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
1652
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
1653
+
1654
+ g = 0.5 # bias
1655
+ off = torch.tensor([[0, 0],
1656
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
1657
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
1658
+ ], device=targets.device).float() * g # offsets
1659
+
1660
+ for i in range(self.nl):
1661
+ anchors = self.anchors[i]
1662
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
1663
+
1664
+ # Match targets to anchors
1665
+ t = targets * gain
1666
+ if nt:
1667
+ # Matches
1668
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
1669
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
1670
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
1671
+ t = t[j] # filter
1672
+
1673
+ # Offsets
1674
+ gxy = t[:, 2:4] # grid xy
1675
+ gxi = gain[[2, 3]] - gxy # inverse
1676
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
1677
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
1678
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
1679
+ t = t.repeat((5, 1, 1))[j]
1680
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
1681
+ else:
1682
+ t = targets[0]
1683
+ offsets = 0
1684
+
1685
+ # Define
1686
+ b, c = t[:, :2].long().T # image, class
1687
+ gxy = t[:, 2:4] # grid xy
1688
+ gwh = t[:, 4:6] # grid wh
1689
+ gij = (gxy - offsets).long()
1690
+ gi, gj = gij.T # grid xy indices
1691
+
1692
+ # Append
1693
+ a = t[:, 6].long() # anchor indices
1694
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
1695
+ anch.append(anchors[a]) # anchors
1696
+
1697
+ return indices, anch
yolov7detect/utils/metrics.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model validation metrics
2
+
3
+ from pathlib import Path
4
+
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import torch
8
+
9
+ from yolov7.utils import general
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, [email protected], [email protected]:0.95]
15
+ return (x[:, :4] * w).sum(1)
16
+
17
+
18
+ def ap_per_class(tp, conf, pred_cls, target_cls, v5_metric=False, plot=False, save_dir='.', names=()):
19
+ """ Compute the average precision, given the recall and precision curves.
20
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
21
+ # Arguments
22
+ tp: True positives (nparray, nx1 or nx10).
23
+ conf: Objectness value from 0-1 (nparray).
24
+ pred_cls: Predicted object classes (nparray).
25
+ target_cls: True object classes (nparray).
26
+ plot: Plot precision-recall curve at [email protected]
27
+ save_dir: Plot save directory
28
+ # Returns
29
+ The average precision as computed in py-faster-rcnn.
30
+ """
31
+
32
+ # Sort by objectness
33
+ i = np.argsort(-conf)
34
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
35
+
36
+ # Find unique classes
37
+ unique_classes = np.unique(target_cls)
38
+ nc = unique_classes.shape[0] # number of classes, number of detections
39
+
40
+ # Create Precision-Recall curve and compute AP for each class
41
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
42
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
43
+ for ci, c in enumerate(unique_classes):
44
+ i = pred_cls == c
45
+ n_l = (target_cls == c).sum() # number of labels
46
+ n_p = i.sum() # number of predictions
47
+
48
+ if n_p == 0 or n_l == 0:
49
+ continue
50
+ else:
51
+ # Accumulate FPs and TPs
52
+ fpc = (1 - tp[i]).cumsum(0)
53
+ tpc = tp[i].cumsum(0)
54
+
55
+ # Recall
56
+ recall = tpc / (n_l + 1e-16) # recall curve
57
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
58
+
59
+ # Precision
60
+ precision = tpc / (tpc + fpc) # precision curve
61
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
62
+
63
+ # AP from recall-precision curve
64
+ for j in range(tp.shape[1]):
65
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j], v5_metric=v5_metric)
66
+ if plot and j == 0:
67
+ py.append(np.interp(px, mrec, mpre)) # precision at [email protected]
68
+
69
+ # Compute F1 (harmonic mean of precision and recall)
70
+ f1 = 2 * p * r / (p + r + 1e-16)
71
+ if plot:
72
+ plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
73
+ plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
74
+ plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
75
+ plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
76
+
77
+ i = f1.mean(0).argmax() # max F1 index
78
+ return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
79
+
80
+
81
+ def compute_ap(recall, precision, v5_metric=False):
82
+ """ Compute the average precision, given the recall and precision curves
83
+ # Arguments
84
+ recall: The recall curve (list)
85
+ precision: The precision curve (list)
86
+ v5_metric: Assume maximum recall to be 1.0, as in YOLOv5, MMDetetion etc.
87
+ # Returns
88
+ Average precision, precision curve, recall curve
89
+ """
90
+
91
+ # Append sentinel values to beginning and end
92
+ if v5_metric: # New YOLOv5 metric, same as MMDetection and Detectron2 repositories
93
+ mrec = np.concatenate(([0.], recall, [1.0]))
94
+ else: # Old YOLOv5 metric, i.e. default YOLOv7 metric
95
+ mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
96
+ mpre = np.concatenate(([1.], precision, [0.]))
97
+
98
+ # Compute the precision envelope
99
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
100
+
101
+ # Integrate area under curve
102
+ method = 'interp' # methods: 'continuous', 'interp'
103
+ if method == 'interp':
104
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
105
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
106
+ else: # 'continuous'
107
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
108
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
109
+
110
+ return ap, mpre, mrec
111
+
112
+
113
+ class ConfusionMatrix:
114
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
115
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
116
+ self.matrix = np.zeros((nc + 1, nc + 1))
117
+ self.nc = nc # number of classes
118
+ self.conf = conf
119
+ self.iou_thres = iou_thres
120
+
121
+ def process_batch(self, detections, labels):
122
+ """
123
+ Return intersection-over-union (Jaccard index) of boxes.
124
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
125
+ Arguments:
126
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
127
+ labels (Array[M, 5]), class, x1, y1, x2, y2
128
+ Returns:
129
+ None, updates confusion matrix accordingly
130
+ """
131
+ detections = detections[detections[:, 4] > self.conf]
132
+ gt_classes = labels[:, 0].int()
133
+ detection_classes = detections[:, 5].int()
134
+ iou = general.box_iou(labels[:, 1:], detections[:, :4])
135
+
136
+ x = torch.where(iou > self.iou_thres)
137
+ if x[0].shape[0]:
138
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
139
+ if x[0].shape[0] > 1:
140
+ matches = matches[matches[:, 2].argsort()[::-1]]
141
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
142
+ matches = matches[matches[:, 2].argsort()[::-1]]
143
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
144
+ else:
145
+ matches = np.zeros((0, 3))
146
+
147
+ n = matches.shape[0] > 0
148
+ m0, m1, _ = matches.transpose().astype(np.int16)
149
+ for i, gc in enumerate(gt_classes):
150
+ j = m0 == i
151
+ if n and sum(j) == 1:
152
+ self.matrix[gc, detection_classes[m1[j]]] += 1 # correct
153
+ else:
154
+ self.matrix[self.nc, gc] += 1 # background FP
155
+
156
+ if n:
157
+ for i, dc in enumerate(detection_classes):
158
+ if not any(m1 == i):
159
+ self.matrix[dc, self.nc] += 1 # background FN
160
+
161
+ def matrix(self):
162
+ return self.matrix
163
+
164
+ def plot(self, save_dir='', names=()):
165
+ try:
166
+ import seaborn as sn
167
+
168
+ array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
169
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
170
+
171
+ fig = plt.figure(figsize=(12, 9), tight_layout=True)
172
+ sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
173
+ labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
174
+ sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
175
+ xticklabels=names + ['background FP'] if labels else "auto",
176
+ yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
177
+ fig.axes[0].set_xlabel('True')
178
+ fig.axes[0].set_ylabel('Predicted')
179
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
180
+ except Exception as e:
181
+ pass
182
+
183
+ def print(self):
184
+ for i in range(self.nc + 1):
185
+ print(' '.join(map(str, self.matrix[i])))
186
+
187
+
188
+ # Plots ----------------------------------------------------------------------------------------------------------------
189
+
190
+ def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
191
+ # Precision-recall curve
192
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
193
+ py = np.stack(py, axis=1)
194
+
195
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
196
+ for i, y in enumerate(py.T):
197
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
198
+ else:
199
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
200
+
201
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f [email protected]' % ap[:, 0].mean())
202
+ ax.set_xlabel('Recall')
203
+ ax.set_ylabel('Precision')
204
+ ax.set_xlim(0, 1)
205
+ ax.set_ylim(0, 1)
206
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
207
+ fig.savefig(Path(save_dir), dpi=250)
208
+
209
+
210
+ def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
211
+ # Metric-confidence curve
212
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
213
+
214
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
215
+ for i, y in enumerate(py):
216
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
217
+ else:
218
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
219
+
220
+ y = py.mean(0)
221
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
222
+ ax.set_xlabel(xlabel)
223
+ ax.set_ylabel(ylabel)
224
+ ax.set_xlim(0, 1)
225
+ ax.set_ylim(0, 1)
226
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
227
+ fig.savefig(Path(save_dir), dpi=250)
yolov7detect/utils/plots.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Plotting utils
2
+
3
+ import glob
4
+ import math
5
+ import os
6
+ import random
7
+ from copy import copy
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import matplotlib
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+ import pandas as pd
15
+ import seaborn as sns
16
+ import torch
17
+ import yaml
18
+ from PIL import Image, ImageDraw, ImageFont
19
+ from scipy.signal import butter, filtfilt
20
+
21
+ from yolov7.utils.general import xywh2xyxy, xyxy2xywh
22
+ from yolov7.utils.metrics import fitness
23
+
24
+ # Settings
25
+ matplotlib.rc('font', **{'size': 11})
26
+ matplotlib.use('Agg') # for writing to files only
27
+
28
+
29
+ def color_list():
30
+ # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
31
+ def hex2rgb(h):
32
+ return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
33
+
34
+ return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949)
35
+
36
+
37
+ def hist2d(x, y, n=100):
38
+ # 2d histogram used in labels.png and evolve.png
39
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
40
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
41
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
42
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
43
+ return np.log(hist[xidx, yidx])
44
+
45
+
46
+ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
47
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
48
+ def butter_lowpass(cutoff, fs, order):
49
+ nyq = 0.5 * fs
50
+ normal_cutoff = cutoff / nyq
51
+ return butter(order, normal_cutoff, btype='low', analog=False)
52
+
53
+ b, a = butter_lowpass(cutoff, fs, order=order)
54
+ return filtfilt(b, a, data) # forward-backward filter
55
+
56
+
57
+ def plot_one_box(x, img, color=None, label=None, line_thickness=3):
58
+ # Plots one bounding box on image img
59
+ tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
60
+ color = color or [random.randint(0, 255) for _ in range(3)]
61
+ c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
62
+ cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
63
+ if label:
64
+ tf = max(tl - 1, 1) # font thickness
65
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
66
+ c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
67
+ cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
68
+ cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
69
+
70
+
71
+ def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None):
72
+ img = Image.fromarray(img)
73
+ draw = ImageDraw.Draw(img)
74
+ line_thickness = line_thickness or max(int(min(img.size) / 200), 2)
75
+ draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot
76
+ if label:
77
+ fontsize = max(round(max(img.size) / 40), 12)
78
+ font = ImageFont.truetype("Arial.ttf", fontsize)
79
+ txt_width, txt_height = font.getsize(label)
80
+ draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
81
+ draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
82
+ return np.asarray(img)
83
+
84
+
85
+ def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
86
+ # Compares the two methods for width-height anchor multiplication
87
+ # https://github.com/ultralytics/yolov3/issues/168
88
+ x = np.arange(-4.0, 4.0, .1)
89
+ ya = np.exp(x)
90
+ yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
91
+
92
+ fig = plt.figure(figsize=(6, 3), tight_layout=True)
93
+ plt.plot(x, ya, '.-', label='YOLOv3')
94
+ plt.plot(x, yb ** 2, '.-', label='YOLOR ^2')
95
+ plt.plot(x, yb ** 1.6, '.-', label='YOLOR ^1.6')
96
+ plt.xlim(left=-4, right=4)
97
+ plt.ylim(bottom=0, top=6)
98
+ plt.xlabel('input')
99
+ plt.ylabel('output')
100
+ plt.grid()
101
+ plt.legend()
102
+ fig.savefig('comparison.png', dpi=200)
103
+
104
+
105
+ def output_to_target(output):
106
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
107
+ targets = []
108
+ for i, o in enumerate(output):
109
+ for *box, conf, cls in o.cpu().numpy():
110
+ targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
111
+ return np.array(targets)
112
+
113
+
114
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
115
+ # Plot image grid with labels
116
+
117
+ if isinstance(images, torch.Tensor):
118
+ images = images.cpu().float().numpy()
119
+ if isinstance(targets, torch.Tensor):
120
+ targets = targets.cpu().numpy()
121
+
122
+ # un-normalise
123
+ if np.max(images[0]) <= 1:
124
+ images *= 255
125
+
126
+ tl = 3 # line thickness
127
+ tf = max(tl - 1, 1) # font thickness
128
+ bs, _, h, w = images.shape # batch size, _, height, width
129
+ bs = min(bs, max_subplots) # limit plot images
130
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
131
+
132
+ # Check if we should resize
133
+ scale_factor = max_size / max(h, w)
134
+ if scale_factor < 1:
135
+ h = math.ceil(scale_factor * h)
136
+ w = math.ceil(scale_factor * w)
137
+
138
+ colors = color_list() # list of colors
139
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
140
+ for i, img in enumerate(images):
141
+ if i == max_subplots: # if last batch has fewer images than we expect
142
+ break
143
+
144
+ block_x = int(w * (i // ns))
145
+ block_y = int(h * (i % ns))
146
+
147
+ img = img.transpose(1, 2, 0)
148
+ if scale_factor < 1:
149
+ img = cv2.resize(img, (w, h))
150
+
151
+ mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
152
+ if len(targets) > 0:
153
+ image_targets = targets[targets[:, 0] == i]
154
+ boxes = xywh2xyxy(image_targets[:, 2:6]).T
155
+ classes = image_targets[:, 1].astype('int')
156
+ labels = image_targets.shape[1] == 6 # labels if no conf column
157
+ conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
158
+
159
+ if boxes.shape[1]:
160
+ if boxes.max() <= 1.01: # if normalized with tolerance 0.01
161
+ boxes[[0, 2]] *= w # scale to pixels
162
+ boxes[[1, 3]] *= h
163
+ elif scale_factor < 1: # absolute coords need scale if image scales
164
+ boxes *= scale_factor
165
+ boxes[[0, 2]] += block_x
166
+ boxes[[1, 3]] += block_y
167
+ for j, box in enumerate(boxes.T):
168
+ cls = int(classes[j])
169
+ color = colors[cls % len(colors)]
170
+ cls = names[cls] if names else cls
171
+ if labels or conf[j] > 0.25: # 0.25 conf thresh
172
+ label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
173
+ plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
174
+
175
+ # Draw image filename labels
176
+ if paths:
177
+ label = Path(paths[i]).name[:40] # trim to 40 char
178
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
179
+ cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
180
+ lineType=cv2.LINE_AA)
181
+
182
+ # Image border
183
+ cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
184
+
185
+ if fname:
186
+ r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
187
+ mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
188
+ # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
189
+ Image.fromarray(mosaic).save(fname) # PIL save
190
+ return mosaic
191
+
192
+
193
+ def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
194
+ # Plot LR simulating training for full epochs
195
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
196
+ y = []
197
+ for _ in range(epochs):
198
+ scheduler.step()
199
+ y.append(optimizer.param_groups[0]['lr'])
200
+ plt.plot(y, '.-', label='LR')
201
+ plt.xlabel('epoch')
202
+ plt.ylabel('LR')
203
+ plt.grid()
204
+ plt.xlim(0, epochs)
205
+ plt.ylim(0)
206
+ plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
207
+ plt.close()
208
+
209
+
210
+ def plot_test_txt(): # from utils.plots import *; plot_test()
211
+ # Plot test.txt histograms
212
+ x = np.loadtxt('test.txt', dtype=np.float32)
213
+ box = xyxy2xywh(x[:, :4])
214
+ cx, cy = box[:, 0], box[:, 1]
215
+
216
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
217
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
218
+ ax.set_aspect('equal')
219
+ plt.savefig('hist2d.png', dpi=300)
220
+
221
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
222
+ ax[0].hist(cx, bins=600)
223
+ ax[1].hist(cy, bins=600)
224
+ plt.savefig('hist1d.png', dpi=200)
225
+
226
+
227
+ def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
228
+ # Plot targets.txt histograms
229
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
230
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
231
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
232
+ ax = ax.ravel()
233
+ for i in range(4):
234
+ ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
235
+ ax[i].legend()
236
+ ax[i].set_title(s[i])
237
+ plt.savefig('targets.jpg', dpi=200)
238
+
239
+
240
+ def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
241
+ # Plot study.txt generated by test.py
242
+ fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
243
+ # ax = ax.ravel()
244
+
245
+ fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
246
+ # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolor-p6', 'yolor-w6', 'yolor-e6', 'yolor-d6']]:
247
+ for f in sorted(Path(path).glob('study*.txt')):
248
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
249
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
250
+ s = ['P', 'R', '[email protected]', '[email protected]:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
251
+ # for i in range(7):
252
+ # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
253
+ # ax[i].set_title(s[i])
254
+
255
+ j = y[3].argmax() + 1
256
+ ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
257
+ label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
258
+
259
+ ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
260
+ 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
261
+
262
+ ax2.grid(alpha=0.2)
263
+ ax2.set_yticks(np.arange(20, 60, 5))
264
+ ax2.set_xlim(0, 57)
265
+ ax2.set_ylim(30, 55)
266
+ ax2.set_xlabel('GPU Speed (ms/img)')
267
+ ax2.set_ylabel('COCO AP val')
268
+ ax2.legend(loc='lower right')
269
+ plt.savefig(str(Path(path).name) + '.png', dpi=300)
270
+
271
+
272
+ def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
273
+ # plot dataset labels
274
+ print('Plotting labels... ')
275
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
276
+ nc = int(c.max() + 1) # number of classes
277
+ colors = color_list()
278
+ x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
279
+
280
+ # seaborn correlogram
281
+ sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
282
+ plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
283
+ plt.close()
284
+
285
+ # matplotlib labels
286
+ matplotlib.use('svg') # faster
287
+ ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
288
+ ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
289
+ ax[0].set_ylabel('instances')
290
+ if 0 < len(names) < 30:
291
+ ax[0].set_xticks(range(len(names)))
292
+ ax[0].set_xticklabels(names, rotation=90, fontsize=10)
293
+ else:
294
+ ax[0].set_xlabel('classes')
295
+ sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
296
+ sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
297
+
298
+ # rectangles
299
+ labels[:, 1:3] = 0.5 # center
300
+ labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
301
+ img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
302
+ for cls, *box in labels[:1000]:
303
+ ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot
304
+ ax[1].imshow(img)
305
+ ax[1].axis('off')
306
+
307
+ for a in [0, 1, 2, 3]:
308
+ for s in ['top', 'right', 'left', 'bottom']:
309
+ ax[a].spines[s].set_visible(False)
310
+
311
+ plt.savefig(save_dir / 'labels.jpg', dpi=200)
312
+ matplotlib.use('Agg')
313
+ plt.close()
314
+
315
+ # loggers
316
+ for k, v in loggers.items() or {}:
317
+ if k == 'wandb' and v:
318
+ v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
319
+
320
+
321
+ def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
322
+ # Plot hyperparameter evolution results in evolve.txt
323
+ with open(yaml_file) as f:
324
+ hyp = yaml.load(f, Loader=yaml.SafeLoader)
325
+ x = np.loadtxt('evolve.txt', ndmin=2)
326
+ f = fitness(x)
327
+ # weights = (f - f.min()) ** 2 # for weighted results
328
+ plt.figure(figsize=(10, 12), tight_layout=True)
329
+ matplotlib.rc('font', **{'size': 8})
330
+ for i, (k, v) in enumerate(hyp.items()):
331
+ y = x[:, i + 7]
332
+ # mu = (y * weights).sum() / weights.sum() # best weighted result
333
+ mu = y[f.argmax()] # best single result
334
+ plt.subplot(6, 5, i + 1)
335
+ plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
336
+ plt.plot(mu, f.max(), 'k+', markersize=15)
337
+ plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
338
+ if i % 5 != 0:
339
+ plt.yticks([])
340
+ print('%15s: %.3g' % (k, mu))
341
+ plt.savefig('evolve.png', dpi=200)
342
+ print('\nPlot saved as evolve.png')
343
+
344
+
345
+ def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
346
+ # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
347
+ ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
348
+ s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
349
+ files = list(Path(save_dir).glob('frames*.txt'))
350
+ for fi, f in enumerate(files):
351
+ try:
352
+ results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
353
+ n = results.shape[1] # number of rows
354
+ x = np.arange(start, min(stop, n) if stop else n)
355
+ results = results[:, x]
356
+ t = (results[0] - results[0].min()) # set t0=0s
357
+ results[0] = x
358
+ for i, a in enumerate(ax):
359
+ if i < len(results):
360
+ label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
361
+ a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
362
+ a.set_title(s[i])
363
+ a.set_xlabel('time (s)')
364
+ # if fi == len(files) - 1:
365
+ # a.set_ylim(bottom=0)
366
+ for side in ['top', 'right']:
367
+ a.spines[side].set_visible(False)
368
+ else:
369
+ a.remove()
370
+ except Exception as e:
371
+ print('Warning: Plotting error for %s; %s' % (f, e))
372
+
373
+ ax[1].legend()
374
+ plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
375
+
376
+
377
+ def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
378
+ # Plot training 'results*.txt', overlaying train and val losses
379
+ s = ['train', 'train', 'train', 'Precision', '[email protected]', 'val', 'val', 'val', 'Recall', '[email protected]:0.95'] # legends
380
+ t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
381
+ for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
382
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
383
+ n = results.shape[1] # number of rows
384
+ x = range(start, min(stop, n) if stop else n)
385
+ fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
386
+ ax = ax.ravel()
387
+ for i in range(5):
388
+ for j in [i, i + 5]:
389
+ y = results[j, x]
390
+ ax[i].plot(x, y, marker='.', label=s[j])
391
+ # y_smooth = butter_lowpass_filtfilt(y)
392
+ # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
393
+
394
+ ax[i].set_title(t[i])
395
+ ax[i].legend()
396
+ ax[i].set_ylabel(f) if i == 0 else None # add filename
397
+ fig.savefig(f.replace('.txt', '.png'), dpi=200)
398
+
399
+
400
+ def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
401
+ # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
402
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
403
+ ax = ax.ravel()
404
+ s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
405
+ 'val Box', 'val Objectness', 'val Classification', '[email protected]', '[email protected]:0.95']
406
+ if bucket:
407
+ # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
408
+ files = ['results%g.txt' % x for x in id]
409
+ c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
410
+ os.system(c)
411
+ else:
412
+ files = list(Path(save_dir).glob('results*.txt'))
413
+ assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
414
+ for fi, f in enumerate(files):
415
+ try:
416
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
417
+ n = results.shape[1] # number of rows
418
+ x = range(start, min(stop, n) if stop else n)
419
+ for i in range(10):
420
+ y = results[i, x]
421
+ if i in [0, 1, 2, 5, 6, 7]:
422
+ y[y == 0] = np.nan # don't show zero loss values
423
+ # y /= y[0] # normalize
424
+ label = labels[fi] if len(labels) else f.stem
425
+ ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
426
+ ax[i].set_title(s[i])
427
+ # if i in [5, 6, 7]: # share train and val loss y axes
428
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
429
+ except Exception as e:
430
+ print('Warning: Plotting error for %s; %s' % (f, e))
431
+
432
+ ax[1].legend()
433
+ fig.savefig(Path(save_dir) / 'results.png', dpi=200)
434
+
435
+
436
+ def output_to_keypoint(output):
437
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
438
+ targets = []
439
+ for i, o in enumerate(output):
440
+ kpts = o[:,6:]
441
+ o = o[:,:6]
442
+ for index, (*box, conf, cls) in enumerate(o.detach().cpu().numpy()):
443
+ targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf, *list(kpts.detach().cpu().numpy()[index])])
444
+ return np.array(targets)
445
+
446
+
447
+ def plot_skeleton_kpts(im, kpts, steps, orig_shape=None):
448
+ #Plot the skeleton and keypointsfor coco datatset
449
+ palette = np.array([[255, 128, 0], [255, 153, 51], [255, 178, 102],
450
+ [230, 230, 0], [255, 153, 255], [153, 204, 255],
451
+ [255, 102, 255], [255, 51, 255], [102, 178, 255],
452
+ [51, 153, 255], [255, 153, 153], [255, 102, 102],
453
+ [255, 51, 51], [153, 255, 153], [102, 255, 102],
454
+ [51, 255, 51], [0, 255, 0], [0, 0, 255], [255, 0, 0],
455
+ [255, 255, 255]])
456
+
457
+ skeleton = [[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12],
458
+ [7, 13], [6, 7], [6, 8], [7, 9], [8, 10], [9, 11], [2, 3],
459
+ [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]]
460
+
461
+ pose_limb_color = palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]]
462
+ pose_kpt_color = palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]]
463
+ radius = 5
464
+ num_kpts = len(kpts) // steps
465
+
466
+ for kid in range(num_kpts):
467
+ r, g, b = pose_kpt_color[kid]
468
+ x_coord, y_coord = kpts[steps * kid], kpts[steps * kid + 1]
469
+ if not (x_coord % 640 == 0 or y_coord % 640 == 0):
470
+ if steps == 3:
471
+ conf = kpts[steps * kid + 2]
472
+ if conf < 0.5:
473
+ continue
474
+ cv2.circle(im, (int(x_coord), int(y_coord)), radius, (int(r), int(g), int(b)), -1)
475
+
476
+ for sk_id, sk in enumerate(skeleton):
477
+ r, g, b = pose_limb_color[sk_id]
478
+ pos1 = (int(kpts[(sk[0]-1)*steps]), int(kpts[(sk[0]-1)*steps+1]))
479
+ pos2 = (int(kpts[(sk[1]-1)*steps]), int(kpts[(sk[1]-1)*steps+1]))
480
+ if steps == 3:
481
+ conf1 = kpts[(sk[0]-1)*steps+2]
482
+ conf2 = kpts[(sk[1]-1)*steps+2]
483
+ if conf1<0.5 or conf2<0.5:
484
+ continue
485
+ if pos1[0]%640 == 0 or pos1[1]%640==0 or pos1[0]<0 or pos1[1]<0:
486
+ continue
487
+ if pos2[0] % 640 == 0 or pos2[1] % 640 == 0 or pos2[0]<0 or pos2[1]<0:
488
+ continue
489
+ cv2.line(im, pos1, pos2, (int(r), int(g), int(b)), thickness=2)
yolov7detect/utils/torch_utils.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOR PyTorch utils
2
+
3
+ import datetime
4
+ import logging
5
+ import math
6
+ import os
7
+ import platform
8
+ import subprocess
9
+ import time
10
+ from contextlib import contextmanager
11
+ from copy import deepcopy
12
+ from pathlib import Path
13
+
14
+ import torch
15
+ import torch.backends.cudnn as cudnn
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ import torchvision
19
+
20
+ try:
21
+ import thop # for FLOPS computation
22
+ except ImportError:
23
+ thop = None
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ @contextmanager
28
+ def torch_distributed_zero_first(local_rank: int):
29
+ """
30
+ Decorator to make all processes in distributed training wait for each local_master to do something.
31
+ """
32
+ if local_rank not in [-1, 0]:
33
+ torch.distributed.barrier()
34
+ yield
35
+ if local_rank == 0:
36
+ torch.distributed.barrier()
37
+
38
+
39
+ def init_torch_seeds(seed=0):
40
+ # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
41
+ torch.manual_seed(seed)
42
+ if seed == 0: # slower, more reproducible
43
+ cudnn.benchmark, cudnn.deterministic = False, True
44
+ else: # faster, less reproducible
45
+ cudnn.benchmark, cudnn.deterministic = True, False
46
+
47
+
48
+ def date_modified(path=__file__):
49
+ # return human-readable file modification date, i.e. '2021-3-26'
50
+ t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
51
+ return f'{t.year}-{t.month}-{t.day}'
52
+
53
+
54
+ def git_describe(path=Path(__file__).parent): # path must be a directory
55
+ # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
56
+ s = f'git -C {path} describe --tags --long --always'
57
+ try:
58
+ return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
59
+ except subprocess.CalledProcessError as e:
60
+ return '' # not a git repository
61
+
62
+
63
+ def select_device(device='', batch_size=None):
64
+ # device = 'cpu' or '0' or '0,1,2,3'
65
+ s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
66
+ cpu = device.lower() == 'cpu'
67
+ if cpu:
68
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
69
+ elif device: # non-cpu device requested
70
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
71
+ assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
72
+
73
+ cuda = not cpu and torch.cuda.is_available()
74
+ if cuda:
75
+ n = torch.cuda.device_count()
76
+ if n > 1 and batch_size: # check that batch_size is compatible with device_count
77
+ assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
78
+ space = ' ' * len(s)
79
+ for i, d in enumerate(device.split(',') if device else range(n)):
80
+ p = torch.cuda.get_device_properties(i)
81
+ s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
82
+ else:
83
+ s += 'CPU\n'
84
+
85
+ logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
86
+ return torch.device('cuda:0' if cuda else 'cpu')
87
+
88
+
89
+ def time_synchronized():
90
+ # pytorch-accurate time
91
+ if torch.cuda.is_available():
92
+ torch.cuda.synchronize()
93
+ return time.time()
94
+
95
+
96
+ def profile(x, ops, n=100, device=None):
97
+ # profile a pytorch module or list of modules. Example usage:
98
+ # x = torch.randn(16, 3, 640, 640) # input
99
+ # m1 = lambda x: x * torch.sigmoid(x)
100
+ # m2 = nn.SiLU()
101
+ # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
102
+
103
+ device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104
+ x = x.to(device)
105
+ x.requires_grad = True
106
+ print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
107
+ print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
108
+ for m in ops if isinstance(ops, list) else [ops]:
109
+ m = m.to(device) if hasattr(m, 'to') else m # device
110
+ m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
111
+ dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
112
+ try:
113
+ flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
114
+ except:
115
+ flops = 0
116
+
117
+ for _ in range(n):
118
+ t[0] = time_synchronized()
119
+ y = m(x)
120
+ t[1] = time_synchronized()
121
+ try:
122
+ _ = y.sum().backward()
123
+ t[2] = time_synchronized()
124
+ except: # no backward method
125
+ t[2] = float('nan')
126
+ dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
127
+ dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
128
+
129
+ s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
130
+ s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
131
+ p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
132
+ print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
133
+
134
+
135
+ def is_parallel(model):
136
+ return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
137
+
138
+
139
+ def intersect_dicts(da, db, exclude=()):
140
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
141
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
142
+
143
+
144
+ def initialize_weights(model):
145
+ for m in model.modules():
146
+ t = type(m)
147
+ if t is nn.Conv2d:
148
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
149
+ elif t is nn.BatchNorm2d:
150
+ m.eps = 1e-3
151
+ m.momentum = 0.03
152
+ elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
153
+ m.inplace = True
154
+
155
+
156
+ def find_modules(model, mclass=nn.Conv2d):
157
+ # Finds layer indices matching module class 'mclass'
158
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
159
+
160
+
161
+ def sparsity(model):
162
+ # Return global model sparsity
163
+ a, b = 0., 0.
164
+ for p in model.parameters():
165
+ a += p.numel()
166
+ b += (p == 0).sum()
167
+ return b / a
168
+
169
+
170
+ def prune(model, amount=0.3):
171
+ # Prune model to requested global sparsity
172
+ import torch.nn.utils.prune as prune
173
+ print('Pruning model... ', end='')
174
+ for name, m in model.named_modules():
175
+ if isinstance(m, nn.Conv2d):
176
+ prune.l1_unstructured(m, name='weight', amount=amount) # prune
177
+ prune.remove(m, 'weight') # make permanent
178
+ print(' %.3g global sparsity' % sparsity(model))
179
+
180
+
181
+ def fuse_conv_and_bn(conv, bn):
182
+ # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
183
+ fusedconv = nn.Conv2d(conv.in_channels,
184
+ conv.out_channels,
185
+ kernel_size=conv.kernel_size,
186
+ stride=conv.stride,
187
+ padding=conv.padding,
188
+ groups=conv.groups,
189
+ bias=True).requires_grad_(False).to(conv.weight.device)
190
+
191
+ # prepare filters
192
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
193
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
194
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
195
+
196
+ # prepare spatial bias
197
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
198
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
199
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
200
+
201
+ return fusedconv
202
+
203
+
204
+ def model_info(model, verbose=False, img_size=640):
205
+ # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
206
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
207
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
208
+ if verbose:
209
+ print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
210
+ for i, (name, p) in enumerate(model.named_parameters()):
211
+ name = name.replace('module_list.', '')
212
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
213
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
214
+
215
+ try: # FLOPS
216
+ from thop import profile
217
+ stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
218
+ img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
219
+ flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
220
+ img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
221
+ fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
222
+ except (ImportError, Exception):
223
+ fs = ''
224
+
225
+ logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
226
+
227
+
228
+ def load_classifier(name='resnet101', n=2):
229
+ # Loads a pretrained model reshaped to n-class output
230
+ model = torchvision.models.__dict__[name](pretrained=True)
231
+
232
+ # ResNet model properties
233
+ # input_size = [3, 224, 224]
234
+ # input_space = 'RGB'
235
+ # input_range = [0, 1]
236
+ # mean = [0.485, 0.456, 0.406]
237
+ # std = [0.229, 0.224, 0.225]
238
+
239
+ # Reshape output to n classes
240
+ filters = model.fc.weight.shape[1]
241
+ model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
242
+ model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
243
+ model.fc.out_features = n
244
+ return model
245
+
246
+
247
+ def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
248
+ # scales img(bs,3,y,x) by ratio constrained to gs-multiple
249
+ if ratio == 1.0:
250
+ return img
251
+ else:
252
+ h, w = img.shape[2:]
253
+ s = (int(h * ratio), int(w * ratio)) # new size
254
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
255
+ if not same_shape: # pad/crop img
256
+ h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
257
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
258
+
259
+
260
+ def copy_attr(a, b, include=(), exclude=()):
261
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
262
+ for k, v in b.__dict__.items():
263
+ if (len(include) and k not in include) or k.startswith('_') or k in exclude:
264
+ continue
265
+ else:
266
+ setattr(a, k, v)
267
+
268
+
269
+ class ModelEMA:
270
+ """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
271
+ Keep a moving average of everything in the model state_dict (parameters and buffers).
272
+ This is intended to allow functionality like
273
+ https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
274
+ A smoothed version of the weights is necessary for some training schemes to perform well.
275
+ This class is sensitive where it is initialized in the sequence of model init,
276
+ GPU assignment and distributed training wrappers.
277
+ """
278
+
279
+ def __init__(self, model, decay=0.9999, updates=0):
280
+ # Create EMA
281
+ self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
282
+ # if next(model.parameters()).device.type != 'cpu':
283
+ # self.ema.half() # FP16 EMA
284
+ self.updates = updates # number of EMA updates
285
+ self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
286
+ for p in self.ema.parameters():
287
+ p.requires_grad_(False)
288
+
289
+ def update(self, model):
290
+ # Update EMA parameters
291
+ with torch.no_grad():
292
+ self.updates += 1
293
+ d = self.decay(self.updates)
294
+
295
+ msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
296
+ for k, v in self.ema.state_dict().items():
297
+ if v.dtype.is_floating_point:
298
+ v *= d
299
+ v += (1. - d) * msd[k].detach()
300
+
301
+ def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
302
+ # Update EMA attributes
303
+ copy_attr(self.ema, model, include, exclude)
304
+
305
+
306
+ class BatchNormXd(torch.nn.modules.batchnorm._BatchNorm):
307
+ def _check_input_dim(self, input):
308
+ # The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc
309
+ # is this method that is overwritten by the sub-class
310
+ # This original goal of this method was for tensor sanity checks
311
+ # If you're ok bypassing those sanity checks (eg. if you trust your inference
312
+ # to provide the right dimensional inputs), then you can just use this method
313
+ # for easy conversion from SyncBatchNorm
314
+ # (unfortunately, SyncBatchNorm does not store the original class - if it did
315
+ # we could return the one that was originally created)
316
+ return
317
+
318
+ def revert_sync_batchnorm(module):
319
+ # this is very similar to the function that it is trying to revert:
320
+ # https://github.com/pytorch/pytorch/blob/c8b3686a3e4ba63dc59e5dcfe5db3430df256833/torch/nn/modules/batchnorm.py#L679
321
+ module_output = module
322
+ if isinstance(module, torch.nn.modules.batchnorm.SyncBatchNorm):
323
+ new_cls = BatchNormXd
324
+ module_output = BatchNormXd(module.num_features,
325
+ module.eps, module.momentum,
326
+ module.affine,
327
+ module.track_running_stats)
328
+ if module.affine:
329
+ with torch.no_grad():
330
+ module_output.weight = module.weight
331
+ module_output.bias = module.bias
332
+ module_output.running_mean = module.running_mean
333
+ module_output.running_var = module.running_var
334
+ module_output.num_batches_tracked = module.num_batches_tracked
335
+ if hasattr(module, "qconfig"):
336
+ module_output.qconfig = module.qconfig
337
+ for name, child in module.named_children():
338
+ module_output.add_module(name, revert_sync_batchnorm(child))
339
+ del module
340
+ return module_output
341
+
342
+
343
+ class TracedModel(nn.Module):
344
+
345
+ def __init__(self, model=None, device=None, img_size=(640,640)):
346
+ super(TracedModel, self).__init__()
347
+
348
+ print(" Convert model to Traced-model... ")
349
+ self.stride = model.stride
350
+ self.names = model.names
351
+ self.model = model
352
+
353
+ self.model = revert_sync_batchnorm(self.model)
354
+ self.model.to('cpu')
355
+ self.model.eval()
356
+
357
+ self.detect_layer = self.model.model[-1]
358
+ self.model.traced = True
359
+
360
+ rand_example = torch.rand(1, 3, img_size, img_size)
361
+
362
+ traced_script_module = torch.jit.trace(self.model, rand_example, strict=False)
363
+ #traced_script_module = torch.jit.script(self.model)
364
+ traced_script_module.save("traced_model.pt")
365
+ print(" traced_script_module saved! ")
366
+ self.model = traced_script_module
367
+ self.model.to(device)
368
+ self.detect_layer.to(device)
369
+ print(" model is traced! \n")
370
+
371
+ def forward(self, x, augment=False, profile=False):
372
+ out = self.model(x)
373
+ out = self.detect_layer(out)
374
+ return out
yolov7detect/utils/wandb_logging/log_dataset.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import yaml
4
+
5
+ from yolov7.utils.wandb_logging.wandb_utils import WandbLogger
6
+
7
+ WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
8
+
9
+
10
+ def create_dataset_artifact(opt):
11
+ with open(opt.data) as f:
12
+ data = yaml.load(f, Loader=yaml.SafeLoader) # data dict
13
+ logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation')
14
+
15
+
16
+ if __name__ == '__main__':
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument('--data', type=str, default='data/coco.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='YOLOR', help='name of W&B Project')
21
+ opt = parser.parse_args()
22
+ opt.resume = False # Explicitly disallow resume check for dataset upload job
23
+
24
+ create_dataset_artifact(opt)
yolov7detect/utils/wandb_logging/wandb_utils.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ import yaml
7
+ from tqdm import tqdm
8
+
9
+ sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path
10
+ from yolov7.utils.datasets import LoadImagesAndLabels
11
+ from yolov7.utils.datasets import img2label_paths
12
+ from yolov7.utils.general import colorstr, xywh2xyxy, check_dataset
13
+
14
+ try:
15
+ import wandb
16
+ from wandb import init, finish
17
+ except ImportError:
18
+ wandb = None
19
+
20
+ WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
21
+
22
+
23
+ def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
24
+ return from_string[len(prefix):]
25
+
26
+
27
+ def check_wandb_config_file(data_config_file):
28
+ wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
29
+ if Path(wandb_config).is_file():
30
+ return wandb_config
31
+ return data_config_file
32
+
33
+
34
+ def get_run_info(run_path):
35
+ run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
36
+ run_id = run_path.stem
37
+ project = run_path.parent.stem
38
+ model_artifact_name = 'run_' + run_id + '_model'
39
+ return run_id, project, model_artifact_name
40
+
41
+
42
+ def check_wandb_resume(opt):
43
+ process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None
44
+ if isinstance(opt.resume, str):
45
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
46
+ if opt.global_rank not in [-1, 0]: # For resuming DDP runs
47
+ run_id, project, model_artifact_name = get_run_info(opt.resume)
48
+ api = wandb.Api()
49
+ artifact = api.artifact(project + '/' + model_artifact_name + ':latest')
50
+ modeldir = artifact.download()
51
+ opt.weights = str(Path(modeldir) / "last.pt")
52
+ return True
53
+ return None
54
+
55
+
56
+ def process_wandb_config_ddp_mode(opt):
57
+ with open(opt.data) as f:
58
+ data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict
59
+ train_dir, val_dir = None, None
60
+ if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
61
+ api = wandb.Api()
62
+ train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
63
+ train_dir = train_artifact.download()
64
+ train_path = Path(train_dir) / 'data/images/'
65
+ data_dict['train'] = str(train_path)
66
+
67
+ if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
68
+ api = wandb.Api()
69
+ val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
70
+ val_dir = val_artifact.download()
71
+ val_path = Path(val_dir) / 'data/images/'
72
+ data_dict['val'] = str(val_path)
73
+ if train_dir or val_dir:
74
+ ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
75
+ with open(ddp_data_path, 'w') as f:
76
+ yaml.dump(data_dict, f)
77
+ opt.data = ddp_data_path
78
+
79
+
80
+ class WandbLogger():
81
+ def __init__(self, opt, name, run_id, data_dict, job_type='Training'):
82
+ # Pre-training routine --
83
+ self.job_type = job_type
84
+ self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict
85
+ # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call
86
+ if isinstance(opt.resume, str): # checks resume from artifact
87
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
88
+ run_id, project, model_artifact_name = get_run_info(opt.resume)
89
+ model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
90
+ assert wandb, 'install wandb to resume wandb runs'
91
+ # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
92
+ self.wandb_run = wandb.init(id=run_id, project=project, resume='allow')
93
+ opt.resume = model_artifact_name
94
+ elif self.wandb:
95
+ self.wandb_run = wandb.init(config=opt,
96
+ resume="allow",
97
+ project='YOLOR' if opt.project == 'runs/train' else Path(opt.project).stem,
98
+ name=name,
99
+ job_type=job_type,
100
+ id=run_id) if not wandb.run else wandb.run
101
+ if self.wandb_run:
102
+ if self.job_type == 'Training':
103
+ if not opt.resume:
104
+ wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict
105
+ # Info useful for resuming from artifacts
106
+ self.wandb_run.config.opt = vars(opt)
107
+ self.wandb_run.config.data_dict = wandb_data_dict
108
+ self.data_dict = self.setup_training(opt, data_dict)
109
+ if self.job_type == 'Dataset Creation':
110
+ self.data_dict = self.check_and_upload_dataset(opt)
111
+ else:
112
+ prefix = colorstr('wandb: ')
113
+ print(f"{prefix}Install Weights & Biases for YOLOR logging with 'pip install wandb' (recommended)")
114
+
115
+ def check_and_upload_dataset(self, opt):
116
+ assert wandb, 'Install wandb to upload dataset'
117
+ check_dataset(self.data_dict)
118
+ config_path = self.log_dataset_artifact(opt.data,
119
+ opt.single_cls,
120
+ 'YOLOR' if opt.project == 'runs/train' else Path(opt.project).stem)
121
+ print("Created dataset config file ", config_path)
122
+ with open(config_path) as f:
123
+ wandb_data_dict = yaml.load(f, Loader=yaml.SafeLoader)
124
+ return wandb_data_dict
125
+
126
+ def setup_training(self, opt, data_dict):
127
+ self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants
128
+ self.bbox_interval = opt.bbox_interval
129
+ if isinstance(opt.resume, str):
130
+ modeldir, _ = self.download_model_artifact(opt)
131
+ if modeldir:
132
+ self.weights = Path(modeldir) / "last.pt"
133
+ config = self.wandb_run.config
134
+ opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
135
+ self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \
136
+ config.opt['hyp']
137
+ data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume
138
+ if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download
139
+ self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
140
+ opt.artifact_alias)
141
+ self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
142
+ opt.artifact_alias)
143
+ self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None
144
+ if self.train_artifact_path is not None:
145
+ train_path = Path(self.train_artifact_path) / 'data/images/'
146
+ data_dict['train'] = str(train_path)
147
+ if self.val_artifact_path is not None:
148
+ val_path = Path(self.val_artifact_path) / 'data/images/'
149
+ data_dict['val'] = str(val_path)
150
+ self.val_table = self.val_artifact.get("val")
151
+ self.map_val_table_path()
152
+ if self.val_artifact is not None:
153
+ self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
154
+ self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
155
+ if opt.bbox_interval == -1:
156
+ self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
157
+ return data_dict
158
+
159
+ def download_dataset_artifact(self, path, alias):
160
+ if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
161
+ dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
162
+ assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
163
+ datadir = dataset_artifact.download()
164
+ return datadir, dataset_artifact
165
+ return None, None
166
+
167
+ def download_model_artifact(self, opt):
168
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
169
+ model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
170
+ assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
171
+ modeldir = model_artifact.download()
172
+ epochs_trained = model_artifact.metadata.get('epochs_trained')
173
+ total_epochs = model_artifact.metadata.get('total_epochs')
174
+ assert epochs_trained < total_epochs, 'training to %g epochs is finished, nothing to resume.' % (
175
+ total_epochs)
176
+ return modeldir, model_artifact
177
+ return None, None
178
+
179
+ def log_model(self, path, opt, epoch, fitness_score, best_model=False):
180
+ model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
181
+ 'original_url': str(path),
182
+ 'epochs_trained': epoch + 1,
183
+ 'save period': opt.save_period,
184
+ 'project': opt.project,
185
+ 'total_epochs': opt.epochs,
186
+ 'fitness_score': fitness_score
187
+ })
188
+ model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
189
+ wandb.log_artifact(model_artifact,
190
+ aliases=['latest', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
191
+ print("Saving model artifact on epoch ", epoch + 1)
192
+
193
+ def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
194
+ with open(data_file) as f:
195
+ data = yaml.load(f, Loader=yaml.SafeLoader) # data dict
196
+ nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
197
+ names = {k: v for k, v in enumerate(names)} # to index dictionary
198
+ self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
199
+ data['train']), names, name='train') if data.get('train') else None
200
+ self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
201
+ data['val']), names, name='val') if data.get('val') else None
202
+ if data.get('train'):
203
+ data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
204
+ if data.get('val'):
205
+ data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
206
+ path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path
207
+ data.pop('download', None)
208
+ with open(path, 'w') as f:
209
+ yaml.dump(data, f)
210
+
211
+ if self.job_type == 'Training': # builds correct artifact pipeline graph
212
+ self.wandb_run.use_artifact(self.val_artifact)
213
+ self.wandb_run.use_artifact(self.train_artifact)
214
+ self.val_artifact.wait()
215
+ self.val_table = self.val_artifact.get('val')
216
+ self.map_val_table_path()
217
+ else:
218
+ self.wandb_run.log_artifact(self.train_artifact)
219
+ self.wandb_run.log_artifact(self.val_artifact)
220
+ return path
221
+
222
+ def map_val_table_path(self):
223
+ self.val_table_map = {}
224
+ print("Mapping dataset")
225
+ for i, data in enumerate(tqdm(self.val_table.data)):
226
+ self.val_table_map[data[3]] = data[0]
227
+
228
+ def create_dataset_table(self, dataset, class_to_id, name='dataset'):
229
+ # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
230
+ artifact = wandb.Artifact(name=name, type="dataset")
231
+ img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
232
+ img_files = tqdm(dataset.img_files) if not img_files else img_files
233
+ for img_file in img_files:
234
+ if Path(img_file).is_dir():
235
+ artifact.add_dir(img_file, name='data/images')
236
+ labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
237
+ artifact.add_dir(labels_path, name='data/labels')
238
+ else:
239
+ artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
240
+ label_file = Path(img2label_paths([img_file])[0])
241
+ artifact.add_file(str(label_file),
242
+ name='data/labels/' + label_file.name) if label_file.exists() else None
243
+ table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
244
+ class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
245
+ for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
246
+ height, width = shapes[0]
247
+ labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) * torch.Tensor([width, height, width, height])
248
+ box_data, img_classes = [], {}
249
+ for cls, *xyxy in labels[:, 1:].tolist():
250
+ cls = int(cls)
251
+ box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
252
+ "class_id": cls,
253
+ "box_caption": "%s" % (class_to_id[cls]),
254
+ "scores": {"acc": 1},
255
+ "domain": "pixel"})
256
+ img_classes[cls] = class_to_id[cls]
257
+ boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
258
+ table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes),
259
+ Path(paths).name)
260
+ artifact.add(table, name)
261
+ return artifact
262
+
263
+ def log_training_progress(self, predn, path, names):
264
+ if self.val_table and self.result_table:
265
+ class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
266
+ box_data = []
267
+ total_conf = 0
268
+ for *xyxy, conf, cls in predn.tolist():
269
+ if conf >= 0.25:
270
+ box_data.append(
271
+ {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
272
+ "class_id": int(cls),
273
+ "box_caption": "%s %.3f" % (names[cls], conf),
274
+ "scores": {"class_score": conf},
275
+ "domain": "pixel"})
276
+ total_conf = total_conf + conf
277
+ boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
278
+ id = self.val_table_map[Path(path).name]
279
+ self.result_table.add_data(self.current_epoch,
280
+ id,
281
+ wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
282
+ total_conf / max(1, len(box_data))
283
+ )
284
+
285
+ def log(self, log_dict):
286
+ if self.wandb_run:
287
+ for key, value in log_dict.items():
288
+ self.log_dict[key] = value
289
+
290
+ def end_epoch(self, best_result=False):
291
+ if self.wandb_run:
292
+ wandb.log(self.log_dict)
293
+ self.log_dict = {}
294
+ if self.result_artifact:
295
+ train_results = wandb.JoinedTable(self.val_table, self.result_table, "id")
296
+ self.result_artifact.add(train_results, 'result')
297
+ wandb.log_artifact(self.result_artifact, aliases=['latest', 'epoch ' + str(self.current_epoch),
298
+ ('best' if best_result else '')])
299
+ self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
300
+ self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
301
+
302
+ def finish_run(self):
303
+ if self.wandb_run:
304
+ if self.log_dict:
305
+ wandb.log(self.log_dict)
306
+ wandb.run.finish()