Unverified 提交 d9b4e6b7 authored 作者: Cristi Fati's avatar Cristi Fati 提交者: GitHub

Add `--include torchscript onnx coreml` argument (#3137)

* Allow users to skip exporting in formats that they don't care about * Correct comments * Update export.py renamed --skip-format to --exclude * Switched format from exclude to include (as instructed by @glenn-jocher) * cleanup Co-authored-by: 's avatarGlenn Jocher <glenn.jocher@ultralytics.com>
上级 bd6f6a78
"""Exports a YOLOv5 *.pt model to ONNX and TorchScript formats """Exports a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats
Usage: Usage:
$ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1 $ python path/to/models/export.py --weights yolov5s.pt --img 640 --batch 1
""" """
import argparse import argparse
...@@ -27,6 +27,7 @@ if __name__ == '__main__': ...@@ -27,6 +27,7 @@ if __name__ == '__main__':
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
parser.add_argument('--batch-size', type=int, default=1, help='batch size') parser.add_argument('--batch-size', type=int, default=1, help='batch size')
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats')
parser.add_argument('--half', action='store_true', help='FP16 half-precision export') parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
parser.add_argument('--train', action='store_true', help='model.train() mode') parser.add_argument('--train', action='store_true', help='model.train() mode')
...@@ -35,6 +36,7 @@ if __name__ == '__main__': ...@@ -35,6 +36,7 @@ if __name__ == '__main__':
parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
opt = parser.parse_args() opt = parser.parse_args()
opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
opt.include = [x.lower() for x in opt.include]
print(opt) print(opt)
set_logging() set_logging()
t = time.time() t = time.time()
...@@ -47,7 +49,7 @@ if __name__ == '__main__': ...@@ -47,7 +49,7 @@ if __name__ == '__main__':
# Checks # Checks
gs = int(max(model.stride)) # grid size (max stride) gs = int(max(model.stride)) # grid size (max stride)
opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
assert not (opt.device.lower() == "cpu" and opt.half), '--half only compatible with GPU export, i.e. use --device 0' assert not (opt.device.lower() == 'cpu' and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
# Input # Input
img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
...@@ -74,6 +76,7 @@ if __name__ == '__main__': ...@@ -74,6 +76,7 @@ if __name__ == '__main__':
print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)") print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
# TorchScript export ----------------------------------------------------------------------------------------------- # TorchScript export -----------------------------------------------------------------------------------------------
if 'torchscript' in opt.include or 'coreml' in opt.include:
prefix = colorstr('TorchScript:') prefix = colorstr('TorchScript:')
try: try:
print(f'\n{prefix} starting export with torch {torch.__version__}...') print(f'\n{prefix} starting export with torch {torch.__version__}...')
...@@ -85,6 +88,7 @@ if __name__ == '__main__': ...@@ -85,6 +88,7 @@ if __name__ == '__main__':
print(f'{prefix} export failure: {e}') print(f'{prefix} export failure: {e}')
# ONNX export ------------------------------------------------------------------------------------------------------ # ONNX export ------------------------------------------------------------------------------------------------------
if 'onnx' in opt.include:
prefix = colorstr('ONNX:') prefix = colorstr('ONNX:')
try: try:
import onnx import onnx
...@@ -107,7 +111,8 @@ if __name__ == '__main__': ...@@ -107,7 +111,8 @@ if __name__ == '__main__':
import onnxsim import onnxsim
print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
model_onnx, check = onnxsim.simplify(model_onnx, model_onnx, check = onnxsim.simplify(
model_onnx,
dynamic_input_shape=opt.dynamic, dynamic_input_shape=opt.dynamic,
input_shapes={'images': list(img.shape)} if opt.dynamic else None) input_shapes={'images': list(img.shape)} if opt.dynamic else None)
assert check, 'assert check failed' assert check, 'assert check failed'
...@@ -119,12 +124,13 @@ if __name__ == '__main__': ...@@ -119,12 +124,13 @@ if __name__ == '__main__':
print(f'{prefix} export failure: {e}') print(f'{prefix} export failure: {e}')
# CoreML export ---------------------------------------------------------------------------------------------------- # CoreML export ----------------------------------------------------------------------------------------------------
if 'coreml' in opt.include:
prefix = colorstr('CoreML:') prefix = colorstr('CoreML:')
try: try:
import coremltools as ct import coremltools as ct
print(f'{prefix} starting export with coremltools {ct.__version__}...') print(f'{prefix} starting export with coremltools {ct.__version__}...')
model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
f = opt.weights.replace('.pt', '.mlmodel') # filename f = opt.weights.replace('.pt', '.mlmodel') # filename
model.save(f) model.save(f)
print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论