Nada2001 commited on
Commit
f9fd0e3
·
1 Parent(s): cf8e6ae

Upload 9 files

Browse files
Files changed (9) hide show
  1. .pre-commit-config.yaml +69 -0
  2. CITATION.cff +14 -0
  3. CONTRIBUTING.md +93 -0
  4. benchmarks.py +169 -0
  5. detect.py +261 -0
  6. export.py +818 -0
  7. hubconf.py +169 -0
  8. train.py +640 -0
  9. val.py +409 -0
.pre-commit-config.yaml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ultralytics YOLO 🚀, AGPL-3.0 license
2
+ # Pre-commit hooks. For more information see https://github.com/pre-commit/pre-commit-hooks/blob/main/README.md
3
+
4
+ exclude: 'docs/'
5
+ # Define bot property if installed via https://github.com/marketplace/pre-commit-ci
6
+ ci:
7
+ autofix_prs: true
8
+ autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
9
+ autoupdate_schedule: monthly
10
+ # submodules: true
11
+
12
+ repos:
13
+ - repo: https://github.com/pre-commit/pre-commit-hooks
14
+ rev: v4.4.0
15
+ hooks:
16
+ - id: end-of-file-fixer
17
+ - id: trailing-whitespace
18
+ - id: check-case-conflict
19
+ - id: check-yaml
20
+ - id: check-docstring-first
21
+ - id: double-quote-string-fixer
22
+ - id: detect-private-key
23
+
24
+ - repo: https://github.com/asottile/pyupgrade
25
+ rev: v3.3.1
26
+ hooks:
27
+ - id: pyupgrade
28
+ name: Upgrade code
29
+ args: [--py37-plus]
30
+
31
+ - repo: https://github.com/PyCQA/isort
32
+ rev: 5.12.0
33
+ hooks:
34
+ - id: isort
35
+ name: Sort imports
36
+
37
+ - repo: https://github.com/google/yapf
38
+ rev: v0.32.0
39
+ hooks:
40
+ - id: yapf
41
+ name: YAPF formatting
42
+
43
+ - repo: https://github.com/executablebooks/mdformat
44
+ rev: 0.7.16
45
+ hooks:
46
+ - id: mdformat
47
+ name: MD formatting
48
+ additional_dependencies:
49
+ - mdformat-gfm
50
+ - mdformat-black
51
+ # exclude: "README.md|README.zh-CN.md|CONTRIBUTING.md"
52
+
53
+ - repo: https://github.com/PyCQA/flake8
54
+ rev: 6.0.0
55
+ hooks:
56
+ - id: flake8
57
+ name: PEP8
58
+
59
+ - repo: https://github.com/codespell-project/codespell
60
+ rev: v2.2.4
61
+ hooks:
62
+ - id: codespell
63
+ args:
64
+ - --ignore-words-list=crate,nd,strack,dota
65
+
66
+ #- repo: https://github.com/asottile/yesqa
67
+ # rev: v1.4.0
68
+ # hooks:
69
+ # - id: yesqa
CITATION.cff ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ preferred-citation:
3
+ type: software
4
+ message: If you use YOLOv5, please cite it as below.
5
+ authors:
6
+ - family-names: Jocher
7
+ given-names: Glenn
8
+ orcid: "https://orcid.org/0000-0001-5950-6979"
9
+ title: "YOLOv5 by Ultralytics"
10
+ version: 7.0
11
+ doi: 10.5281/zenodo.3908559
12
+ date-released: 2020-5-29
13
+ license: AGPL-3.0
14
+ url: "https://github.com/ultralytics/yolov5"
CONTRIBUTING.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Contributing to YOLOv5 🚀
2
+
3
+ We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's:
4
+
5
+ - Reporting a bug
6
+ - Discussing the current state of the code
7
+ - Submitting a fix
8
+ - Proposing a new feature
9
+ - Becoming a maintainer
10
+
11
+ YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be
12
+ helping push the frontiers of what's possible in AI 😃!
13
+
14
+ ## Submitting a Pull Request (PR) 🛠️
15
+
16
+ Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
17
+
18
+ ### 1. Select File to Update
19
+
20
+ Select `requirements.txt` to update by clicking on it in GitHub.
21
+
22
+ <p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
23
+
24
+ ### 2. Click 'Edit this file'
25
+
26
+ The button is in the top-right corner.
27
+
28
+ <p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
29
+
30
+ ### 3. Make Changes
31
+
32
+ Change the `matplotlib` version from `3.2.2` to `3.3`.
33
+
34
+ <p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
35
+
36
+ ### 4. Preview Changes and Submit PR
37
+
38
+ Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**
39
+ for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose
40
+ changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃!
41
+
42
+ <p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
43
+
44
+ ### PR recommendations
45
+
46
+ To allow your work to be integrated as seamlessly as possible, we advise you to:
47
+
48
+ - ✅ Verify your PR is **up-to-date** with `ultralytics/yolov5` `master` branch. If your PR is behind you can update
49
+ your code by clicking the 'Update branch' button or by running `git pull` and `git merge master` locally.
50
+
51
+ <p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 15" src="https://user-images.githubusercontent.com/26833433/187295893-50ed9f44-b2c9-4138-a614-de69bd1753d7.png"></p>
52
+
53
+ - ✅ Verify all YOLOv5 Continuous Integration (CI) **checks are passing**.
54
+
55
+ <p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 03" src="https://user-images.githubusercontent.com/26833433/187296922-545c5498-f64a-4d8c-8300-5fa764360da6.png"></p>
56
+
57
+ - ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase
58
+ but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
59
+
60
+ ## Submitting a Bug Report 🐛
61
+
62
+ If you spot a problem with YOLOv5 please submit a Bug Report!
63
+
64
+ For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few
65
+ short guidelines below to help users provide what we need to get started.
66
+
67
+ When asking a question, people will be better able to provide help if you provide **code** that they can easily
68
+ understand and use to **reproduce** the problem. This is referred to by community members as creating
69
+ a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces
70
+ the problem should be:
71
+
72
+ - ✅ **Minimal** – Use as little code as possible that still produces the same problem
73
+ - ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself
74
+ - ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem
75
+
76
+ In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code
77
+ should be:
78
+
79
+ - ✅ **Current** – Verify that your code is up-to-date with the current
80
+ GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new
81
+ copy to ensure your problem has not already been resolved by previous commits.
82
+ - ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this
83
+ repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.
84
+
85
+ If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛
86
+ **Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and provide
87
+ a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better
88
+ understand and diagnose your problem.
89
+
90
+ ## License
91
+
92
+ By contributing, you agree that your contributions will be licensed under
93
+ the [AGPL-3.0 license](https://choosealicense.com/licenses/agpl-3.0/)
benchmarks.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
+ """
3
+ Run YOLOv5 benchmarks on all supported export formats
4
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+
19
+ Requirements:
20
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
22
+ $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
23
+
24
+ Usage:
25
+ $ python benchmarks.py --weights yolov5s.pt --img 640
26
+ """
27
+
28
+ import argparse
29
+ import platform
30
+ import sys
31
+ import time
32
+ from pathlib import Path
33
+
34
+ import pandas as pd
35
+
36
+ FILE = Path(__file__).resolve()
37
+ ROOT = FILE.parents[0] # YOLOv5 root directory
38
+ if str(ROOT) not in sys.path:
39
+ sys.path.append(str(ROOT)) # add ROOT to PATH
40
+ # ROOT = ROOT.relative_to(Path.cwd()) # relative
41
+
42
+ import export
43
+ from models.experimental import attempt_load
44
+ from models.yolo import SegmentationModel
45
+ from segment.val import run as val_seg
46
+ from utils import notebook_init
47
+ from utils.general import LOGGER, check_yaml, file_size, print_args
48
+ from utils.torch_utils import select_device
49
+ from val import run as val_det
50
+
51
+
52
+ def run(
53
+ weights=ROOT / 'yolov5s.pt', # weights path
54
+ imgsz=640, # inference size (pixels)
55
+ batch_size=1, # batch size
56
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
57
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
58
+ half=False, # use FP16 half-precision inference
59
+ test=False, # test exports only
60
+ pt_only=False, # test PyTorch only
61
+ hard_fail=False, # throw error on benchmark failure
62
+ ):
63
+ y, t = [], time.time()
64
+ device = select_device(device)
65
+ model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
66
+ for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
67
+ try:
68
+ assert i not in (9, 10), 'inference not supported' # Edge TPU and TF.js are unsupported
69
+ assert i != 5 or platform.system() == 'Darwin', 'inference only supported on macOS>=10.13' # CoreML
70
+ if 'cpu' in device.type:
71
+ assert cpu, 'inference not supported on CPU'
72
+ if 'cuda' in device.type:
73
+ assert gpu, 'inference not supported on GPU'
74
+
75
+ # Export
76
+ if f == '-':
77
+ w = weights # PyTorch format
78
+ else:
79
+ w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others
80
+ assert suffix in str(w), 'export failed'
81
+
82
+ # Validate
83
+ if model_type == SegmentationModel:
84
+ result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task='speed', half=half)
85
+ metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
86
+ else: # DetectionModel:
87
+ result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task='speed', half=half)
88
+ metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
89
+ speed = result[2][1] # times (preprocess, inference, postprocess)
90
+ y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
91
+ except Exception as e:
92
+ if hard_fail:
93
+ assert type(e) is AssertionError, f'Benchmark --hard-fail for {name}: {e}'
94
+ LOGGER.warning(f'WARNING ⚠️ Benchmark failure for {name}: {e}')
95
+ y.append([name, None, None, None]) # mAP, t_inference
96
+ if pt_only and i == 0:
97
+ break # break after PyTorch
98
+
99
+ # Print results
100
+ LOGGER.info('\n')
101
+ parse_opt()
102
+ notebook_init() # print system info
103
+ c = ['Format', 'Size (MB)', 'mAP50-95', 'Inference time (ms)'] if map else ['Format', 'Export', '', '']
104
+ py = pd.DataFrame(y, columns=c)
105
+ LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)')
106
+ LOGGER.info(str(py if map else py.iloc[:, :2]))
107
+ if hard_fail and isinstance(hard_fail, str):
108
+ metrics = py['mAP50-95'].array # values to compare to floor
109
+ floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
110
+ assert all(x > floor for x in metrics if pd.notna(x)), f'HARD FAIL: mAP50-95 < floor {floor}'
111
+ return py
112
+
113
+
114
+ def test(
115
+ weights=ROOT / 'yolov5s.pt', # weights path
116
+ imgsz=640, # inference size (pixels)
117
+ batch_size=1, # batch size
118
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
119
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
120
+ half=False, # use FP16 half-precision inference
121
+ test=False, # test exports only
122
+ pt_only=False, # test PyTorch only
123
+ hard_fail=False, # throw error on benchmark failure
124
+ ):
125
+ y, t = [], time.time()
126
+ device = select_device(device)
127
+ for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
128
+ try:
129
+ w = weights if f == '-' else \
130
+ export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # weights
131
+ assert suffix in str(w), 'export failed'
132
+ y.append([name, True])
133
+ except Exception:
134
+ y.append([name, False]) # mAP, t_inference
135
+
136
+ # Print results
137
+ LOGGER.info('\n')
138
+ parse_opt()
139
+ notebook_init() # print system info
140
+ py = pd.DataFrame(y, columns=['Format', 'Export'])
141
+ LOGGER.info(f'\nExports complete ({time.time() - t:.2f}s)')
142
+ LOGGER.info(str(py))
143
+ return py
144
+
145
+
146
+ def parse_opt():
147
+ parser = argparse.ArgumentParser()
148
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
149
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
150
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
151
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
152
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
153
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
154
+ parser.add_argument('--test', action='store_true', help='test exports only')
155
+ parser.add_argument('--pt-only', action='store_true', help='test PyTorch only')
156
+ parser.add_argument('--hard-fail', nargs='?', const=True, default=False, help='Exception on error or < min metric')
157
+ opt = parser.parse_args()
158
+ opt.data = check_yaml(opt.data) # check YAML
159
+ print_args(vars(opt))
160
+ return opt
161
+
162
+
163
+ def main(opt):
164
+ test(**vars(opt)) if opt.test else run(**vars(opt))
165
+
166
+
167
+ if __name__ == '__main__':
168
+ opt = parse_opt()
169
+ main(opt)
detect.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
+ """
3
+ Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
4
+
5
+ Usage - sources:
6
+ $ python detect.py --weights yolov5s.pt --source 0 # webcam
7
+ img.jpg # image
8
+ vid.mp4 # video
9
+ screen # screenshot
10
+ path/ # directory
11
+ list.txt # list of images
12
+ list.streams # list of streams
13
+ 'path/*.jpg' # glob
14
+ 'https://youtu.be/Zgi9g1ksQHc' # YouTube
15
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
16
+
17
+ Usage - formats:
18
+ $ python detect.py --weights yolov5s.pt # PyTorch
19
+ yolov5s.torchscript # TorchScript
20
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
21
+ yolov5s_openvino_model # OpenVINO
22
+ yolov5s.engine # TensorRT
23
+ yolov5s.mlmodel # CoreML (macOS-only)
24
+ yolov5s_saved_model # TensorFlow SavedModel
25
+ yolov5s.pb # TensorFlow GraphDef
26
+ yolov5s.tflite # TensorFlow Lite
27
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
28
+ yolov5s_paddle_model # PaddlePaddle
29
+ """
30
+
31
+ import argparse
32
+ import os
33
+ import platform
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ import torch
38
+
39
+ FILE = Path(__file__).resolve()
40
+ ROOT = FILE.parents[0] # YOLOv5 root directory
41
+ if str(ROOT) not in sys.path:
42
+ sys.path.append(str(ROOT)) # add ROOT to PATH
43
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
44
+
45
+ from models.common import DetectMultiBackend
46
+ from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
47
+ from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
48
+ increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)
49
+ from utils.plots import Annotator, colors, save_one_box
50
+ from utils.torch_utils import select_device, smart_inference_mode
51
+
52
+
53
+ @smart_inference_mode()
54
+ def run(
55
+ weights=ROOT / 'yolov5s.pt', # model path or triton URL
56
+ source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam)
57
+ data=ROOT / 'data/coco128.yaml', # dataset.yaml path
58
+ imgsz=(640, 640), # inference size (height, width)
59
+ conf_thres=0.25, # confidence threshold
60
+ iou_thres=0.45, # NMS IOU threshold
61
+ max_det=1000, # maximum detections per image
62
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
63
+ view_img=False, # show results
64
+ save_txt=False, # save results to *.txt
65
+ save_conf=False, # save confidences in --save-txt labels
66
+ save_crop=False, # save cropped prediction boxes
67
+ nosave=False, # do not save images/videos
68
+ classes=None, # filter by class: --class 0, or --class 0 2 3
69
+ agnostic_nms=False, # class-agnostic NMS
70
+ augment=False, # augmented inference
71
+ visualize=False, # visualize features
72
+ update=False, # update all models
73
+ project=ROOT / 'runs/detect', # save results to project/name
74
+ name='exp', # save results to project/name
75
+ exist_ok=False, # existing project/name ok, do not increment
76
+ line_thickness=3, # bounding box thickness (pixels)
77
+ hide_labels=False, # hide labels
78
+ hide_conf=False, # hide confidences
79
+ half=False, # use FP16 half-precision inference
80
+ dnn=False, # use OpenCV DNN for ONNX inference
81
+ vid_stride=1, # video frame-rate stride
82
+ ):
83
+ source = str(source)
84
+ save_img = not nosave and not source.endswith('.txt') # save inference images
85
+ is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
86
+ is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
87
+ webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
88
+ screenshot = source.lower().startswith('screen')
89
+ if is_url and is_file:
90
+ source = check_file(source) # download
91
+
92
+ # Directories
93
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
94
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
95
+
96
+ # Load model
97
+ device = select_device(device)
98
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
99
+ stride, names, pt = model.stride, model.names, model.pt
100
+ imgsz = check_img_size(imgsz, s=stride) # check image size
101
+
102
+ # Dataloader
103
+ bs = 1 # batch_size
104
+ if webcam:
105
+ view_img = check_imshow(warn=True)
106
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
107
+ bs = len(dataset)
108
+ elif screenshot:
109
+ dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
110
+ else:
111
+ dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
112
+ vid_path, vid_writer = [None] * bs, [None] * bs
113
+
114
+ # Run inference
115
+ model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
116
+ seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
117
+ for path, im, im0s, vid_cap, s in dataset:
118
+ with dt[0]:
119
+ im = torch.from_numpy(im).to(model.device)
120
+ im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
121
+ im /= 255 # 0 - 255 to 0.0 - 1.0
122
+ if len(im.shape) == 3:
123
+ im = im[None] # expand for batch dim
124
+
125
+ # Inference
126
+ with dt[1]:
127
+ visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
128
+ pred = model(im, augment=augment, visualize=visualize)
129
+
130
+ # NMS
131
+ with dt[2]:
132
+ pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
133
+
134
+ # Second-stage classifier (optional)
135
+ # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
136
+
137
+ # Process predictions
138
+ for i, det in enumerate(pred): # per image
139
+ seen += 1
140
+ if webcam: # batch_size >= 1
141
+ p, im0, frame = path[i], im0s[i].copy(), dataset.count
142
+ s += f'{i}: '
143
+ else:
144
+ p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
145
+
146
+ p = Path(p) # to Path
147
+ save_path = str(save_dir / p.name) # im.jpg
148
+ txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
149
+ s += '%gx%g ' % im.shape[2:] # print string
150
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
151
+ imc = im0.copy() if save_crop else im0 # for save_crop
152
+ annotator = Annotator(im0, line_width=line_thickness, example=str(names))
153
+ if len(det):
154
+ # Rescale boxes from img_size to im0 size
155
+ det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
156
+
157
+ # Print results
158
+ for c in det[:, 5].unique():
159
+ n = (det[:, 5] == c).sum() # detections per class
160
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
161
+
162
+ # Write results
163
+ for *xyxy, conf, cls in reversed(det):
164
+ if save_txt: # Write to file
165
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
166
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
167
+ with open(f'{txt_path}.txt', 'a') as f:
168
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
169
+
170
+ if save_img or save_crop or view_img: # Add bbox to image
171
+ c = int(cls) # integer class
172
+ label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
173
+ annotator.box_label(xyxy, label, color=colors(c, True))
174
+ if save_crop:
175
+ save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
176
+
177
+ # Stream results
178
+ im0 = annotator.result()
179
+ if view_img:
180
+ if platform.system() == 'Linux' and p not in windows:
181
+ windows.append(p)
182
+ cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
183
+ cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
184
+ cv2.imshow(str(p), im0)
185
+ cv2.waitKey(1) # 1 millisecond
186
+
187
+ # Save results (image with detections)
188
+ if save_img:
189
+ if dataset.mode == 'image':
190
+ cv2.imwrite(save_path, im0)
191
+ else: # 'video' or 'stream'
192
+ if vid_path[i] != save_path: # new video
193
+ vid_path[i] = save_path
194
+ if isinstance(vid_writer[i], cv2.VideoWriter):
195
+ vid_writer[i].release() # release previous video writer
196
+ if vid_cap: # video
197
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
198
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
199
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
200
+ else: # stream
201
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
202
+ save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
203
+ vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
204
+ vid_writer[i].write(im0)
205
+
206
+ # Print time (inference-only)
207
+ LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
208
+
209
+ # Print results
210
+ t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
211
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
212
+ if save_txt or save_img:
213
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
214
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
215
+ if update:
216
+ strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
217
+
218
+
219
+ def parse_opt():
220
+ parser = argparse.ArgumentParser()
221
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path or triton URL')
222
+ parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
223
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
224
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
225
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
226
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
227
+ parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
228
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
229
+ parser.add_argument('--view-img', action='store_true', help='show results')
230
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
231
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
232
+ parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
233
+ parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
234
+ parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
235
+ parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
236
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
237
+ parser.add_argument('--visualize', action='store_true', help='visualize features')
238
+ parser.add_argument('--update', action='store_true', help='update all models')
239
+ parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
240
+ parser.add_argument('--name', default='exp', help='save results to project/name')
241
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
242
+ parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
243
+ parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
244
+ parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
245
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
246
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
247
+ parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
248
+ opt = parser.parse_args()
249
+ opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
250
+ print_args(vars(opt))
251
+ return opt
252
+
253
+
254
+ def main(opt):
255
+ check_requirements(exclude=('tensorboard', 'thop'))
256
+ run(**vars(opt))
257
+
258
+
259
+ if __name__ == '__main__':
260
+ opt = parse_opt()
261
+ main(opt)
export.py ADDED
@@ -0,0 +1,818 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
+ """
3
+ Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
4
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+ PaddlePaddle | `paddle` | yolov5s_paddle_model/
19
+
20
+ Requirements:
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
22
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
23
+
24
+ Usage:
25
+ $ python export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
26
+
27
+ Inference:
28
+ $ python detect.py --weights yolov5s.pt # PyTorch
29
+ yolov5s.torchscript # TorchScript
30
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
31
+ yolov5s_openvino_model # OpenVINO
32
+ yolov5s.engine # TensorRT
33
+ yolov5s.mlmodel # CoreML (macOS-only)
34
+ yolov5s_saved_model # TensorFlow SavedModel
35
+ yolov5s.pb # TensorFlow GraphDef
36
+ yolov5s.tflite # TensorFlow Lite
37
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
38
+ yolov5s_paddle_model # PaddlePaddle
39
+
40
+ TensorFlow.js:
41
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
42
+ $ npm install
43
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
44
+ $ npm start
45
+ """
46
+
47
+ import argparse
48
+ import contextlib
49
+ import json
50
+ import os
51
+ import platform
52
+ import re
53
+ import subprocess
54
+ import sys
55
+ import time
56
+ import warnings
57
+ from pathlib import Path
58
+
59
+ import pandas as pd
60
+ import torch
61
+ from torch.utils.mobile_optimizer import optimize_for_mobile
62
+
63
+ FILE = Path(__file__).resolve()
64
+ ROOT = FILE.parents[0] # YOLOv5 root directory
65
+ if str(ROOT) not in sys.path:
66
+ sys.path.append(str(ROOT)) # add ROOT to PATH
67
+ if platform.system() != 'Windows':
68
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
69
+
70
+ from models.experimental import attempt_load
71
+ from models.yolo import ClassificationModel, Detect, DetectionModel, SegmentationModel
72
+ from utils.dataloaders import LoadImages
73
+ from utils.general import (LOGGER, Profile, check_dataset, check_img_size, check_requirements, check_version,
74
+ check_yaml, colorstr, file_size, get_default_args, print_args, url2file, yaml_save)
75
+ from utils.torch_utils import select_device, smart_inference_mode
76
+
77
+ MACOS = platform.system() == 'Darwin' # macOS environment
78
+
79
+
80
+ class iOSModel(torch.nn.Module):
81
+
82
+ def __init__(self, model, im):
83
+ super().__init__()
84
+ b, c, h, w = im.shape # batch, channel, height, width
85
+ self.model = model
86
+ self.nc = model.nc # number of classes
87
+ if w == h:
88
+ self.normalize = 1. / w
89
+ else:
90
+ self.normalize = torch.tensor([1. / w, 1. / h, 1. / w, 1. / h]) # broadcast (slower, smaller)
91
+ # np = model(im)[0].shape[1] # number of points
92
+ # self.normalize = torch.tensor([1. / w, 1. / h, 1. / w, 1. / h]).expand(np, 4) # explicit (faster, larger)
93
+
94
+ def forward(self, x):
95
+ xywh, conf, cls = self.model(x)[0].squeeze().split((4, 1, self.nc), 1)
96
+ return cls * conf, xywh * self.normalize # confidence (3780, 80), coordinates (3780, 4)
97
+
98
+
99
+ def export_formats():
100
+ # YOLOv5 export formats
101
+ x = [
102
+ ['PyTorch', '-', '.pt', True, True],
103
+ ['TorchScript', 'torchscript', '.torchscript', True, True],
104
+ ['ONNX', 'onnx', '.onnx', True, True],
105
+ ['OpenVINO', 'openvino', '_openvino_model', True, False],
106
+ ['TensorRT', 'engine', '.engine', False, True],
107
+ ['CoreML', 'coreml', '.mlmodel', True, False],
108
+ ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],
109
+ ['TensorFlow GraphDef', 'pb', '.pb', True, True],
110
+ ['TensorFlow Lite', 'tflite', '.tflite', True, False],
111
+ ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False, False],
112
+ ['TensorFlow.js', 'tfjs', '_web_model', False, False],
113
+ ['PaddlePaddle', 'paddle', '_paddle_model', True, True],]
114
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])
115
+
116
+
117
+ def try_export(inner_func):
118
+ # YOLOv5 export decorator, i..e @try_export
119
+ inner_args = get_default_args(inner_func)
120
+
121
+ def outer_func(*args, **kwargs):
122
+ prefix = inner_args['prefix']
123
+ try:
124
+ with Profile() as dt:
125
+ f, model = inner_func(*args, **kwargs)
126
+ LOGGER.info(f'{prefix} export success ✅ {dt.t:.1f}s, saved as {f} ({file_size(f):.1f} MB)')
127
+ return f, model
128
+ except Exception as e:
129
+ LOGGER.info(f'{prefix} export failure ❌ {dt.t:.1f}s: {e}')
130
+ return None, None
131
+
132
+ return outer_func
133
+
134
+
135
+ @try_export
136
+ def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
137
+ # YOLOv5 TorchScript model export
138
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
139
+ f = file.with_suffix('.torchscript')
140
+
141
+ ts = torch.jit.trace(model, im, strict=False)
142
+ d = {'shape': im.shape, 'stride': int(max(model.stride)), 'names': model.names}
143
+ extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
144
+ if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
145
+ optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
146
+ else:
147
+ ts.save(str(f), _extra_files=extra_files)
148
+ return f, None
149
+
150
+
151
+ @try_export
152
+ def export_onnx(model, im, file, opset, dynamic, simplify, prefix=colorstr('ONNX:')):
153
+ # YOLOv5 ONNX export
154
+ check_requirements('onnx>=1.12.0')
155
+ import onnx
156
+
157
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
158
+ f = file.with_suffix('.onnx')
159
+
160
+ output_names = ['output0', 'output1'] if isinstance(model, SegmentationModel) else ['output0']
161
+ if dynamic:
162
+ dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}} # shape(1,3,640,640)
163
+ if isinstance(model, SegmentationModel):
164
+ dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
165
+ dynamic['output1'] = {0: 'batch', 2: 'mask_height', 3: 'mask_width'} # shape(1,32,160,160)
166
+ elif isinstance(model, DetectionModel):
167
+ dynamic['output0'] = {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
168
+
169
+ torch.onnx.export(
170
+ model.cpu() if dynamic else model, # --dynamic only compatible with cpu
171
+ im.cpu() if dynamic else im,
172
+ f,
173
+ verbose=False,
174
+ opset_version=opset,
175
+ do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
176
+ input_names=['images'],
177
+ output_names=output_names,
178
+ dynamic_axes=dynamic or None)
179
+
180
+ # Checks
181
+ model_onnx = onnx.load(f) # load onnx model
182
+ onnx.checker.check_model(model_onnx) # check onnx model
183
+
184
+ # Metadata
185
+ d = {'stride': int(max(model.stride)), 'names': model.names}
186
+ for k, v in d.items():
187
+ meta = model_onnx.metadata_props.add()
188
+ meta.key, meta.value = k, str(v)
189
+ onnx.save(model_onnx, f)
190
+
191
+ # Simplify
192
+ if simplify:
193
+ try:
194
+ cuda = torch.cuda.is_available()
195
+ check_requirements(('onnxruntime-gpu' if cuda else 'onnxruntime', 'onnx-simplifier>=0.4.1'))
196
+ import onnxsim
197
+
198
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
199
+ model_onnx, check = onnxsim.simplify(model_onnx)
200
+ assert check, 'assert check failed'
201
+ onnx.save(model_onnx, f)
202
+ except Exception as e:
203
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
204
+ return f, model_onnx
205
+
206
+
207
+ @try_export
208
+ def export_openvino(file, metadata, half, prefix=colorstr('OpenVINO:')):
209
+ # YOLOv5 OpenVINO export
210
+ check_requirements('openvino-dev') # requires openvino-dev: https://pypi.org/project/openvino-dev/
211
+ import openvino.inference_engine as ie
212
+
213
+ LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
214
+ f = str(file).replace('.pt', f'_openvino_model{os.sep}')
215
+
216
+ args = [
217
+ 'mo',
218
+ '--input_model',
219
+ str(file.with_suffix('.onnx')),
220
+ '--output_dir',
221
+ f,
222
+ '--data_type',
223
+ ('FP16' if half else 'FP32'),]
224
+ subprocess.run(args, check=True, env=os.environ) # export
225
+ yaml_save(Path(f) / file.with_suffix('.yaml').name, metadata) # add metadata.yaml
226
+ return f, None
227
+
228
+
229
+ @try_export
230
+ def export_paddle(model, im, file, metadata, prefix=colorstr('PaddlePaddle:')):
231
+ # YOLOv5 Paddle export
232
+ check_requirements(('paddlepaddle', 'x2paddle'))
233
+ import x2paddle
234
+ from x2paddle.convert import pytorch2paddle
235
+
236
+ LOGGER.info(f'\n{prefix} starting export with X2Paddle {x2paddle.__version__}...')
237
+ f = str(file).replace('.pt', f'_paddle_model{os.sep}')
238
+
239
+ pytorch2paddle(module=model, save_dir=f, jit_type='trace', input_examples=[im]) # export
240
+ yaml_save(Path(f) / file.with_suffix('.yaml').name, metadata) # add metadata.yaml
241
+ return f, None
242
+
243
+
244
+ @try_export
245
+ def export_coreml(model, im, file, int8, half, nms, prefix=colorstr('CoreML:')):
246
+ # YOLOv5 CoreML export
247
+ check_requirements('coremltools')
248
+ import coremltools as ct
249
+
250
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
251
+ f = file.with_suffix('.mlmodel')
252
+
253
+ if nms:
254
+ model = iOSModel(model, im)
255
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
256
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
257
+ bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
258
+ if bits < 32:
259
+ if MACOS: # quantization only supported on macOS
260
+ with warnings.catch_warnings():
261
+ warnings.filterwarnings('ignore', category=DeprecationWarning) # suppress numpy==1.20 float warning
262
+ ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
263
+ else:
264
+ print(f'{prefix} quantization only supported on macOS, skipping...')
265
+ ct_model.save(f)
266
+ return f, ct_model
267
+
268
+
269
+ @try_export
270
+ def export_engine(model, im, file, half, dynamic, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
271
+ # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
272
+ assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
273
+ try:
274
+ import tensorrt as trt
275
+ except Exception:
276
+ if platform.system() == 'Linux':
277
+ check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')
278
+ import tensorrt as trt
279
+
280
+ if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
281
+ grid = model.model[-1].anchor_grid
282
+ model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
283
+ export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
284
+ model.model[-1].anchor_grid = grid
285
+ else: # TensorRT >= 8
286
+ check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
287
+ export_onnx(model, im, file, 12, dynamic, simplify) # opset 12
288
+ onnx = file.with_suffix('.onnx')
289
+
290
+ LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
291
+ assert onnx.exists(), f'failed to export ONNX file: {onnx}'
292
+ f = file.with_suffix('.engine') # TensorRT engine file
293
+ logger = trt.Logger(trt.Logger.INFO)
294
+ if verbose:
295
+ logger.min_severity = trt.Logger.Severity.VERBOSE
296
+
297
+ builder = trt.Builder(logger)
298
+ config = builder.create_builder_config()
299
+ config.max_workspace_size = workspace * 1 << 30
300
+ # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
301
+
302
+ flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
303
+ network = builder.create_network(flag)
304
+ parser = trt.OnnxParser(network, logger)
305
+ if not parser.parse_from_file(str(onnx)):
306
+ raise RuntimeError(f'failed to load ONNX file: {onnx}')
307
+
308
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
309
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
310
+ for inp in inputs:
311
+ LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
312
+ for out in outputs:
313
+ LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
314
+
315
+ if dynamic:
316
+ if im.shape[0] <= 1:
317
+ LOGGER.warning(f'{prefix} WARNING ⚠️ --dynamic model requires maximum --batch-size argument')
318
+ profile = builder.create_optimization_profile()
319
+ for inp in inputs:
320
+ profile.set_shape(inp.name, (1, *im.shape[1:]), (max(1, im.shape[0] // 2), *im.shape[1:]), im.shape)
321
+ config.add_optimization_profile(profile)
322
+
323
+ LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and half else 32} engine as {f}')
324
+ if builder.platform_has_fast_fp16 and half:
325
+ config.set_flag(trt.BuilderFlag.FP16)
326
+ with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
327
+ t.write(engine.serialize())
328
+ return f, None
329
+
330
+
331
+ @try_export
332
+ def export_saved_model(model,
333
+ im,
334
+ file,
335
+ dynamic,
336
+ tf_nms=False,
337
+ agnostic_nms=False,
338
+ topk_per_class=100,
339
+ topk_all=100,
340
+ iou_thres=0.45,
341
+ conf_thres=0.25,
342
+ keras=False,
343
+ prefix=colorstr('TensorFlow SavedModel:')):
344
+ # YOLOv5 TensorFlow SavedModel export
345
+ try:
346
+ import tensorflow as tf
347
+ except Exception:
348
+ check_requirements(f"tensorflow{'' if torch.cuda.is_available() else '-macos' if MACOS else '-cpu'}")
349
+ import tensorflow as tf
350
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
351
+
352
+ from models.tf import TFModel
353
+
354
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
355
+ f = str(file).replace('.pt', '_saved_model')
356
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
357
+
358
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
359
+ im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
360
+ _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
361
+ inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
362
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
363
+ keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
364
+ keras_model.trainable = False
365
+ keras_model.summary()
366
+ if keras:
367
+ keras_model.save(f, save_format='tf')
368
+ else:
369
+ spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
370
+ m = tf.function(lambda x: keras_model(x)) # full model
371
+ m = m.get_concrete_function(spec)
372
+ frozen_func = convert_variables_to_constants_v2(m)
373
+ tfm = tf.Module()
374
+ tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x), [spec])
375
+ tfm.__call__(im)
376
+ tf.saved_model.save(tfm,
377
+ f,
378
+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=False) if check_version(
379
+ tf.__version__, '2.6') else tf.saved_model.SaveOptions())
380
+ return f, keras_model
381
+
382
+
383
+ @try_export
384
+ def export_pb(keras_model, file, prefix=colorstr('TensorFlow GraphDef:')):
385
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
386
+ import tensorflow as tf
387
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
388
+
389
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
390
+ f = file.with_suffix('.pb')
391
+
392
+ m = tf.function(lambda x: keras_model(x)) # full model
393
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
394
+ frozen_func = convert_variables_to_constants_v2(m)
395
+ frozen_func.graph.as_graph_def()
396
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
397
+ return f, None
398
+
399
+
400
+ @try_export
401
+ def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
402
+ # YOLOv5 TensorFlow Lite export
403
+ import tensorflow as tf
404
+
405
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
406
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
407
+ f = str(file).replace('.pt', '-fp16.tflite')
408
+
409
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
410
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
411
+ converter.target_spec.supported_types = [tf.float16]
412
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
413
+ if int8:
414
+ from models.tf import representative_dataset_gen
415
+ dataset = LoadImages(check_dataset(check_yaml(data))['train'], img_size=imgsz, auto=False)
416
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
417
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
418
+ converter.target_spec.supported_types = []
419
+ converter.inference_input_type = tf.uint8 # or tf.int8
420
+ converter.inference_output_type = tf.uint8 # or tf.int8
421
+ converter.experimental_new_quantizer = True
422
+ f = str(file).replace('.pt', '-int8.tflite')
423
+ if nms or agnostic_nms:
424
+ converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
425
+
426
+ tflite_model = converter.convert()
427
+ open(f, 'wb').write(tflite_model)
428
+ return f, None
429
+
430
+
431
+ @try_export
432
+ def export_edgetpu(file, prefix=colorstr('Edge TPU:')):
433
+ # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
434
+ cmd = 'edgetpu_compiler --version'
435
+ help_url = 'https://coral.ai/docs/edgetpu/compiler/'
436
+ assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
437
+ if subprocess.run(f'{cmd} > /dev/null 2>&1', shell=True).returncode != 0:
438
+ LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
439
+ sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
440
+ for c in (
441
+ 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
442
+ 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
443
+ 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
444
+ subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
445
+ ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
446
+
447
+ LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
448
+ f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
449
+ f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
450
+
451
+ subprocess.run([
452
+ 'edgetpu_compiler',
453
+ '-s',
454
+ '-d',
455
+ '-k',
456
+ '10',
457
+ '--out_dir',
458
+ str(file.parent),
459
+ f_tfl,], check=True)
460
+ return f, None
461
+
462
+
463
+ @try_export
464
+ def export_tfjs(file, int8, prefix=colorstr('TensorFlow.js:')):
465
+ # YOLOv5 TensorFlow.js export
466
+ check_requirements('tensorflowjs')
467
+ import tensorflowjs as tfjs
468
+
469
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
470
+ f = str(file).replace('.pt', '_web_model') # js dir
471
+ f_pb = file.with_suffix('.pb') # *.pb path
472
+ f_json = f'{f}/model.json' # *.json path
473
+
474
+ args = [
475
+ 'tensorflowjs_converter',
476
+ '--input_format=tf_frozen_model',
477
+ '--quantize_uint8' if int8 else '',
478
+ '--output_node_names=Identity,Identity_1,Identity_2,Identity_3',
479
+ str(f_pb),
480
+ str(f),]
481
+ subprocess.run([arg for arg in args if arg], check=True)
482
+
483
+ json = Path(f_json).read_text()
484
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
485
+ subst = re.sub(
486
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
487
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
488
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
489
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
490
+ r'"Identity_1": {"name": "Identity_1"}, '
491
+ r'"Identity_2": {"name": "Identity_2"}, '
492
+ r'"Identity_3": {"name": "Identity_3"}}}', json)
493
+ j.write(subst)
494
+ return f, None
495
+
496
+
497
+ def add_tflite_metadata(file, metadata, num_outputs):
498
+ # Add metadata to *.tflite models per https://www.tensorflow.org/lite/models/convert/metadata
499
+ with contextlib.suppress(ImportError):
500
+ # check_requirements('tflite_support')
501
+ from tflite_support import flatbuffers
502
+ from tflite_support import metadata as _metadata
503
+ from tflite_support import metadata_schema_py_generated as _metadata_fb
504
+
505
+ tmp_file = Path('/tmp/meta.txt')
506
+ with open(tmp_file, 'w') as meta_f:
507
+ meta_f.write(str(metadata))
508
+
509
+ model_meta = _metadata_fb.ModelMetadataT()
510
+ label_file = _metadata_fb.AssociatedFileT()
511
+ label_file.name = tmp_file.name
512
+ model_meta.associatedFiles = [label_file]
513
+
514
+ subgraph = _metadata_fb.SubGraphMetadataT()
515
+ subgraph.inputTensorMetadata = [_metadata_fb.TensorMetadataT()]
516
+ subgraph.outputTensorMetadata = [_metadata_fb.TensorMetadataT()] * num_outputs
517
+ model_meta.subgraphMetadata = [subgraph]
518
+
519
+ b = flatbuffers.Builder(0)
520
+ b.Finish(model_meta.Pack(b), _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER)
521
+ metadata_buf = b.Output()
522
+
523
+ populator = _metadata.MetadataPopulator.with_model_file(file)
524
+ populator.load_metadata_buffer(metadata_buf)
525
+ populator.load_associated_files([str(tmp_file)])
526
+ populator.populate()
527
+ tmp_file.unlink()
528
+
529
+
530
+ def pipeline_coreml(model, im, file, names, y, prefix=colorstr('CoreML Pipeline:')):
531
+ # YOLOv5 CoreML pipeline
532
+ import coremltools as ct
533
+ from PIL import Image
534
+
535
+ print(f'{prefix} starting pipeline with coremltools {ct.__version__}...')
536
+ batch_size, ch, h, w = list(im.shape) # BCHW
537
+ t = time.time()
538
+
539
+ # Output shapes
540
+ spec = model.get_spec()
541
+ out0, out1 = iter(spec.description.output)
542
+ if platform.system() == 'Darwin':
543
+ img = Image.new('RGB', (w, h)) # img(192 width, 320 height)
544
+ # img = torch.zeros((*opt.img_size, 3)).numpy() # img size(320,192,3) iDetection
545
+ out = model.predict({'image': img})
546
+ out0_shape, out1_shape = out[out0.name].shape, out[out1.name].shape
547
+ else: # linux and windows can not run model.predict(), get sizes from pytorch output y
548
+ s = tuple(y[0].shape)
549
+ out0_shape, out1_shape = (s[1], s[2] - 5), (s[1], 4) # (3780, 80), (3780, 4)
550
+
551
+ # Checks
552
+ nx, ny = spec.description.input[0].type.imageType.width, spec.description.input[0].type.imageType.height
553
+ na, nc = out0_shape
554
+ # na, nc = out0.type.multiArrayType.shape # number anchors, classes
555
+ assert len(names) == nc, f'{len(names)} names found for nc={nc}' # check
556
+
557
+ # Define output shapes (missing)
558
+ out0.type.multiArrayType.shape[:] = out0_shape # (3780, 80)
559
+ out1.type.multiArrayType.shape[:] = out1_shape # (3780, 4)
560
+ # spec.neuralNetwork.preprocessing[0].featureName = '0'
561
+
562
+ # Flexible input shapes
563
+ # from coremltools.models.neural_network import flexible_shape_utils
564
+ # s = [] # shapes
565
+ # s.append(flexible_shape_utils.NeuralNetworkImageSize(320, 192))
566
+ # s.append(flexible_shape_utils.NeuralNetworkImageSize(640, 384)) # (height, width)
567
+ # flexible_shape_utils.add_enumerated_image_sizes(spec, feature_name='image', sizes=s)
568
+ # r = flexible_shape_utils.NeuralNetworkImageSizeRange() # shape ranges
569
+ # r.add_height_range((192, 640))
570
+ # r.add_width_range((192, 640))
571
+ # flexible_shape_utils.update_image_size_range(spec, feature_name='image', size_range=r)
572
+
573
+ # Print
574
+ print(spec.description)
575
+
576
+ # Model from spec
577
+ model = ct.models.MLModel(spec)
578
+
579
+ # 3. Create NMS protobuf
580
+ nms_spec = ct.proto.Model_pb2.Model()
581
+ nms_spec.specificationVersion = 5
582
+ for i in range(2):
583
+ decoder_output = model._spec.description.output[i].SerializeToString()
584
+ nms_spec.description.input.add()
585
+ nms_spec.description.input[i].ParseFromString(decoder_output)
586
+ nms_spec.description.output.add()
587
+ nms_spec.description.output[i].ParseFromString(decoder_output)
588
+
589
+ nms_spec.description.output[0].name = 'confidence'
590
+ nms_spec.description.output[1].name = 'coordinates'
591
+
592
+ output_sizes = [nc, 4]
593
+ for i in range(2):
594
+ ma_type = nms_spec.description.output[i].type.multiArrayType
595
+ ma_type.shapeRange.sizeRanges.add()
596
+ ma_type.shapeRange.sizeRanges[0].lowerBound = 0
597
+ ma_type.shapeRange.sizeRanges[0].upperBound = -1
598
+ ma_type.shapeRange.sizeRanges.add()
599
+ ma_type.shapeRange.sizeRanges[1].lowerBound = output_sizes[i]
600
+ ma_type.shapeRange.sizeRanges[1].upperBound = output_sizes[i]
601
+ del ma_type.shape[:]
602
+
603
+ nms = nms_spec.nonMaximumSuppression
604
+ nms.confidenceInputFeatureName = out0.name # 1x507x80
605
+ nms.coordinatesInputFeatureName = out1.name # 1x507x4
606
+ nms.confidenceOutputFeatureName = 'confidence'
607
+ nms.coordinatesOutputFeatureName = 'coordinates'
608
+ nms.iouThresholdInputFeatureName = 'iouThreshold'
609
+ nms.confidenceThresholdInputFeatureName = 'confidenceThreshold'
610
+ nms.iouThreshold = 0.45
611
+ nms.confidenceThreshold = 0.25
612
+ nms.pickTop.perClass = True
613
+ nms.stringClassLabels.vector.extend(names.values())
614
+ nms_model = ct.models.MLModel(nms_spec)
615
+
616
+ # 4. Pipeline models together
617
+ pipeline = ct.models.pipeline.Pipeline(input_features=[('image', ct.models.datatypes.Array(3, ny, nx)),
618
+ ('iouThreshold', ct.models.datatypes.Double()),
619
+ ('confidenceThreshold', ct.models.datatypes.Double())],
620
+ output_features=['confidence', 'coordinates'])
621
+ pipeline.add_model(model)
622
+ pipeline.add_model(nms_model)
623
+
624
+ # Correct datatypes
625
+ pipeline.spec.description.input[0].ParseFromString(model._spec.description.input[0].SerializeToString())
626
+ pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString())
627
+ pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString())
628
+
629
+ # Update metadata
630
+ pipeline.spec.specificationVersion = 5
631
+ pipeline.spec.description.metadata.versionString = 'https://github.com/ultralytics/yolov5'
632
+ pipeline.spec.description.metadata.shortDescription = 'https://github.com/ultralytics/yolov5'
633
+ pipeline.spec.description.metadata.author = '[email protected]'
634
+ pipeline.spec.description.metadata.license = 'https://github.com/ultralytics/yolov5/blob/master/LICENSE'
635
+ pipeline.spec.description.metadata.userDefined.update({
636
+ 'classes': ','.join(names.values()),
637
+ 'iou_threshold': str(nms.iouThreshold),
638
+ 'confidence_threshold': str(nms.confidenceThreshold)})
639
+
640
+ # Save the model
641
+ f = file.with_suffix('.mlmodel') # filename
642
+ model = ct.models.MLModel(pipeline.spec)
643
+ model.input_description['image'] = 'Input image'
644
+ model.input_description['iouThreshold'] = f'(optional) IOU Threshold override (default: {nms.iouThreshold})'
645
+ model.input_description['confidenceThreshold'] = \
646
+ f'(optional) Confidence Threshold override (default: {nms.confidenceThreshold})'
647
+ model.output_description['confidence'] = 'Boxes × Class confidence (see user-defined metadata "classes")'
648
+ model.output_description['coordinates'] = 'Boxes × [x, y, width, height] (relative to image size)'
649
+ model.save(f) # pipelined
650
+ print(f'{prefix} pipeline success ({time.time() - t:.2f}s), saved as {f} ({file_size(f):.1f} MB)')
651
+
652
+
653
+ @smart_inference_mode()
654
+ def run(
655
+ data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
656
+ weights=ROOT / 'yolov5s.pt', # weights path
657
+ imgsz=(640, 640), # image (height, width)
658
+ batch_size=1, # batch size
659
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
660
+ include=('torchscript', 'onnx'), # include formats
661
+ half=False, # FP16 half-precision export
662
+ inplace=False, # set YOLOv5 Detect() inplace=True
663
+ keras=False, # use Keras
664
+ optimize=False, # TorchScript: optimize for mobile
665
+ int8=False, # CoreML/TF INT8 quantization
666
+ dynamic=False, # ONNX/TF/TensorRT: dynamic axes
667
+ simplify=False, # ONNX: simplify model
668
+ opset=12, # ONNX: opset version
669
+ verbose=False, # TensorRT: verbose log
670
+ workspace=4, # TensorRT: workspace size (GB)
671
+ nms=False, # TF: add NMS to model
672
+ agnostic_nms=False, # TF: add agnostic NMS to model
673
+ topk_per_class=100, # TF.js NMS: topk per class to keep
674
+ topk_all=100, # TF.js NMS: topk for all classes to keep
675
+ iou_thres=0.45, # TF.js NMS: IoU threshold
676
+ conf_thres=0.25, # TF.js NMS: confidence threshold
677
+ ):
678
+ t = time.time()
679
+ include = [x.lower() for x in include] # to lowercase
680
+ fmts = tuple(export_formats()['Argument'][1:]) # --include arguments
681
+ flags = [x in include for x in fmts]
682
+ assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {fmts}'
683
+ jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle = flags # export booleans
684
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
685
+
686
+ # Load PyTorch model
687
+ device = select_device(device)
688
+ if half:
689
+ assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
690
+ assert not dynamic, '--half not compatible with --dynamic, i.e. use either --half or --dynamic but not both'
691
+ model = attempt_load(weights, device=device, inplace=True, fuse=True) # load FP32 model
692
+
693
+ # Checks
694
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
695
+ if optimize:
696
+ assert device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'
697
+
698
+ # Input
699
+ gs = int(max(model.stride)) # grid size (max stride)
700
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
701
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
702
+
703
+ # Update model
704
+ model.eval()
705
+ for k, m in model.named_modules():
706
+ if isinstance(m, Detect):
707
+ m.inplace = inplace
708
+ m.dynamic = dynamic
709
+ m.export = True
710
+
711
+ for _ in range(2):
712
+ y = model(im) # dry runs
713
+ if half and not coreml:
714
+ im, model = im.half(), model.half() # to FP16
715
+ shape = tuple((y[0] if isinstance(y, tuple) else y).shape) # model output shape
716
+ metadata = {'stride': int(max(model.stride)), 'names': model.names} # model metadata
717
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
718
+
719
+ # Exports
720
+ f = [''] * len(fmts) # exported filenames
721
+ warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
722
+ if jit: # TorchScript
723
+ f[0], _ = export_torchscript(model, im, file, optimize)
724
+ if engine: # TensorRT required before ONNX
725
+ f[1], _ = export_engine(model, im, file, half, dynamic, simplify, workspace, verbose)
726
+ if onnx or xml: # OpenVINO requires ONNX
727
+ f[2], _ = export_onnx(model, im, file, opset, dynamic, simplify)
728
+ if xml: # OpenVINO
729
+ f[3], _ = export_openvino(file, metadata, half)
730
+ if coreml: # CoreML
731
+ f[4], ct_model = export_coreml(model, im, file, int8, half, nms)
732
+ if nms:
733
+ pipeline_coreml(ct_model, im, file, model.names, y)
734
+ if any((saved_model, pb, tflite, edgetpu, tfjs)): # TensorFlow formats
735
+ assert not tflite or not tfjs, 'TFLite and TF.js models must be exported separately, please pass only one type.'
736
+ assert not isinstance(model, ClassificationModel), 'ClassificationModel export to TF formats not yet supported.'
737
+ f[5], s_model = export_saved_model(model.cpu(),
738
+ im,
739
+ file,
740
+ dynamic,
741
+ tf_nms=nms or agnostic_nms or tfjs,
742
+ agnostic_nms=agnostic_nms or tfjs,
743
+ topk_per_class=topk_per_class,
744
+ topk_all=topk_all,
745
+ iou_thres=iou_thres,
746
+ conf_thres=conf_thres,
747
+ keras=keras)
748
+ if pb or tfjs: # pb prerequisite to tfjs
749
+ f[6], _ = export_pb(s_model, file)
750
+ if tflite or edgetpu:
751
+ f[7], _ = export_tflite(s_model, im, file, int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
752
+ if edgetpu:
753
+ f[8], _ = export_edgetpu(file)
754
+ add_tflite_metadata(f[8] or f[7], metadata, num_outputs=len(s_model.outputs))
755
+ if tfjs:
756
+ f[9], _ = export_tfjs(file, int8)
757
+ if paddle: # PaddlePaddle
758
+ f[10], _ = export_paddle(model, im, file, metadata)
759
+
760
+ # Finish
761
+ f = [str(x) for x in f if x] # filter out '' and None
762
+ if any(f):
763
+ cls, det, seg = (isinstance(model, x) for x in (ClassificationModel, DetectionModel, SegmentationModel)) # type
764
+ det &= not seg # segmentation models inherit from SegmentationModel(DetectionModel)
765
+ dir = Path('segment' if seg else 'classify' if cls else '')
766
+ h = '--half' if half else '' # --half FP16 inference arg
767
+ s = '# WARNING ⚠️ ClassificationModel not yet supported for PyTorch Hub AutoShape inference' if cls else \
768
+ '# WARNING ⚠️ SegmentationModel not yet supported for PyTorch Hub AutoShape inference' if seg else ''
769
+ LOGGER.info(f'\nExport complete ({time.time() - t:.1f}s)'
770
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
771
+ f"\nDetect: python {dir / ('detect.py' if det else 'predict.py')} --weights {f[-1]} {h}"
772
+ f"\nValidate: python {dir / 'val.py'} --weights {f[-1]} {h}"
773
+ f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}') {s}"
774
+ f'\nVisualize: https://netron.app')
775
+ return f # return list of exported files/dirs
776
+
777
+
778
+ def parse_opt(known=False):
779
+ parser = argparse.ArgumentParser()
780
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
781
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
782
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
783
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
784
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
785
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
786
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
787
+ parser.add_argument('--keras', action='store_true', help='TF: use Keras')
788
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
789
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
790
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF/TensorRT: dynamic axes')
791
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
792
+ parser.add_argument('--opset', type=int, default=17, help='ONNX: opset version')
793
+ parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
794
+ parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
795
+ parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
796
+ parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
797
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
798
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
799
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
800
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
801
+ parser.add_argument(
802
+ '--include',
803
+ nargs='+',
804
+ default=['torchscript'],
805
+ help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle')
806
+ opt = parser.parse_known_args()[0] if known else parser.parse_args()
807
+ print_args(vars(opt))
808
+ return opt
809
+
810
+
811
+ def main(opt):
812
+ for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
813
+ run(**vars(opt))
814
+
815
+
816
+ if __name__ == '__main__':
817
+ opt = parse_opt()
818
+ main(opt)
hubconf.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
+ """
3
+ PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5
4
+
5
+ Usage:
6
+ import torch
7
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # official model
8
+ model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s') # from branch
9
+ model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt') # custom/local model
10
+ model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local') # local repo
11
+ """
12
+
13
+ import torch
14
+
15
+
16
+ def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
17
+ """Creates or loads a YOLOv5 model
18
+
19
+ Arguments:
20
+ name (str): model name 'yolov5s' or path 'path/to/best.pt'
21
+ pretrained (bool): load pretrained weights into the model
22
+ channels (int): number of input channels
23
+ classes (int): number of model classes
24
+ autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
25
+ verbose (bool): print all information to screen
26
+ device (str, torch.device, None): device to use for model parameters
27
+
28
+ Returns:
29
+ YOLOv5 model
30
+ """
31
+ from pathlib import Path
32
+
33
+ from models.common import AutoShape, DetectMultiBackend
34
+ from models.experimental import attempt_load
35
+ from models.yolo import ClassificationModel, DetectionModel, SegmentationModel
36
+ from utils.downloads import attempt_download
37
+ from utils.general import LOGGER, check_requirements, intersect_dicts, logging
38
+ from utils.torch_utils import select_device
39
+
40
+ if not verbose:
41
+ LOGGER.setLevel(logging.WARNING)
42
+ check_requirements(exclude=('opencv-python', 'tensorboard', 'thop'))
43
+ name = Path(name)
44
+ path = name.with_suffix('.pt') if name.suffix == '' and not name.is_dir() else name # checkpoint path
45
+ try:
46
+ device = select_device(device)
47
+ if pretrained and channels == 3 and classes == 80:
48
+ try:
49
+ model = DetectMultiBackend(path, device=device, fuse=autoshape) # detection model
50
+ if autoshape:
51
+ if model.pt and isinstance(model.model, ClassificationModel):
52
+ LOGGER.warning('WARNING ⚠️ YOLOv5 ClassificationModel is not yet AutoShape compatible. '
53
+ 'You must pass torch tensors in BCHW to this model, i.e. shape(1,3,224,224).')
54
+ elif model.pt and isinstance(model.model, SegmentationModel):
55
+ LOGGER.warning('WARNING ⚠️ YOLOv5 SegmentationModel is not yet AutoShape compatible. '
56
+ 'You will not be able to run inference with this model.')
57
+ else:
58
+ model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
59
+ except Exception:
60
+ model = attempt_load(path, device=device, fuse=False) # arbitrary model
61
+ else:
62
+ cfg = list((Path(__file__).parent / 'models').rglob(f'{path.stem}.yaml'))[0] # model.yaml path
63
+ model = DetectionModel(cfg, channels, classes) # create model
64
+ if pretrained:
65
+ ckpt = torch.load(attempt_download(path), map_location=device) # load
66
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
67
+ csd = intersect_dicts(csd, model.state_dict(), exclude=['anchors']) # intersect
68
+ model.load_state_dict(csd, strict=False) # load
69
+ if len(ckpt['model'].names) == classes:
70
+ model.names = ckpt['model'].names # set class names attribute
71
+ if not verbose:
72
+ LOGGER.setLevel(logging.INFO) # reset to default
73
+ return model.to(device)
74
+
75
+ except Exception as e:
76
+ help_url = 'https://github.com/ultralytics/yolov5/issues/36'
77
+ s = f'{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help.'
78
+ raise Exception(s) from e
79
+
80
+
81
+ def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None):
82
+ # YOLOv5 custom or local model
83
+ return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
84
+
85
+
86
+ def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
87
+ # YOLOv5-nano model https://github.com/ultralytics/yolov5
88
+ return _create('yolov5n', pretrained, channels, classes, autoshape, _verbose, device)
89
+
90
+
91
+ def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
92
+ # YOLOv5-small model https://github.com/ultralytics/yolov5
93
+ return _create('yolov5s', pretrained, channels, classes, autoshape, _verbose, device)
94
+
95
+
96
+ def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
97
+ # YOLOv5-medium model https://github.com/ultralytics/yolov5
98
+ return _create('yolov5m', pretrained, channels, classes, autoshape, _verbose, device)
99
+
100
+
101
+ def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
102
+ # YOLOv5-large model https://github.com/ultralytics/yolov5
103
+ return _create('yolov5l', pretrained, channels, classes, autoshape, _verbose, device)
104
+
105
+
106
+ def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
107
+ # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
108
+ return _create('yolov5x', pretrained, channels, classes, autoshape, _verbose, device)
109
+
110
+
111
+ def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
112
+ # YOLOv5-nano-P6 model https://github.com/ultralytics/yolov5
113
+ return _create('yolov5n6', pretrained, channels, classes, autoshape, _verbose, device)
114
+
115
+
116
+ def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
117
+ # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
118
+ return _create('yolov5s6', pretrained, channels, classes, autoshape, _verbose, device)
119
+
120
+
121
+ def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
122
+ # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
123
+ return _create('yolov5m6', pretrained, channels, classes, autoshape, _verbose, device)
124
+
125
+
126
+ def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
127
+ # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
128
+ return _create('yolov5l6', pretrained, channels, classes, autoshape, _verbose, device)
129
+
130
+
131
+ def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
132
+ # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
133
+ return _create('yolov5x6', pretrained, channels, classes, autoshape, _verbose, device)
134
+
135
+
136
+ if __name__ == '__main__':
137
+ import argparse
138
+ from pathlib import Path
139
+
140
+ import numpy as np
141
+ from PIL import Image
142
+
143
+ from utils.general import cv2, print_args
144
+
145
+ # Argparser
146
+ parser = argparse.ArgumentParser()
147
+ parser.add_argument('--model', type=str, default='yolov5s', help='model name')
148
+ opt = parser.parse_args()
149
+ print_args(vars(opt))
150
+
151
+ # Model
152
+ model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
153
+ # model = custom(path='path/to/model.pt') # custom
154
+
155
+ # Images
156
+ imgs = [
157
+ 'data/images/zidane.jpg', # filename
158
+ Path('data/images/zidane.jpg'), # Path
159
+ 'https://ultralytics.com/images/zidane.jpg', # URI
160
+ cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
161
+ Image.open('data/images/bus.jpg'), # PIL
162
+ np.zeros((320, 640, 3))] # numpy
163
+
164
+ # Inference
165
+ results = model(imgs, size=320) # batched inference
166
+
167
+ # Results
168
+ results.print()
169
+ results.save()
train.py ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
+ """
3
+ Train a YOLOv5 model on a custom dataset.
4
+ Models and datasets download automatically from the latest YOLOv5 release.
5
+
6
+ Usage - Single-GPU training:
7
+ $ python train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (recommended)
8
+ $ python train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch
9
+
10
+ Usage - Multi-GPU DDP training:
11
+ $ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 train.py --data coco128.yaml --weights yolov5s.pt --img 640 --device 0,1,2,3
12
+
13
+ Models: https://github.com/ultralytics/yolov5/tree/master/models
14
+ Datasets: https://github.com/ultralytics/yolov5/tree/master/data
15
+ Tutorial: https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data
16
+ """
17
+
18
+ import argparse
19
+ import math
20
+ import os
21
+ import random
22
+ import subprocess
23
+ import sys
24
+ import time
25
+ from copy import deepcopy
26
+ from datetime import datetime
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+ import torch
31
+ import torch.distributed as dist
32
+ import torch.nn as nn
33
+ import yaml
34
+ from torch.optim import lr_scheduler
35
+ from tqdm import tqdm
36
+
37
+ FILE = Path(__file__).resolve()
38
+ ROOT = FILE.parents[0] # YOLOv5 root directory
39
+ if str(ROOT) not in sys.path:
40
+ sys.path.append(str(ROOT)) # add ROOT to PATH
41
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
42
+
43
+ import val as validate # for end-of-epoch mAP
44
+ from models.experimental import attempt_load
45
+ from models.yolo import Model
46
+ from utils.autoanchor import check_anchors
47
+ from utils.autobatch import check_train_batch_size
48
+ from utils.callbacks import Callbacks
49
+ from utils.dataloaders import create_dataloader
50
+ from utils.downloads import attempt_download, is_url
51
+ from utils.general import (LOGGER, TQDM_BAR_FORMAT, check_amp, check_dataset, check_file, check_git_info,
52
+ check_git_status, check_img_size, check_requirements, check_suffix, check_yaml, colorstr,
53
+ get_latest_run, increment_path, init_seeds, intersect_dicts, labels_to_class_weights,
54
+ labels_to_image_weights, methods, one_cycle, print_args, print_mutation, strip_optimizer,
55
+ yaml_save)
56
+ from utils.loggers import Loggers
57
+ from utils.loggers.comet.comet_utils import check_comet_resume
58
+ from utils.loss import ComputeLoss
59
+ from utils.metrics import fitness
60
+ from utils.plots import plot_evolve
61
+ from utils.torch_utils import (EarlyStopping, ModelEMA, de_parallel, select_device, smart_DDP, smart_optimizer,
62
+ smart_resume, torch_distributed_zero_first)
63
+
64
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
65
+ RANK = int(os.getenv('RANK', -1))
66
+ WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
67
+ GIT_INFO = check_git_info()
68
+
69
+
70
+ def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hyp dictionary
71
+ save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \
72
+ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \
73
+ opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze
74
+ callbacks.run('on_pretrain_routine_start')
75
+
76
+ # Directories
77
+ w = save_dir / 'weights' # weights dir
78
+ (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
79
+ last, best = w / 'last.pt', w / 'best.pt'
80
+
81
+ # Hyperparameters
82
+ if isinstance(hyp, str):
83
+ with open(hyp, errors='ignore') as f:
84
+ hyp = yaml.safe_load(f) # load hyps dict
85
+ LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
86
+ opt.hyp = hyp.copy() # for saving hyps to checkpoints
87
+
88
+ # Save run settings
89
+ if not evolve:
90
+ yaml_save(save_dir / 'hyp.yaml', hyp)
91
+ yaml_save(save_dir / 'opt.yaml', vars(opt))
92
+
93
+ # Loggers
94
+ data_dict = None
95
+ if RANK in {-1, 0}:
96
+ loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
97
+
98
+ # Register actions
99
+ for k in methods(loggers):
100
+ callbacks.register_action(k, callback=getattr(loggers, k))
101
+
102
+ # Process custom dataset artifact link
103
+ data_dict = loggers.remote_dataset
104
+ if resume: # If resuming runs from remote artifact
105
+ weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size
106
+
107
+ # Config
108
+ plots = not evolve and not opt.noplots # create plots
109
+ cuda = device.type != 'cpu'
110
+ init_seeds(opt.seed + 1 + RANK, deterministic=True)
111
+ with torch_distributed_zero_first(LOCAL_RANK):
112
+ data_dict = data_dict or check_dataset(data) # check if None
113
+ train_path, val_path = data_dict['train'], data_dict['val']
114
+ nc = 1 if single_cls else int(data_dict['nc']) # number of classes
115
+ names = {0: 'item'} if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
116
+ is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset
117
+
118
+ # Model
119
+ check_suffix(weights, '.pt') # check weights
120
+ pretrained = weights.endswith('.pt')
121
+ if pretrained:
122
+ with torch_distributed_zero_first(LOCAL_RANK):
123
+ weights = attempt_download(weights) # download if not found locally
124
+ ckpt = torch.load(weights, map_location='cpu') # load checkpoint to CPU to avoid CUDA memory leak
125
+ model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
126
+ exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys
127
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
128
+ csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
129
+ model.load_state_dict(csd, strict=False) # load
130
+ LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report
131
+ else:
132
+ model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
133
+ amp = check_amp(model) # check AMP
134
+
135
+ # Freeze
136
+ freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
137
+ for k, v in model.named_parameters():
138
+ v.requires_grad = True # train all layers
139
+ # v.register_hook(lambda x: torch.nan_to_num(x)) # NaN to 0 (commented for erratic training results)
140
+ if any(x in k for x in freeze):
141
+ LOGGER.info(f'freezing {k}')
142
+ v.requires_grad = False
143
+
144
+ # Image size
145
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
146
+ imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
147
+
148
+ # Batch size
149
+ if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
150
+ batch_size = check_train_batch_size(model, imgsz, amp)
151
+ loggers.on_params_update({'batch_size': batch_size})
152
+
153
+ # Optimizer
154
+ nbs = 64 # nominal batch size
155
+ accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
156
+ hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
157
+ optimizer = smart_optimizer(model, opt.optimizer, hyp['lr0'], hyp['momentum'], hyp['weight_decay'])
158
+
159
+ # Scheduler
160
+ if opt.cos_lr:
161
+ lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
162
+ else:
163
+ lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
164
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
165
+
166
+ # EMA
167
+ ema = ModelEMA(model) if RANK in {-1, 0} else None
168
+
169
+ # Resume
170
+ best_fitness, start_epoch = 0.0, 0
171
+ if pretrained:
172
+ if resume:
173
+ best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume)
174
+ del ckpt, csd
175
+
176
+ # DP mode
177
+ if cuda and RANK == -1 and torch.cuda.device_count() > 1:
178
+ LOGGER.warning('WARNING ⚠️ DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n'
179
+ 'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.')
180
+ model = torch.nn.DataParallel(model)
181
+
182
+ # SyncBatchNorm
183
+ if opt.sync_bn and cuda and RANK != -1:
184
+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
185
+ LOGGER.info('Using SyncBatchNorm()')
186
+
187
+ # Trainloader
188
+ train_loader, dataset = create_dataloader(train_path,
189
+ imgsz,
190
+ batch_size // WORLD_SIZE,
191
+ gs,
192
+ single_cls,
193
+ hyp=hyp,
194
+ augment=True,
195
+ cache=None if opt.cache == 'val' else opt.cache,
196
+ rect=opt.rect,
197
+ rank=LOCAL_RANK,
198
+ workers=workers,
199
+ image_weights=opt.image_weights,
200
+ quad=opt.quad,
201
+ prefix=colorstr('train: '),
202
+ shuffle=True,
203
+ seed=opt.seed)
204
+ labels = np.concatenate(dataset.labels, 0)
205
+ mlc = int(labels[:, 0].max()) # max label class
206
+ assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}'
207
+
208
+ # Process 0
209
+ if RANK in {-1, 0}:
210
+ val_loader = create_dataloader(val_path,
211
+ imgsz,
212
+ batch_size // WORLD_SIZE * 2,
213
+ gs,
214
+ single_cls,
215
+ hyp=hyp,
216
+ cache=None if noval else opt.cache,
217
+ rect=True,
218
+ rank=-1,
219
+ workers=workers * 2,
220
+ pad=0.5,
221
+ prefix=colorstr('val: '))[0]
222
+
223
+ if not resume:
224
+ if not opt.noautoanchor:
225
+ check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) # run AutoAnchor
226
+ model.half().float() # pre-reduce anchor precision
227
+
228
+ callbacks.run('on_pretrain_routine_end', labels, names)
229
+
230
+ # DDP mode
231
+ if cuda and RANK != -1:
232
+ model = smart_DDP(model)
233
+
234
+ # Model attributes
235
+ nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
236
+ hyp['box'] *= 3 / nl # scale to layers
237
+ hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers
238
+ hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
239
+ hyp['label_smoothing'] = opt.label_smoothing
240
+ model.nc = nc # attach number of classes to model
241
+ model.hyp = hyp # attach hyperparameters to model
242
+ model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
243
+ model.names = names
244
+
245
+ # Start training
246
+ t0 = time.time()
247
+ nb = len(train_loader) # number of batches
248
+ nw = max(round(hyp['warmup_epochs'] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
249
+ # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
250
+ last_opt_step = -1
251
+ maps = np.zeros(nc) # mAP per class
252
+ results = (0, 0, 0, 0, 0, 0, 0) # P, R, [email protected], [email protected], val_loss(box, obj, cls)
253
+ scheduler.last_epoch = start_epoch - 1 # do not move
254
+ scaler = torch.cuda.amp.GradScaler(enabled=amp)
255
+ stopper, stop = EarlyStopping(patience=opt.patience), False
256
+ compute_loss = ComputeLoss(model) # init loss class
257
+ callbacks.run('on_train_start')
258
+ LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
259
+ f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
260
+ f"Logging results to {colorstr('bold', save_dir)}\n"
261
+ f'Starting training for {epochs} epochs...')
262
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
263
+ callbacks.run('on_train_epoch_start')
264
+ model.train()
265
+
266
+ # Update image weights (optional, single-GPU only)
267
+ if opt.image_weights:
268
+ cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
269
+ iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
270
+ dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
271
+
272
+ # Update mosaic border (optional)
273
+ # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
274
+ # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
275
+
276
+ mloss = torch.zeros(3, device=device) # mean losses
277
+ if RANK != -1:
278
+ train_loader.sampler.set_epoch(epoch)
279
+ pbar = enumerate(train_loader)
280
+ LOGGER.info(('\n' + '%11s' * 7) % ('Epoch', 'GPU_mem', 'box_loss', 'obj_loss', 'cls_loss', 'Instances', 'Size'))
281
+ if RANK in {-1, 0}:
282
+ pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar
283
+ optimizer.zero_grad()
284
+ for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
285
+ callbacks.run('on_train_batch_start')
286
+ ni = i + nb * epoch # number integrated batches (since train start)
287
+ imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
288
+
289
+ # Warmup
290
+ if ni <= nw:
291
+ xi = [0, nw] # x interp
292
+ # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
293
+ accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
294
+ for j, x in enumerate(optimizer.param_groups):
295
+ # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
296
+ x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 0 else 0.0, x['initial_lr'] * lf(epoch)])
297
+ if 'momentum' in x:
298
+ x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
299
+
300
+ # Multi-scale
301
+ if opt.multi_scale:
302
+ sz = random.randrange(int(imgsz * 0.5), int(imgsz * 1.5) + gs) // gs * gs # size
303
+ sf = sz / max(imgs.shape[2:]) # scale factor
304
+ if sf != 1:
305
+ ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
306
+ imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
307
+
308
+ # Forward
309
+ with torch.cuda.amp.autocast(amp):
310
+ pred = model(imgs) # forward
311
+ loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
312
+ if RANK != -1:
313
+ loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
314
+ if opt.quad:
315
+ loss *= 4.
316
+
317
+ # Backward
318
+ scaler.scale(loss).backward()
319
+
320
+ # Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
321
+ if ni - last_opt_step >= accumulate:
322
+ scaler.unscale_(optimizer) # unscale gradients
323
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
324
+ scaler.step(optimizer) # optimizer.step
325
+ scaler.update()
326
+ optimizer.zero_grad()
327
+ if ema:
328
+ ema.update(model)
329
+ last_opt_step = ni
330
+
331
+ # Log
332
+ if RANK in {-1, 0}:
333
+ mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
334
+ mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
335
+ pbar.set_description(('%11s' * 2 + '%11.4g' * 5) %
336
+ (f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1]))
337
+ callbacks.run('on_train_batch_end', model, ni, imgs, targets, paths, list(mloss))
338
+ if callbacks.stop_training:
339
+ return
340
+ # end batch ------------------------------------------------------------------------------------------------
341
+
342
+ # Scheduler
343
+ lr = [x['lr'] for x in optimizer.param_groups] # for loggers
344
+ scheduler.step()
345
+
346
+ if RANK in {-1, 0}:
347
+ # mAP
348
+ callbacks.run('on_train_epoch_end', epoch=epoch)
349
+ ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights'])
350
+ final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
351
+ if not noval or final_epoch: # Calculate mAP
352
+ results, maps, _ = validate.run(data_dict,
353
+ batch_size=batch_size // WORLD_SIZE * 2,
354
+ imgsz=imgsz,
355
+ half=amp,
356
+ model=ema.ema,
357
+ single_cls=single_cls,
358
+ dataloader=val_loader,
359
+ save_dir=save_dir,
360
+ plots=False,
361
+ callbacks=callbacks,
362
+ compute_loss=compute_loss)
363
+
364
+ # Update best mAP
365
+ fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, [email protected], [email protected]]
366
+ stop = stopper(epoch=epoch, fitness=fi) # early stop check
367
+ if fi > best_fitness:
368
+ best_fitness = fi
369
+ log_vals = list(mloss) + list(results) + lr
370
+ callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
371
+
372
+ # Save model
373
+ if (not nosave) or (final_epoch and not evolve): # if save
374
+ ckpt = {
375
+ 'epoch': epoch,
376
+ 'best_fitness': best_fitness,
377
+ 'model': deepcopy(de_parallel(model)).half(),
378
+ 'ema': deepcopy(ema.ema).half(),
379
+ 'updates': ema.updates,
380
+ 'optimizer': optimizer.state_dict(),
381
+ 'opt': vars(opt),
382
+ 'git': GIT_INFO, # {remote, branch, commit} if a git repo
383
+ 'date': datetime.now().isoformat()}
384
+
385
+ # Save last, best and delete
386
+ torch.save(ckpt, last)
387
+ if best_fitness == fi:
388
+ torch.save(ckpt, best)
389
+ if opt.save_period > 0 and epoch % opt.save_period == 0:
390
+ torch.save(ckpt, w / f'epoch{epoch}.pt')
391
+ del ckpt
392
+ callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
393
+
394
+ # EarlyStopping
395
+ if RANK != -1: # if DDP training
396
+ broadcast_list = [stop if RANK == 0 else None]
397
+ dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
398
+ if RANK != 0:
399
+ stop = broadcast_list[0]
400
+ if stop:
401
+ break # must break all DDP ranks
402
+
403
+ # end epoch ----------------------------------------------------------------------------------------------------
404
+ # end training -----------------------------------------------------------------------------------------------------
405
+ if RANK in {-1, 0}:
406
+ LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.')
407
+ for f in last, best:
408
+ if f.exists():
409
+ strip_optimizer(f) # strip optimizers
410
+ if f is best:
411
+ LOGGER.info(f'\nValidating {f}...')
412
+ results, _, _ = validate.run(
413
+ data_dict,
414
+ batch_size=batch_size // WORLD_SIZE * 2,
415
+ imgsz=imgsz,
416
+ model=attempt_load(f, device).half(),
417
+ iou_thres=0.65 if is_coco else 0.60, # best pycocotools at iou 0.65
418
+ single_cls=single_cls,
419
+ dataloader=val_loader,
420
+ save_dir=save_dir,
421
+ save_json=is_coco,
422
+ verbose=True,
423
+ plots=plots,
424
+ callbacks=callbacks,
425
+ compute_loss=compute_loss) # val best model with plots
426
+ if is_coco:
427
+ callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
428
+
429
+ callbacks.run('on_train_end', last, best, epoch, results)
430
+
431
+ torch.cuda.empty_cache()
432
+ return results
433
+
434
+
435
+ def parse_opt(known=False):
436
+ parser = argparse.ArgumentParser()
437
+ parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path')
438
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
439
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
440
+ parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path')
441
+ parser.add_argument('--epochs', type=int, default=100, help='total training epochs')
442
+ parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch')
443
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)')
444
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
445
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
446
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
447
+ parser.add_argument('--noval', action='store_true', help='only validate final epoch')
448
+ parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
449
+ parser.add_argument('--noplots', action='store_true', help='save no plot files')
450
+ parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
451
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
452
+ parser.add_argument('--cache', type=str, nargs='?', const='ram', help='image --cache ram/disk')
453
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
454
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
455
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
456
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
457
+ parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
458
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
459
+ parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
460
+ parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name')
461
+ parser.add_argument('--name', default='exp', help='save to project/name')
462
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
463
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
464
+ parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
465
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
466
+ parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
467
+ parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
468
+ parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
469
+ parser.add_argument('--seed', type=int, default=0, help='Global training seed')
470
+ parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
471
+
472
+ # Logger arguments
473
+ parser.add_argument('--entity', default=None, help='Entity')
474
+ parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='Upload data, "val" option')
475
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval')
476
+ parser.add_argument('--artifact_alias', type=str, default='latest', help='Version of dataset artifact to use')
477
+
478
+ return parser.parse_known_args()[0] if known else parser.parse_args()
479
+
480
+
481
+ def main(opt, callbacks=Callbacks()):
482
+ # Checks
483
+ if RANK in {-1, 0}:
484
+ print_args(vars(opt))
485
+ check_git_status()
486
+ check_requirements()
487
+
488
+ # Resume (from specified or most recent last.pt)
489
+ if opt.resume and not check_comet_resume(opt) and not opt.evolve:
490
+ last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run())
491
+ opt_yaml = last.parent.parent / 'opt.yaml' # train options yaml
492
+ opt_data = opt.data # original dataset
493
+ if opt_yaml.is_file():
494
+ with open(opt_yaml, errors='ignore') as f:
495
+ d = yaml.safe_load(f)
496
+ else:
497
+ d = torch.load(last, map_location='cpu')['opt']
498
+ opt = argparse.Namespace(**d) # replace
499
+ opt.cfg, opt.weights, opt.resume = '', str(last), True # reinstate
500
+ if is_url(opt_data):
501
+ opt.data = check_file(opt_data) # avoid HUB resume auth timeout
502
+ else:
503
+ opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \
504
+ check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks
505
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
506
+ if opt.evolve:
507
+ if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve
508
+ opt.project = str(ROOT / 'runs/evolve')
509
+ opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
510
+ if opt.name == 'cfg':
511
+ opt.name = Path(opt.cfg).stem # use model.yaml as name
512
+ opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
513
+
514
+ # DDP mode
515
+ device = select_device(opt.device, batch_size=opt.batch_size)
516
+ if LOCAL_RANK != -1:
517
+ msg = 'is not compatible with YOLOv5 Multi-GPU DDP training'
518
+ assert not opt.image_weights, f'--image-weights {msg}'
519
+ assert not opt.evolve, f'--evolve {msg}'
520
+ assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size'
521
+ assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
522
+ assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
523
+ torch.cuda.set_device(LOCAL_RANK)
524
+ device = torch.device('cuda', LOCAL_RANK)
525
+ dist.init_process_group(backend='nccl' if dist.is_nccl_available() else 'gloo')
526
+
527
+ # Train
528
+ if not opt.evolve:
529
+ train(opt.hyp, opt, device, callbacks)
530
+
531
+ # Evolve hyperparameters (optional)
532
+ else:
533
+ # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
534
+ meta = {
535
+ 'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
536
+ 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
537
+ 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
538
+ 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
539
+ 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
540
+ 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
541
+ 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
542
+ 'box': (1, 0.02, 0.2), # box loss gain
543
+ 'cls': (1, 0.2, 4.0), # cls loss gain
544
+ 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
545
+ 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
546
+ 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
547
+ 'iou_t': (0, 0.1, 0.7), # IoU training threshold
548
+ 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
549
+ 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
550
+ 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
551
+ 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
552
+ 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
553
+ 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
554
+ 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
555
+ 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
556
+ 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
557
+ 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
558
+ 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
559
+ 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
560
+ 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
561
+ 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
562
+ 'mixup': (1, 0.0, 1.0), # image mixup (probability)
563
+ 'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability)
564
+
565
+ with open(opt.hyp, errors='ignore') as f:
566
+ hyp = yaml.safe_load(f) # load hyps dict
567
+ if 'anchors' not in hyp: # anchors commented in hyp.yaml
568
+ hyp['anchors'] = 3
569
+ if opt.noautoanchor:
570
+ del hyp['anchors'], meta['anchors']
571
+ opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
572
+ # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
573
+ evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv'
574
+ if opt.bucket:
575
+ # download evolve.csv if exists
576
+ subprocess.run([
577
+ 'gsutil',
578
+ 'cp',
579
+ f'gs://{opt.bucket}/evolve.csv',
580
+ str(evolve_csv),])
581
+
582
+ for _ in range(opt.evolve): # generations to evolve
583
+ if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
584
+ # Select parent(s)
585
+ parent = 'single' # parent selection method: 'single' or 'weighted'
586
+ x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1)
587
+ n = min(5, len(x)) # number of previous results to consider
588
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
589
+ w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0)
590
+ if parent == 'single' or len(x) == 1:
591
+ # x = x[random.randint(0, n - 1)] # random selection
592
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
593
+ elif parent == 'weighted':
594
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
595
+
596
+ # Mutate
597
+ mp, s = 0.8, 0.2 # mutation probability, sigma
598
+ npr = np.random
599
+ npr.seed(int(time.time()))
600
+ g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
601
+ ng = len(meta)
602
+ v = np.ones(ng)
603
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
604
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
605
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
606
+ hyp[k] = float(x[i + 7] * v[i]) # mutate
607
+
608
+ # Constrain to limits
609
+ for k, v in meta.items():
610
+ hyp[k] = max(hyp[k], v[1]) # lower limit
611
+ hyp[k] = min(hyp[k], v[2]) # upper limit
612
+ hyp[k] = round(hyp[k], 5) # significant digits
613
+
614
+ # Train mutation
615
+ results = train(hyp.copy(), opt, device, callbacks)
616
+ callbacks = Callbacks()
617
+ # Write mutation results
618
+ keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss',
619
+ 'val/obj_loss', 'val/cls_loss')
620
+ print_mutation(keys, results, hyp.copy(), save_dir, opt.bucket)
621
+
622
+ # Plot results
623
+ plot_evolve(evolve_csv)
624
+ LOGGER.info(f'Hyperparameter evolution finished {opt.evolve} generations\n'
625
+ f"Results saved to {colorstr('bold', save_dir)}\n"
626
+ f'Usage example: $ python train.py --hyp {evolve_yaml}')
627
+
628
+
629
+ def run(**kwargs):
630
+ # Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
631
+ opt = parse_opt(True)
632
+ for k, v in kwargs.items():
633
+ setattr(opt, k, v)
634
+ main(opt)
635
+ return opt
636
+
637
+
638
+ if __name__ == '__main__':
639
+ opt = parse_opt()
640
+ main(opt)
val.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
2
+ """
3
+ Validate a trained YOLOv5 detection model on a detection dataset
4
+
5
+ Usage:
6
+ $ python val.py --weights yolov5s.pt --data coco128.yaml --img 640
7
+
8
+ Usage - formats:
9
+ $ python val.py --weights yolov5s.pt # PyTorch
10
+ yolov5s.torchscript # TorchScript
11
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
12
+ yolov5s_openvino_model # OpenVINO
13
+ yolov5s.engine # TensorRT
14
+ yolov5s.mlmodel # CoreML (macOS-only)
15
+ yolov5s_saved_model # TensorFlow SavedModel
16
+ yolov5s.pb # TensorFlow GraphDef
17
+ yolov5s.tflite # TensorFlow Lite
18
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
19
+ yolov5s_paddle_model # PaddlePaddle
20
+ """
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import subprocess
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+ import torch
31
+ from tqdm import tqdm
32
+
33
+ FILE = Path(__file__).resolve()
34
+ ROOT = FILE.parents[0] # YOLOv5 root directory
35
+ if str(ROOT) not in sys.path:
36
+ sys.path.append(str(ROOT)) # add ROOT to PATH
37
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
38
+
39
+ from models.common import DetectMultiBackend
40
+ from utils.callbacks import Callbacks
41
+ from utils.dataloaders import create_dataloader
42
+ from utils.general import (LOGGER, TQDM_BAR_FORMAT, Profile, check_dataset, check_img_size, check_requirements,
43
+ check_yaml, coco80_to_coco91_class, colorstr, increment_path, non_max_suppression,
44
+ print_args, scale_boxes, xywh2xyxy, xyxy2xywh)
45
+ from utils.metrics import ConfusionMatrix, ap_per_class, box_iou
46
+ from utils.plots import output_to_target, plot_images, plot_val_study
47
+ from utils.torch_utils import select_device, smart_inference_mode
48
+
49
+
50
+ def save_one_txt(predn, save_conf, shape, file):
51
+ # Save one txt result
52
+ gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
53
+ for *xyxy, conf, cls in predn.tolist():
54
+ xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
55
+ line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
56
+ with open(file, 'a') as f:
57
+ f.write(('%g ' * len(line)).rstrip() % line + '\n')
58
+
59
+
60
+ def save_one_json(predn, jdict, path, class_map):
61
+ # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}
62
+ image_id = int(path.stem) if path.stem.isnumeric() else path.stem
63
+ box = xyxy2xywh(predn[:, :4]) # xywh
64
+ box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
65
+ for p, b in zip(predn.tolist(), box.tolist()):
66
+ jdict.append({
67
+ 'image_id': image_id,
68
+ 'category_id': class_map[int(p[5])],
69
+ 'bbox': [round(x, 3) for x in b],
70
+ 'score': round(p[4], 5)})
71
+
72
+
73
+ def process_batch(detections, labels, iouv):
74
+ """
75
+ Return correct prediction matrix
76
+ Arguments:
77
+ detections (array[N, 6]), x1, y1, x2, y2, conf, class
78
+ labels (array[M, 5]), class, x1, y1, x2, y2
79
+ Returns:
80
+ correct (array[N, 10]), for 10 IoU levels
81
+ """
82
+ correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool)
83
+ iou = box_iou(labels[:, 1:], detections[:, :4])
84
+ correct_class = labels[:, 0:1] == detections[:, 5]
85
+ for i in range(len(iouv)):
86
+ x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match
87
+ if x[0].shape[0]:
88
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou]
89
+ if x[0].shape[0] > 1:
90
+ matches = matches[matches[:, 2].argsort()[::-1]]
91
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
92
+ # matches = matches[matches[:, 2].argsort()[::-1]]
93
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
94
+ correct[matches[:, 1].astype(int), i] = True
95
+ return torch.tensor(correct, dtype=torch.bool, device=iouv.device)
96
+
97
+
98
+ @smart_inference_mode()
99
+ def run(
100
+ data,
101
+ weights=None, # model.pt path(s)
102
+ batch_size=32, # batch size
103
+ imgsz=640, # inference size (pixels)
104
+ conf_thres=0.001, # confidence threshold
105
+ iou_thres=0.6, # NMS IoU threshold
106
+ max_det=300, # maximum detections per image
107
+ task='val', # train, val, test, speed or study
108
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
109
+ workers=8, # max dataloader workers (per RANK in DDP mode)
110
+ single_cls=False, # treat as single-class dataset
111
+ augment=False, # augmented inference
112
+ verbose=False, # verbose output
113
+ save_txt=False, # save results to *.txt
114
+ save_hybrid=False, # save label+prediction hybrid results to *.txt
115
+ save_conf=False, # save confidences in --save-txt labels
116
+ save_json=False, # save a COCO-JSON results file
117
+ project=ROOT / 'runs/val', # save to project/name
118
+ name='exp', # save to project/name
119
+ exist_ok=False, # existing project/name ok, do not increment
120
+ half=True, # use FP16 half-precision inference
121
+ dnn=False, # use OpenCV DNN for ONNX inference
122
+ model=None,
123
+ dataloader=None,
124
+ save_dir=Path(''),
125
+ plots=True,
126
+ callbacks=Callbacks(),
127
+ compute_loss=None,
128
+ ):
129
+ # Initialize/load model and set device
130
+ training = model is not None
131
+ if training: # called by train.py
132
+ device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
133
+ half &= device.type != 'cpu' # half precision only supported on CUDA
134
+ model.half() if half else model.float()
135
+ else: # called directly
136
+ device = select_device(device, batch_size=batch_size)
137
+
138
+ # Directories
139
+ save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
140
+ (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
141
+
142
+ # Load model
143
+ model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
144
+ stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
145
+ imgsz = check_img_size(imgsz, s=stride) # check image size
146
+ half = model.fp16 # FP16 supported on limited backends with CUDA
147
+ if engine:
148
+ batch_size = model.batch_size
149
+ else:
150
+ device = model.device
151
+ if not (pt or jit):
152
+ batch_size = 1 # export.py models default to batch-size 1
153
+ LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')
154
+
155
+ # Data
156
+ data = check_dataset(data) # check
157
+
158
+ # Configure
159
+ model.eval()
160
+ cuda = device.type != 'cpu'
161
+ is_coco = isinstance(data.get('val'), str) and data['val'].endswith(f'coco{os.sep}val2017.txt') # COCO dataset
162
+ nc = 1 if single_cls else int(data['nc']) # number of classes
163
+ iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for [email protected]:0.95
164
+ niou = iouv.numel()
165
+
166
+ # Dataloader
167
+ if not training:
168
+ if pt and not single_cls: # check --weights are trained on --data
169
+ ncm = model.model.nc
170
+ assert ncm == nc, f'{weights} ({ncm} classes) trained on different --data than what you passed ({nc} ' \
171
+ f'classes). Pass correct combination of --weights and --data that are trained together.'
172
+ model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup
173
+ pad, rect = (0.0, False) if task == 'speed' else (0.5, pt) # square inference for benchmarks
174
+ task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
175
+ dataloader = create_dataloader(data[task],
176
+ imgsz,
177
+ batch_size,
178
+ stride,
179
+ single_cls,
180
+ pad=pad,
181
+ rect=rect,
182
+ workers=workers,
183
+ prefix=colorstr(f'{task}: '))[0]
184
+
185
+ seen = 0
186
+ confusion_matrix = ConfusionMatrix(nc=nc)
187
+ names = model.names if hasattr(model, 'names') else model.module.names # get class names
188
+ if isinstance(names, (list, tuple)): # old format
189
+ names = dict(enumerate(names))
190
+ class_map = coco80_to_coco91_class() if is_coco else list(range(1000))
191
+ s = ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'P', 'R', 'mAP50', 'mAP50-95')
192
+ tp, fp, p, r, f1, mp, mr, map50, ap50, map = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
193
+ dt = Profile(), Profile(), Profile() # profiling times
194
+ loss = torch.zeros(3, device=device)
195
+ jdict, stats, ap, ap_class = [], [], [], []
196
+ callbacks.run('on_val_start')
197
+ pbar = tqdm(dataloader, desc=s, bar_format=TQDM_BAR_FORMAT) # progress bar
198
+ for batch_i, (im, targets, paths, shapes) in enumerate(pbar):
199
+ callbacks.run('on_val_batch_start')
200
+ with dt[0]:
201
+ if cuda:
202
+ im = im.to(device, non_blocking=True)
203
+ targets = targets.to(device)
204
+ im = im.half() if half else im.float() # uint8 to fp16/32
205
+ im /= 255 # 0 - 255 to 0.0 - 1.0
206
+ nb, _, height, width = im.shape # batch size, channels, height, width
207
+
208
+ # Inference
209
+ with dt[1]:
210
+ preds, train_out = model(im) if compute_loss else (model(im, augment=augment), None)
211
+
212
+ # Loss
213
+ if compute_loss:
214
+ loss += compute_loss(train_out, targets)[1] # box, obj, cls
215
+
216
+ # NMS
217
+ targets[:, 2:] *= torch.tensor((width, height, width, height), device=device) # to pixels
218
+ lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
219
+ with dt[2]:
220
+ preds = non_max_suppression(preds,
221
+ conf_thres,
222
+ iou_thres,
223
+ labels=lb,
224
+ multi_label=True,
225
+ agnostic=single_cls,
226
+ max_det=max_det)
227
+
228
+ # Metrics
229
+ for si, pred in enumerate(preds):
230
+ labels = targets[targets[:, 0] == si, 1:]
231
+ nl, npr = labels.shape[0], pred.shape[0] # number of labels, predictions
232
+ path, shape = Path(paths[si]), shapes[si][0]
233
+ correct = torch.zeros(npr, niou, dtype=torch.bool, device=device) # init
234
+ seen += 1
235
+
236
+ if npr == 0:
237
+ if nl:
238
+ stats.append((correct, *torch.zeros((2, 0), device=device), labels[:, 0]))
239
+ if plots:
240
+ confusion_matrix.process_batch(detections=None, labels=labels[:, 0])
241
+ continue
242
+
243
+ # Predictions
244
+ if single_cls:
245
+ pred[:, 5] = 0
246
+ predn = pred.clone()
247
+ scale_boxes(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred
248
+
249
+ # Evaluate
250
+ if nl:
251
+ tbox = xywh2xyxy(labels[:, 1:5]) # target boxes
252
+ scale_boxes(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels
253
+ labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
254
+ correct = process_batch(predn, labelsn, iouv)
255
+ if plots:
256
+ confusion_matrix.process_batch(predn, labelsn)
257
+ stats.append((correct, pred[:, 4], pred[:, 5], labels[:, 0])) # (correct, conf, pcls, tcls)
258
+
259
+ # Save/log
260
+ if save_txt:
261
+ save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')
262
+ if save_json:
263
+ save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionary
264
+ callbacks.run('on_val_image_end', pred, predn, path, names, im[si])
265
+
266
+ # Plot images
267
+ if plots and batch_i < 3:
268
+ plot_images(im, targets, paths, save_dir / f'val_batch{batch_i}_labels.jpg', names) # labels
269
+ plot_images(im, output_to_target(preds), paths, save_dir / f'val_batch{batch_i}_pred.jpg', names) # pred
270
+
271
+ callbacks.run('on_val_batch_end', batch_i, im, targets, paths, shapes, preds)
272
+
273
+ # Compute metrics
274
+ stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)] # to numpy
275
+ if len(stats) and stats[0].any():
276
+ tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
277
+ ap50, ap = ap[:, 0], ap.mean(1) # [email protected], [email protected]:0.95
278
+ mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
279
+ nt = np.bincount(stats[3].astype(int), minlength=nc) # number of targets per class
280
+
281
+ # Print results
282
+ pf = '%22s' + '%11i' * 2 + '%11.3g' * 4 # print format
283
+ LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
284
+ if nt.sum() == 0:
285
+ LOGGER.warning(f'WARNING ⚠️ no labels found in {task} set, can not compute metrics without labels')
286
+
287
+ # Print results per class
288
+ if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
289
+ for i, c in enumerate(ap_class):
290
+ LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
291
+
292
+ # Print speeds
293
+ t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
294
+ if not training:
295
+ shape = (batch_size, 3, imgsz, imgsz)
296
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t)
297
+
298
+ # Plots
299
+ if plots:
300
+ confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
301
+ callbacks.run('on_val_end', nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix)
302
+
303
+ # Save JSON
304
+ if save_json and len(jdict):
305
+ w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
306
+ anno_json = str(Path('../datasets/coco/annotations/instances_val2017.json')) # annotations
307
+ pred_json = str(save_dir / f'{w}_predictions.json') # predictions
308
+ LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...')
309
+ with open(pred_json, 'w') as f:
310
+ json.dump(jdict, f)
311
+
312
+ try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
313
+ check_requirements('pycocotools>=2.0.6')
314
+ from pycocotools.coco import COCO
315
+ from pycocotools.cocoeval import COCOeval
316
+
317
+ anno = COCO(anno_json) # init annotations api
318
+ pred = anno.loadRes(pred_json) # init predictions api
319
+ eval = COCOeval(anno, pred, 'bbox')
320
+ if is_coco:
321
+ eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.im_files] # image IDs to evaluate
322
+ eval.evaluate()
323
+ eval.accumulate()
324
+ eval.summarize()
325
+ map, map50 = eval.stats[:2] # update results ([email protected]:0.95, [email protected])
326
+ except Exception as e:
327
+ LOGGER.info(f'pycocotools unable to run: {e}')
328
+
329
+ # Return results
330
+ model.float() # for training
331
+ if not training:
332
+ s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
333
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
334
+ maps = np.zeros(nc) + map
335
+ for i, c in enumerate(ap_class):
336
+ maps[c] = ap[i]
337
+ return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
338
+
339
+
340
+ def parse_opt():
341
+ parser = argparse.ArgumentParser()
342
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
343
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
344
+ parser.add_argument('--batch-size', type=int, default=32, help='batch size')
345
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
346
+ parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold')
347
+ parser.add_argument('--iou-thres', type=float, default=0.6, help='NMS IoU threshold')
348
+ parser.add_argument('--max-det', type=int, default=300, help='maximum detections per image')
349
+ parser.add_argument('--task', default='val', help='train, val, test, speed or study')
350
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
351
+ parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
352
+ parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
353
+ parser.add_argument('--augment', action='store_true', help='augmented inference')
354
+ parser.add_argument('--verbose', action='store_true', help='report mAP by class')
355
+ parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
356
+ parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
357
+ parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
358
+ parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file')
359
+ parser.add_argument('--project', default=ROOT / 'runs/val', help='save to project/name')
360
+ parser.add_argument('--name', default='exp', help='save to project/name')
361
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
362
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
363
+ parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
364
+ opt = parser.parse_args()
365
+ opt.data = check_yaml(opt.data) # check YAML
366
+ opt.save_json |= opt.data.endswith('coco.yaml')
367
+ opt.save_txt |= opt.save_hybrid
368
+ print_args(vars(opt))
369
+ return opt
370
+
371
+
372
+ def main(opt):
373
+ check_requirements(exclude=('tensorboard', 'thop'))
374
+
375
+ if opt.task in ('train', 'val', 'test'): # run normally
376
+ if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466
377
+ LOGGER.info(f'WARNING ⚠️ confidence threshold {opt.conf_thres} > 0.001 produces invalid results')
378
+ if opt.save_hybrid:
379
+ LOGGER.info('WARNING ⚠️ --save-hybrid will return high mAP from hybrid labels, not from predictions alone')
380
+ run(**vars(opt))
381
+
382
+ else:
383
+ weights = opt.weights if isinstance(opt.weights, list) else [opt.weights]
384
+ opt.half = torch.cuda.is_available() and opt.device != 'cpu' # FP16 for fastest results
385
+ if opt.task == 'speed': # speed benchmarks
386
+ # python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt...
387
+ opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False
388
+ for opt.weights in weights:
389
+ run(**vars(opt), plots=False)
390
+
391
+ elif opt.task == 'study': # speed vs mAP benchmarks
392
+ # python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt...
393
+ for opt.weights in weights:
394
+ f = f'study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt' # filename to save to
395
+ x, y = list(range(256, 1536 + 128, 128)), [] # x axis (image sizes), y axis
396
+ for opt.imgsz in x: # img-size
397
+ LOGGER.info(f'\nRunning {f} --imgsz {opt.imgsz}...')
398
+ r, _, t = run(**vars(opt), plots=False)
399
+ y.append(r + t) # results and times
400
+ np.savetxt(f, y, fmt='%10.4g') # save
401
+ subprocess.run(['zip', '-r', 'study.zip', 'study_*.txt'])
402
+ plot_val_study(x=x) # plot
403
+ else:
404
+ raise NotImplementedError(f'--task {opt.task} not in ("train", "val", "test", "speed", "study")')
405
+
406
+
407
+ if __name__ == '__main__':
408
+ opt = parse_opt()
409
+ main(opt)