owaiskha9654 commited on
Commit
ed5e87a
1 Parent(s): e549ce4
Files changed (6) hide show
  1. detect.py +195 -0
  2. export.py +205 -0
  3. hubconf.py +97 -0
  4. scripts/get_coco.sh +22 -0
  5. test.py +347 -0
  6. train.py +702 -0
detect.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 models.experimental import attempt_load
11
+ from utils.datasets import LoadStreams, LoadImages
12
+ from 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 utils.plots import plot_one_box
15
+ from 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
+ pred = model(img, augment=opt.augment)[0]
88
+ t2 = time_synchronized()
89
+
90
+ # Apply NMS
91
+ pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
92
+ t3 = time_synchronized()
93
+
94
+ # Apply Classifier
95
+ if classify:
96
+ pred = apply_classifier(pred, modelc, img, im0s)
97
+
98
+ # Process detections
99
+ for i, det in enumerate(pred): # detections per image
100
+ if webcam: # batch_size >= 1
101
+ p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
102
+ else:
103
+ p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
104
+
105
+ p = Path(p) # to Path
106
+ save_path = str(save_dir / p.name) # img.jpg
107
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
108
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
109
+ if len(det):
110
+ # Rescale boxes from img_size to im0 size
111
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
112
+
113
+ # Print results
114
+ for c in det[:, -1].unique():
115
+ n = (det[:, -1] == c).sum() # detections per class
116
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
117
+
118
+ # Write results
119
+ for *xyxy, conf, cls in reversed(det):
120
+ if save_txt: # Write to file
121
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
122
+ line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
123
+ with open(txt_path + '.txt', 'a') as f:
124
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
125
+
126
+ if save_img or view_img: # Add bbox to image
127
+ label = f'{names[int(cls)]} {conf:.2f}'
128
+ plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
129
+
130
+ # Print time (inference + NMS)
131
+ print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
132
+
133
+ # Stream results
134
+ if view_img:
135
+ cv2.imshow(str(p), im0)
136
+ cv2.waitKey(1) # 1 millisecond
137
+
138
+ # Save results (image with detections)
139
+ if save_img:
140
+ if dataset.mode == 'image':
141
+ cv2.imwrite(save_path, im0)
142
+ print(f" The image with the result is saved in: {save_path}")
143
+ else: # 'video' or 'stream'
144
+ if vid_path != save_path: # new video
145
+ vid_path = save_path
146
+ if isinstance(vid_writer, cv2.VideoWriter):
147
+ vid_writer.release() # release previous video writer
148
+ if vid_cap: # video
149
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
150
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
151
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
152
+ else: # stream
153
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
154
+ save_path += '.mp4'
155
+ vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
156
+ vid_writer.write(im0)
157
+
158
+ if save_txt or save_img:
159
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
160
+ #print(f"Results saved to {save_dir}{s}")
161
+
162
+ print(f'Done. ({time.time() - t0:.3f}s)')
163
+
164
+
165
+ if __name__ == '__main__':
166
+ parser = argparse.ArgumentParser()
167
+ parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
168
+ parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
169
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
170
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
171
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
172
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
173
+ parser.add_argument('--view-img', action='store_true', help='display results')
174
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
175
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
176
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
177
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
178
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
179
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
180
+ parser.add_argument('--update', action='store_true', help='update all models')
181
+ parser.add_argument('--project', default='runs/detect', help='save results to project/name')
182
+ parser.add_argument('--name', default='exp', help='save results to project/name')
183
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
184
+ parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
185
+ opt = parser.parse_args()
186
+ print(opt)
187
+ #check_requirements(exclude=('pycocotools', 'thop'))
188
+
189
+ with torch.no_grad():
190
+ if opt.update: # update all models (to fix SourceChangeWarning)
191
+ for opt.weights in ['yolov7.pt']:
192
+ detect()
193
+ strip_optimizer(opt.weights)
194
+ else:
195
+ detect()
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 models.experimental import attempt_load, End2End
14
+ from utils.activations import Hardswish, SiLU
15
+ from utils.general import set_logging, check_img_size
16
+ from utils.torch_utils import select_device
17
+ from 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)
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))
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 models.yolo import Model
13
+ from utils.general import check_requirements, set_logging
14
+ from utils.google_utils import attempt_download
15
+ from 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()
scripts/get_coco.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # COCO 2017 dataset http://cocodataset.org
3
+ # Download command: bash ./scripts/get_coco.sh
4
+
5
+ # Download/unzip labels
6
+ d='./' # unzip directory
7
+ url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
8
+ f='coco2017labels-segments.zip' # or 'coco2017labels.zip', 68 MB
9
+ echo 'Downloading' $url$f ' ...'
10
+ curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
11
+
12
+ # Download/unzip images
13
+ d='./coco/images' # unzip directory
14
+ url=http://images.cocodataset.org/zips/
15
+ f1='train2017.zip' # 19G, 118k images
16
+ f2='val2017.zip' # 1G, 5k images
17
+ f3='test2017.zip' # 7G, 41k images (optional)
18
+ for f in $f1 $f2 $f3; do
19
+ echo 'Downloading' $url$f '...'
20
+ curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
21
+ done
22
+ wait # finish background tasks
test.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 models.experimental import attempt_load
13
+ from utils.datasets import create_dataloader
14
+ from 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 utils.metrics import ap_per_class, ConfusionMatrix
17
+ from utils.plots import plot_images, output_to_target, plot_study_txt
18
+ from 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
+ # Initialize/load model and set device
44
+ training = model is not None
45
+ if training: # called by train.py
46
+ device = next(model.parameters()).device # get model device
47
+
48
+ else: # called directly
49
+ set_logging()
50
+ device = select_device(opt.device, batch_size=batch_size)
51
+
52
+ # Directories
53
+ save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
54
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
55
+
56
+ # Load model
57
+ model = attempt_load(weights, map_location=device) # load FP32 model
58
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
59
+ imgsz = check_img_size(imgsz, s=gs) # check img_size
60
+
61
+ if trace:
62
+ model = TracedModel(model, device, opt.img_size)
63
+
64
+ # Half
65
+ half = device.type != 'cpu' and half_precision # half precision only supported on CUDA
66
+ if half:
67
+ model.half()
68
+
69
+ # Configure
70
+ model.eval()
71
+ if isinstance(data, str):
72
+ is_coco = data.endswith('coco.yaml')
73
+ with open(data) as f:
74
+ data = yaml.load(f, Loader=yaml.SafeLoader)
75
+ check_dataset(data) # check
76
+ nc = 1 if single_cls else int(data['nc']) # number of classes
77
+ iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
78
+ niou = iouv.numel()
79
+
80
+ # Logging
81
+ log_imgs = 0
82
+ if wandb_logger and wandb_logger.wandb:
83
+ log_imgs = min(wandb_logger.log_imgs, 100)
84
+ # Dataloader
85
+ if not training:
86
+ if device.type != 'cpu':
87
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
88
+ task = opt.task if opt.task in ('train', 'val', 'test') else 'val' # path to train/val/test images
89
+ dataloader = create_dataloader(data[task], imgsz, batch_size, gs, opt, pad=0.5, rect=True,
90
+ prefix=colorstr(f'{task}: '))[0]
91
+
92
+ seen = 0
93
+ confusion_matrix = ConfusionMatrix(nc=nc)
94
+ names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
95
+ coco91class = coco80_to_coco91_class()
96
+ s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
97
+ p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
98
+ loss = torch.zeros(3, device=device)
99
+ jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
100
+ for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
101
+ img = img.to(device, non_blocking=True)
102
+ img = img.half() if half else img.float() # uint8 to fp16/32
103
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
104
+ targets = targets.to(device)
105
+ nb, _, height, width = img.shape # batch size, channels, height, width
106
+
107
+ with torch.no_grad():
108
+ # Run model
109
+ t = time_synchronized()
110
+ out, train_out = model(img, augment=augment) # inference and training outputs
111
+ t0 += time_synchronized() - t
112
+
113
+ # Compute loss
114
+ if compute_loss:
115
+ loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls
116
+
117
+ # Run NMS
118
+ targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels
119
+ lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
120
+ t = time_synchronized()
121
+ out = non_max_suppression(out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb, multi_label=True)
122
+ t1 += time_synchronized() - t
123
+
124
+ # Statistics per image
125
+ for si, pred in enumerate(out):
126
+ labels = targets[targets[:, 0] == si, 1:]
127
+ nl = len(labels)
128
+ tcls = labels[:, 0].tolist() if nl else [] # target class
129
+ path = Path(paths[si])
130
+ seen += 1
131
+
132
+ if len(pred) == 0:
133
+ if nl:
134
+ stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
135
+ continue
136
+
137
+ # Predictions
138
+ predn = pred.clone()
139
+ scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred
140
+
141
+ # Append to text file
142
+ if save_txt:
143
+ gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
144
+ for *xyxy, conf, cls in predn.tolist():
145
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
146
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
147
+ with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:
148
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
149
+
150
+ # W&B logging - Media Panel Plots
151
+ if len(wandb_images) < log_imgs and wandb_logger.current_epoch > 0: # Check for test operation
152
+ if wandb_logger.current_epoch % wandb_logger.bbox_interval == 0:
153
+ box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
154
+ "class_id": int(cls),
155
+ "box_caption": "%s %.3f" % (names[cls], conf),
156
+ "scores": {"class_score": conf},
157
+ "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
158
+ boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
159
+ wandb_images.append(wandb_logger.wandb.Image(img[si], boxes=boxes, caption=path.name))
160
+ wandb_logger.log_training_progress(predn, path, names) if wandb_logger and wandb_logger.wandb_run else None
161
+
162
+ # Append to pycocotools JSON dictionary
163
+ if save_json:
164
+ # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
165
+ image_id = int(path.stem) if path.stem.isnumeric() else path.stem
166
+ box = xyxy2xywh(predn[:, :4]) # xywh
167
+ box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
168
+ for p, b in zip(pred.tolist(), box.tolist()):
169
+ jdict.append({'image_id': image_id,
170
+ 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
171
+ 'bbox': [round(x, 3) for x in b],
172
+ 'score': round(p[4], 5)})
173
+
174
+ # Assign all predictions as incorrect
175
+ correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
176
+ if nl:
177
+ detected = [] # target indices
178
+ tcls_tensor = labels[:, 0]
179
+
180
+ # target boxes
181
+ tbox = xywh2xyxy(labels[:, 1:5])
182
+ scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels
183
+ if plots:
184
+ confusion_matrix.process_batch(predn, torch.cat((labels[:, 0:1], tbox), 1))
185
+
186
+ # Per target class
187
+ for cls in torch.unique(tcls_tensor):
188
+ ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices
189
+ pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices
190
+
191
+ # Search for detections
192
+ if pi.shape[0]:
193
+ # Prediction to target ious
194
+ ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices
195
+
196
+ # Append detections
197
+ detected_set = set()
198
+ for j in (ious > iouv[0]).nonzero(as_tuple=False):
199
+ d = ti[i[j]] # detected target
200
+ if d.item() not in detected_set:
201
+ detected_set.add(d.item())
202
+ detected.append(d)
203
+ correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
204
+ if len(detected) == nl: # all targets already located in image
205
+ break
206
+
207
+ # Append statistics (correct, conf, pcls, tcls)
208
+ stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
209
+
210
+ # Plot images
211
+ if plots and batch_i < 3:
212
+ f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels
213
+ Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()
214
+ f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions
215
+ Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start()
216
+
217
+ # Compute statistics
218
+ stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
219
+ if len(stats) and stats[0].any():
220
+ p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
221
+ ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
222
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
223
+ nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
224
+ else:
225
+ nt = torch.zeros(1)
226
+
227
+ # Print results
228
+ pf = '%20s' + '%12i' * 2 + '%12.3g' * 4 # print format
229
+ print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
230
+
231
+ # Print results per class
232
+ if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
233
+ for i, c in enumerate(ap_class):
234
+ print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
235
+
236
+ # Print speeds
237
+ t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
238
+ if not training:
239
+ print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
240
+
241
+ # Plots
242
+ if plots:
243
+ confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
244
+ if wandb_logger and wandb_logger.wandb:
245
+ val_batches = [wandb_logger.wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]
246
+ wandb_logger.log({"Validation": val_batches})
247
+ if wandb_images:
248
+ wandb_logger.log({"Bounding Box Debugger/Images": wandb_images})
249
+
250
+ # Save JSON
251
+ if save_json and len(jdict):
252
+ w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
253
+ anno_json = '../coco/annotations/instances_val2017.json' # annotations json
254
+ pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
255
+ print('\nEvaluating pycocotools mAP... saving %s...' % pred_json)
256
+ with open(pred_json, 'w') as f:
257
+ json.dump(jdict, f)
258
+
259
+ try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
260
+ from pycocotools.coco import COCO
261
+ from pycocotools.cocoeval import COCOeval
262
+
263
+ anno = COCO(anno_json) # init annotations api
264
+ pred = anno.loadRes(pred_json) # init predictions api
265
+ eval = COCOeval(anno, pred, 'bbox')
266
+ if is_coco:
267
+ eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate
268
+ eval.evaluate()
269
+ eval.accumulate()
270
+ eval.summarize()
271
+ map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
272
+ except Exception as e:
273
+ print(f'pycocotools unable to run: {e}')
274
+
275
+ # Return results
276
+ model.float() # for training
277
+ if not training:
278
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
279
+ print(f"Results saved to {save_dir}{s}")
280
+ maps = np.zeros(nc) + map
281
+ for i, c in enumerate(ap_class):
282
+ maps[c] = ap[i]
283
+ return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
284
+
285
+
286
+ if __name__ == '__main__':
287
+ parser = argparse.ArgumentParser(prog='test.py')
288
+ parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
289
+ parser.add_argument('--data', type=str, default='data/coco.yaml', help='*.data path')
290
+ parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
291
+ parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
292
+ parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
293
+ parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS')
294
+ parser.add_argument('--task', default='val', help='train, val, test, speed or study')
295
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
296
+ parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
297
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
298
+ parser.add_argument('--verbose', action='store_true', help='report mAP by class')
299
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
300
+ parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
301
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
302
+ parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
303
+ parser.add_argument('--project', default='runs/test', help='save to project/name')
304
+ parser.add_argument('--name', default='exp', help='save to project/name')
305
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
306
+ parser.add_argument('--trace', action='store_true', help='trace model')
307
+ opt = parser.parse_args()
308
+ opt.save_json |= opt.data.endswith('coco.yaml')
309
+ opt.data = check_file(opt.data) # check file
310
+ print(opt)
311
+ #check_requirements()
312
+
313
+ if opt.task in ('train', 'val', 'test'): # run normally
314
+ test(opt.data,
315
+ opt.weights,
316
+ opt.batch_size,
317
+ opt.img_size,
318
+ opt.conf_thres,
319
+ opt.iou_thres,
320
+ opt.save_json,
321
+ opt.single_cls,
322
+ opt.augment,
323
+ opt.verbose,
324
+ save_txt=opt.save_txt | opt.save_hybrid,
325
+ save_hybrid=opt.save_hybrid,
326
+ save_conf=opt.save_conf,
327
+ trace=opt.trace,
328
+ )
329
+
330
+ elif opt.task == 'speed': # speed benchmarks
331
+ for w in opt.weights:
332
+ test(opt.data, w, opt.batch_size, opt.img_size, 0.25, 0.45, save_json=False, plots=False)
333
+
334
+ elif opt.task == 'study': # run over a range of settings and save/plot
335
+ # python test.py --task study --data coco.yaml --iou 0.65 --weights yolov7.pt
336
+ x = list(range(256, 1536 + 128, 128)) # x axis (image sizes)
337
+ for w in opt.weights:
338
+ f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to
339
+ y = [] # y axis
340
+ for i in x: # img-size
341
+ print(f'\nRunning {f} point {i}...')
342
+ r, _, t = test(opt.data, w, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,
343
+ plots=False)
344
+ y.append(r + t) # results and times
345
+ np.savetxt(f, y, fmt='%10.4g') # save
346
+ os.system('zip -r study.zip study_*.txt')
347
+ plot_study_txt(x=x) # plot
train.py ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 models.experimental import attempt_load
26
+ from models.yolo import Model
27
+ from utils.autoanchor import check_anchors
28
+ from utils.datasets import create_dataloader
29
+ from 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 utils.google_utils import attempt_download
33
+ from utils.loss import ComputeLoss, ComputeLossOTA
34
+ from utils.plots import plot_images, plot_labels, plot_results, plot_evolution
35
+ from utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first, is_parallel
36
+ from 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, mAP@.5, mAP@.5-.95, 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 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
+
428
+ # Write
429
+ with open(results_file, 'a') as f:
430
+ f.write(s + '%10.4g' * 7 % results + '\n') # append metrics, val_loss
431
+ if len(opt.name) and opt.bucket:
432
+ os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name))
433
+
434
+ # Log
435
+ tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
436
+ 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
437
+ 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
438
+ 'x/lr0', 'x/lr1', 'x/lr2'] # params
439
+ for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags):
440
+ if tb_writer:
441
+ tb_writer.add_scalar(tag, x, epoch) # tensorboard
442
+ if wandb_logger.wandb:
443
+ wandb_logger.log({tag: x}) # W&B
444
+
445
+ # Update best mAP
446
+ fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
447
+ if fi > best_fitness:
448
+ best_fitness = fi
449
+ wandb_logger.end_epoch(best_result=best_fitness == fi)
450
+
451
+ # Save model
452
+ if (not opt.nosave) or (final_epoch and not opt.evolve): # if save
453
+ ckpt = {'epoch': epoch,
454
+ 'best_fitness': best_fitness,
455
+ 'training_results': results_file.read_text(),
456
+ 'model': deepcopy(model.module if is_parallel(model) else model).half(),
457
+ 'ema': deepcopy(ema.ema).half(),
458
+ 'updates': ema.updates,
459
+ 'optimizer': optimizer.state_dict(),
460
+ 'wandb_id': wandb_logger.wandb_run.id if wandb_logger.wandb else None}
461
+
462
+ # Save last, best and delete
463
+ torch.save(ckpt, last)
464
+ if best_fitness == fi:
465
+ torch.save(ckpt, best)
466
+ if (best_fitness == fi) and (epoch >= 200):
467
+ torch.save(ckpt, wdir / 'best_{:03d}.pt'.format(epoch))
468
+ if epoch == 0:
469
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
470
+ elif ((epoch+1) % 25) == 0:
471
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
472
+ elif epoch >= (epochs-5):
473
+ torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch))
474
+ if wandb_logger.wandb:
475
+ if ((epoch + 1) % opt.save_period == 0 and not final_epoch) and opt.save_period != -1:
476
+ wandb_logger.log_model(
477
+ last.parent, opt, epoch, fi, best_model=best_fitness == fi)
478
+ del ckpt
479
+
480
+ # end epoch ----------------------------------------------------------------------------------------------------
481
+ # end training
482
+ if rank in [-1, 0]:
483
+ # Plots
484
+ if plots:
485
+ plot_results(save_dir=save_dir) # save as results.png
486
+ if wandb_logger.wandb:
487
+ files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]]
488
+ wandb_logger.log({"Results": [wandb_logger.wandb.Image(str(save_dir / f), caption=f) for f in files
489
+ if (save_dir / f).exists()]})
490
+ # Test best.pt
491
+ logger.info('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
492
+ if opt.data.endswith('coco.yaml') and nc == 80: # if COCO
493
+ for m in (last, best) if best.exists() else (last): # speed, mAP tests
494
+ results, _, _ = test.test(opt.data,
495
+ batch_size=batch_size * 2,
496
+ imgsz=imgsz_test,
497
+ conf_thres=0.001,
498
+ iou_thres=0.7,
499
+ model=attempt_load(m, device).half(),
500
+ single_cls=opt.single_cls,
501
+ dataloader=testloader,
502
+ save_dir=save_dir,
503
+ save_json=True,
504
+ plots=False,
505
+ is_coco=is_coco)
506
+
507
+ # Strip optimizers
508
+ final = best if best.exists() else last # final model
509
+ for f in last, best:
510
+ if f.exists():
511
+ strip_optimizer(f) # strip optimizers
512
+ if opt.bucket:
513
+ os.system(f'gsutil cp {final} gs://{opt.bucket}/weights') # upload
514
+ if wandb_logger.wandb and not opt.evolve: # Log the stripped model
515
+ wandb_logger.wandb.log_artifact(str(final), type='model',
516
+ name='run_' + wandb_logger.wandb_run.id + '_model',
517
+ aliases=['last', 'best', 'stripped'])
518
+ wandb_logger.finish_run()
519
+ else:
520
+ dist.destroy_process_group()
521
+ torch.cuda.empty_cache()
522
+ return results
523
+
524
+
525
+ if __name__ == '__main__':
526
+ parser = argparse.ArgumentParser()
527
+ parser.add_argument('--weights', type=str, default='yolo7.pt', help='initial weights path')
528
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
529
+ parser.add_argument('--data', type=str, default='data/coco.yaml', help='data.yaml path')
530
+ parser.add_argument('--hyp', type=str, default='data/hyp.scratch.p5.yaml', help='hyperparameters path')
531
+ parser.add_argument('--epochs', type=int, default=300)
532
+ parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
533
+ parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
534
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
535
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
536
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
537
+ parser.add_argument('--notest', action='store_true', help='only test final epoch')
538
+ parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
539
+ parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
540
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
541
+ parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
542
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
543
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
544
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
545
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
546
+ parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
547
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
548
+ parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
549
+ parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers')
550
+ parser.add_argument('--project', default='runs/train', help='save to project/name')
551
+ parser.add_argument('--entity', default=None, help='W&B entity')
552
+ parser.add_argument('--name', default='exp', help='save to project/name')
553
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
554
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
555
+ parser.add_argument('--linear-lr', action='store_true', help='linear LR')
556
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
557
+ parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table')
558
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B')
559
+ parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch')
560
+ parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used')
561
+ parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone of yolov7=50, first3=0 1 2')
562
+ opt = parser.parse_args()
563
+
564
+ # Set DDP variables
565
+ opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1
566
+ opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1
567
+ set_logging(opt.global_rank)
568
+ #if opt.global_rank in [-1, 0]:
569
+ # check_git_status()
570
+ # check_requirements()
571
+
572
+ # Resume
573
+ wandb_run = check_wandb_resume(opt)
574
+ if opt.resume and not wandb_run: # resume an interrupted run
575
+ ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
576
+ assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
577
+ apriori = opt.global_rank, opt.local_rank
578
+ with open(Path(ckpt).parent.parent / 'opt.yaml') as f:
579
+ opt = argparse.Namespace(**yaml.load(f, Loader=yaml.SafeLoader)) # replace
580
+ opt.cfg, opt.weights, opt.resume, opt.batch_size, opt.global_rank, opt.local_rank = '', ckpt, True, opt.total_batch_size, *apriori # reinstate
581
+ logger.info('Resuming training from %s' % ckpt)
582
+ else:
583
+ # opt.hyp = opt.hyp or ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml')
584
+ opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
585
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
586
+ opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
587
+ opt.name = 'evolve' if opt.evolve else opt.name
588
+ opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve) # increment run
589
+
590
+ # DDP mode
591
+ opt.total_batch_size = opt.batch_size
592
+ device = select_device(opt.device, batch_size=opt.batch_size)
593
+ if opt.local_rank != -1:
594
+ assert torch.cuda.device_count() > opt.local_rank
595
+ torch.cuda.set_device(opt.local_rank)
596
+ device = torch.device('cuda', opt.local_rank)
597
+ dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
598
+ assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count'
599
+ opt.batch_size = opt.total_batch_size // opt.world_size
600
+
601
+ # Hyperparameters
602
+ with open(opt.hyp) as f:
603
+ hyp = yaml.load(f, Loader=yaml.SafeLoader) # load hyps
604
+
605
+ # Train
606
+ logger.info(opt)
607
+ if not opt.evolve:
608
+ tb_writer = None # init loggers
609
+ if opt.global_rank in [-1, 0]:
610
+ prefix = colorstr('tensorboard: ')
611
+ logger.info(f"{prefix}Start with 'tensorboard --logdir {opt.project}', view at http://localhost:6006/")
612
+ tb_writer = SummaryWriter(opt.save_dir) # Tensorboard
613
+ train(hyp, opt, device, tb_writer)
614
+
615
+ # Evolve hyperparameters (optional)
616
+ else:
617
+ # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
618
+ meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
619
+ 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
620
+ 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
621
+ 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
622
+ 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
623
+ 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
624
+ 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
625
+ 'box': (1, 0.02, 0.2), # box loss gain
626
+ 'cls': (1, 0.2, 4.0), # cls loss gain
627
+ 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
628
+ 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
629
+ 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
630
+ 'iou_t': (0, 0.1, 0.7), # IoU training threshold
631
+ 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
632
+ 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
633
+ 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
634
+ 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
635
+ 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
636
+ 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
637
+ 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
638
+ 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
639
+ 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
640
+ 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
641
+ 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
642
+ 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
643
+ 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
644
+ 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
645
+ 'mixup': (1, 0.0, 1.0), # image mixup (probability)
646
+ 'copy_paste': (1, 0.0, 1.0), # segment copy-paste (probability)
647
+ 'paste_in': (1, 0.0, 1.0)} # segment copy-paste (probability)
648
+
649
+ with open(opt.hyp, errors='ignore') as f:
650
+ hyp = yaml.safe_load(f) # load hyps dict
651
+ if 'anchors' not in hyp: # anchors commented in hyp.yaml
652
+ hyp['anchors'] = 3
653
+
654
+ assert opt.local_rank == -1, 'DDP mode not implemented for --evolve'
655
+ opt.notest, opt.nosave = True, True # only test/save final epoch
656
+ # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
657
+ yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here
658
+ if opt.bucket:
659
+ os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
660
+
661
+ for _ in range(300): # generations to evolve
662
+ if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate
663
+ # Select parent(s)
664
+ parent = 'single' # parent selection method: 'single' or 'weighted'
665
+ x = np.loadtxt('evolve.txt', ndmin=2)
666
+ n = min(5, len(x)) # number of previous results to consider
667
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
668
+ w = fitness(x) - fitness(x).min() # weights
669
+ if parent == 'single' or len(x) == 1:
670
+ # x = x[random.randint(0, n - 1)] # random selection
671
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
672
+ elif parent == 'weighted':
673
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
674
+
675
+ # Mutate
676
+ mp, s = 0.8, 0.2 # mutation probability, sigma
677
+ npr = np.random
678
+ npr.seed(int(time.time()))
679
+ g = np.array([x[0] for x in meta.values()]) # gains 0-1
680
+ ng = len(meta)
681
+ v = np.ones(ng)
682
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
683
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
684
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
685
+ hyp[k] = float(x[i + 7] * v[i]) # mutate
686
+
687
+ # Constrain to limits
688
+ for k, v in meta.items():
689
+ hyp[k] = max(hyp[k], v[1]) # lower limit
690
+ hyp[k] = min(hyp[k], v[2]) # upper limit
691
+ hyp[k] = round(hyp[k], 5) # significant digits
692
+
693
+ # Train mutation
694
+ results = train(hyp.copy(), opt, device)
695
+
696
+ # Write mutation results
697
+ print_mutation(hyp.copy(), results, yaml_file, opt.bucket)
698
+
699
+ # Plot results
700
+ plot_evolution(yaml_file)
701
+ print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n'
702
+ f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}')