2021-06-10 04:43:46 +08:00
|
|
|
"""Export a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats
|
2020-06-30 05:00:13 +08:00
|
|
|
|
|
|
|
Usage:
|
2021-06-21 23:25:04 +08:00
|
|
|
$ python path/to/export.py --weights yolov5s.pt --img 640 --batch 1
|
2020-06-30 05:00:13 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
import argparse
|
2020-10-05 00:50:32 +08:00
|
|
|
import sys
|
2020-10-06 20:54:02 +08:00
|
|
|
import time
|
2021-04-27 23:02:07 +08:00
|
|
|
from pathlib import Path
|
2020-10-05 00:50:32 +08:00
|
|
|
|
2020-08-03 06:47:36 +08:00
|
|
|
import torch
|
2020-08-25 12:59:26 +08:00
|
|
|
import torch.nn as nn
|
2021-04-24 03:21:58 +08:00
|
|
|
from torch.utils.mobile_optimizer import optimize_for_mobile
|
2020-08-03 06:47:36 +08:00
|
|
|
|
2021-06-10 21:35:22 +08:00
|
|
|
FILE = Path(__file__).absolute()
|
2021-06-21 23:25:04 +08:00
|
|
|
sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
|
2021-06-10 21:35:22 +08:00
|
|
|
|
|
|
|
from models.common import Conv
|
|
|
|
from models.yolo import Detect
|
2020-08-25 12:47:49 +08:00
|
|
|
from models.experimental import attempt_load
|
2020-12-17 09:55:57 +08:00
|
|
|
from utils.activations import Hardswish, SiLU
|
2021-04-24 07:31:11 +08:00
|
|
|
from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
|
2021-03-07 04:02:10 +08:00
|
|
|
from utils.torch_utils import select_device
|
2020-06-30 05:00:13 +08:00
|
|
|
|
2021-06-10 04:43:46 +08:00
|
|
|
|
2021-06-21 23:25:04 +08:00
|
|
|
def run(weights='./yolov5s.pt', # weights path
|
|
|
|
img_size=(640, 640), # image (height, width)
|
|
|
|
batch_size=1, # batch size
|
|
|
|
device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
|
|
|
include=('torchscript', 'onnx', 'coreml'), # include formats
|
|
|
|
half=False, # FP16 half-precision export
|
|
|
|
inplace=False, # set YOLOv5 Detect() inplace=True
|
|
|
|
train=False, # model.train() mode
|
|
|
|
optimize=False, # TorchScript: optimize for mobile
|
|
|
|
dynamic=False, # ONNX: dynamic axes
|
|
|
|
simplify=False, # ONNX: simplify model
|
|
|
|
opset_version=12, # ONNX: opset version
|
|
|
|
):
|
2020-10-06 20:54:02 +08:00
|
|
|
t = time.time()
|
2021-06-10 04:43:46 +08:00
|
|
|
include = [x.lower() for x in include]
|
|
|
|
img_size *= 2 if len(img_size) == 1 else 1 # expand
|
2020-06-30 05:00:13 +08:00
|
|
|
|
|
|
|
# Load PyTorch model
|
2021-06-10 04:43:46 +08:00
|
|
|
device = select_device(device)
|
2021-06-22 19:33:38 +08:00
|
|
|
assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
|
2021-06-10 04:43:46 +08:00
|
|
|
model = attempt_load(weights, map_location=device) # load FP32 model
|
2020-10-06 20:54:02 +08:00
|
|
|
labels = model.names
|
|
|
|
|
2021-06-08 16:22:10 +08:00
|
|
|
# Input
|
2020-10-06 20:54:02 +08:00
|
|
|
gs = int(max(model.stride)) # grid size (max stride)
|
2021-06-10 04:43:46 +08:00
|
|
|
img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples
|
|
|
|
img = torch.zeros(batch_size, 3, *img_size).to(device) # image size(1,3,320,192) iDetection
|
2020-10-11 22:23:36 +08:00
|
|
|
|
2020-08-25 10:27:54 +08:00
|
|
|
# Update model
|
2021-06-10 04:43:46 +08:00
|
|
|
if half:
|
2021-05-03 04:42:33 +08:00
|
|
|
img, model = img.half(), model.half() # to FP16
|
2021-06-10 04:43:46 +08:00
|
|
|
model.train() if train else model.eval() # training mode = no Detect() layer grid construction
|
2020-08-25 12:47:49 +08:00
|
|
|
for k, m in model.named_modules():
|
2020-10-06 20:54:02 +08:00
|
|
|
m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
|
2021-06-10 21:35:22 +08:00
|
|
|
if isinstance(m, Conv): # assign export-friendly activations
|
2020-12-17 09:55:57 +08:00
|
|
|
if isinstance(m.act, nn.Hardswish):
|
|
|
|
m.act = Hardswish()
|
|
|
|
elif isinstance(m.act, nn.SiLU):
|
|
|
|
m.act = SiLU()
|
2021-06-10 21:35:22 +08:00
|
|
|
elif isinstance(m, Detect):
|
2021-06-10 04:43:46 +08:00
|
|
|
m.inplace = inplace
|
|
|
|
m.onnx_dynamic = dynamic
|
2021-05-04 01:01:29 +08:00
|
|
|
# m.forward = m.forward_export # assign forward (optional)
|
|
|
|
|
2021-04-24 06:10:38 +08:00
|
|
|
for _ in range(2):
|
|
|
|
y = model(img) # dry runs
|
2021-06-10 04:43:46 +08:00
|
|
|
print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)")
|
2020-06-30 05:00:13 +08:00
|
|
|
|
2021-04-20 19:54:03 +08:00
|
|
|
# TorchScript export -----------------------------------------------------------------------------------------------
|
2021-06-10 04:43:46 +08:00
|
|
|
if 'torchscript' in include or 'coreml' in include:
|
2021-05-13 01:46:32 +08:00
|
|
|
prefix = colorstr('TorchScript:')
|
|
|
|
try:
|
|
|
|
print(f'\n{prefix} starting export with torch {torch.__version__}...')
|
2021-06-10 04:43:46 +08:00
|
|
|
f = weights.replace('.pt', '.torchscript.pt') # filename
|
2021-05-13 01:46:32 +08:00
|
|
|
ts = torch.jit.trace(model, img, strict=False)
|
2021-06-10 04:43:46 +08:00
|
|
|
(optimize_for_mobile(ts) if optimize else ts).save(f)
|
2021-05-13 01:46:32 +08:00
|
|
|
print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
|
|
|
except Exception as e:
|
|
|
|
print(f'{prefix} export failure: {e}')
|
2020-06-30 05:00:13 +08:00
|
|
|
|
2021-04-20 19:54:03 +08:00
|
|
|
# ONNX export ------------------------------------------------------------------------------------------------------
|
2021-06-10 04:43:46 +08:00
|
|
|
if 'onnx' in include:
|
2021-05-13 01:46:32 +08:00
|
|
|
prefix = colorstr('ONNX:')
|
|
|
|
try:
|
|
|
|
import onnx
|
|
|
|
|
|
|
|
print(f'{prefix} starting export with onnx {onnx.__version__}...')
|
2021-06-10 04:43:46 +08:00
|
|
|
f = weights.replace('.pt', '.onnx') # filename
|
|
|
|
torch.onnx.export(model, img, f, verbose=False, opset_version=opset_version,
|
|
|
|
training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
|
|
|
|
do_constant_folding=not train,
|
2021-06-08 16:22:10 +08:00
|
|
|
input_names=['images'],
|
|
|
|
output_names=['output'],
|
|
|
|
dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
|
|
|
|
'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
|
2021-06-10 04:43:46 +08:00
|
|
|
} if dynamic else None)
|
2021-05-13 01:46:32 +08:00
|
|
|
|
|
|
|
# Checks
|
|
|
|
model_onnx = onnx.load(f) # load onnx model
|
|
|
|
onnx.checker.check_model(model_onnx) # check onnx model
|
|
|
|
# print(onnx.helper.printable_graph(model_onnx.graph)) # print
|
|
|
|
|
|
|
|
# Simplify
|
2021-06-10 04:43:46 +08:00
|
|
|
if simplify:
|
2021-05-13 01:46:32 +08:00
|
|
|
try:
|
|
|
|
check_requirements(['onnx-simplifier'])
|
|
|
|
import onnxsim
|
|
|
|
|
|
|
|
print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
|
|
|
|
model_onnx, check = onnxsim.simplify(
|
|
|
|
model_onnx,
|
2021-06-10 04:43:46 +08:00
|
|
|
dynamic_input_shape=dynamic,
|
|
|
|
input_shapes={'images': list(img.shape)} if dynamic else None)
|
2021-05-13 01:46:32 +08:00
|
|
|
assert check, 'assert check failed'
|
|
|
|
onnx.save(model_onnx, f)
|
|
|
|
except Exception as e:
|
|
|
|
print(f'{prefix} simplifier failure: {e}')
|
|
|
|
print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
|
|
|
except Exception as e:
|
|
|
|
print(f'{prefix} export failure: {e}')
|
2020-07-04 02:50:59 +08:00
|
|
|
|
2021-04-20 19:54:03 +08:00
|
|
|
# CoreML export ----------------------------------------------------------------------------------------------------
|
2021-06-10 04:43:46 +08:00
|
|
|
if 'coreml' in include:
|
2021-05-13 01:46:32 +08:00
|
|
|
prefix = colorstr('CoreML:')
|
|
|
|
try:
|
|
|
|
import coremltools as ct
|
|
|
|
|
|
|
|
print(f'{prefix} starting export with coremltools {ct.__version__}...')
|
2021-06-10 04:43:46 +08:00
|
|
|
assert train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`'
|
2021-05-13 01:46:32 +08:00
|
|
|
model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
|
2021-06-10 04:43:46 +08:00
|
|
|
f = weights.replace('.pt', '.mlmodel') # filename
|
2021-05-13 01:46:32 +08:00
|
|
|
model.save(f)
|
|
|
|
print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
|
|
|
|
except Exception as e:
|
|
|
|
print(f'{prefix} export failure: {e}')
|
2020-07-05 08:13:43 +08:00
|
|
|
|
2020-07-04 02:50:59 +08:00
|
|
|
# Finish
|
2021-04-16 20:03:27 +08:00
|
|
|
print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
|
2021-06-10 04:43:46 +08:00
|
|
|
|
|
|
|
|
2021-06-19 18:06:59 +08:00
|
|
|
def parse_opt():
|
2021-06-10 04:43:46 +08:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
|
|
|
|
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)')
|
|
|
|
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('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats')
|
|
|
|
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('--train', action='store_true', help='model.train() mode')
|
|
|
|
parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
|
|
|
|
parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes')
|
|
|
|
parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
|
|
|
|
parser.add_argument('--opset-version', type=int, default=12, help='ONNX: opset version')
|
|
|
|
opt = parser.parse_args()
|
2021-06-19 18:06:59 +08:00
|
|
|
return opt
|
|
|
|
|
|
|
|
|
|
|
|
def main(opt):
|
2021-06-10 04:43:46 +08:00
|
|
|
set_logging()
|
2021-06-19 22:30:25 +08:00
|
|
|
print(colorstr('export: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
|
2021-06-21 23:25:04 +08:00
|
|
|
run(**vars(opt))
|
2021-06-19 18:06:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
opt = parse_opt()
|
|
|
|
main(opt)
|