2020-07-02 06:46:15 +08:00
|
|
|
"""Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
|
2020-06-30 05:00:13 +08:00
|
|
|
|
|
|
|
Usage:
|
2021-04-16 20:03:27 +08:00
|
|
|
$ export PYTHONPATH="$PWD" && python models/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
|
2020-10-05 00:50:32 +08:00
|
|
|
|
|
|
|
sys.path.append('./') # to run '$ python *.py' files in subdirectories
|
2020-06-30 05:00:13 +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
|
|
|
|
2020-09-03 04:23:29 +08:00
|
|
|
import models
|
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-16 20:03:27 +08:00
|
|
|
from utils.general import colorstr, check_img_size, check_requirements, 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
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
parser = argparse.ArgumentParser()
|
2021-04-20 19:54:03 +08:00
|
|
|
parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
|
2020-08-26 14:07:22 +08:00
|
|
|
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
|
2020-06-30 05:00:13 +08:00
|
|
|
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
2021-03-07 04:02:10 +08:00
|
|
|
parser.add_argument('--grid', action='store_true', help='export Detect() layer grid')
|
|
|
|
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
2021-04-20 19:54:03 +08:00
|
|
|
parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
|
|
|
|
parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
|
2020-06-30 05:00:13 +08:00
|
|
|
opt = parser.parse_args()
|
|
|
|
opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
|
|
|
|
print(opt)
|
2020-08-13 05:18:19 +08:00
|
|
|
set_logging()
|
2020-10-06 20:54:02 +08:00
|
|
|
t = time.time()
|
2020-06-30 05:00:13 +08:00
|
|
|
|
|
|
|
# Load PyTorch model
|
2021-03-07 04:02:10 +08:00
|
|
|
device = select_device(opt.device)
|
|
|
|
model = attempt_load(opt.weights, map_location=device) # load FP32 model
|
2020-10-06 20:54:02 +08:00
|
|
|
labels = model.names
|
|
|
|
|
|
|
|
# Checks
|
|
|
|
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
|
2020-08-25 10:27:54 +08:00
|
|
|
|
2020-10-11 22:23:36 +08:00
|
|
|
# Input
|
2021-03-07 04:02:10 +08:00
|
|
|
img = torch.zeros(opt.batch_size, 3, *opt.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
|
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
|
2020-12-17 09:55:57 +08:00
|
|
|
if isinstance(m, models.common.Conv): # assign export-friendly activations
|
|
|
|
if isinstance(m.act, nn.Hardswish):
|
|
|
|
m.act = Hardswish()
|
|
|
|
elif isinstance(m.act, nn.SiLU):
|
|
|
|
m.act = SiLU()
|
|
|
|
# elif isinstance(m, models.yolo.Detect):
|
2020-09-03 04:23:29 +08:00
|
|
|
# m.forward = m.forward_export # assign forward (optional)
|
2021-03-07 04:02:10 +08:00
|
|
|
model.model[-1].export = not opt.grid # set Detect() layer grid export
|
2020-07-04 11:05:50 +08:00
|
|
|
y = model(img) # dry run
|
2020-06-30 05:00:13 +08:00
|
|
|
|
2021-04-20 19:54:03 +08:00
|
|
|
# TorchScript export -----------------------------------------------------------------------------------------------
|
2021-04-16 20:03:27 +08:00
|
|
|
prefix = colorstr('TorchScript:')
|
2020-06-30 05:00:13 +08:00
|
|
|
try:
|
2021-04-16 20:03:27 +08:00
|
|
|
print(f'\n{prefix} starting export with torch {torch.__version__}...')
|
2020-07-11 02:56:01 +08:00
|
|
|
f = opt.weights.replace('.pt', '.torchscript.pt') # filename
|
2021-04-12 05:11:43 +08:00
|
|
|
ts = torch.jit.trace(model, img, strict=False)
|
2021-04-24 03:21:58 +08:00
|
|
|
ts = optimize_for_mobile(ts) # https://pytorch.org/tutorials/recipes/script_optimized.html
|
2020-06-30 05:00:13 +08:00
|
|
|
ts.save(f)
|
2021-04-16 20:03:27 +08:00
|
|
|
print(f'{prefix} export success, saved as {f}')
|
2020-07-02 06:46:15 +08:00
|
|
|
except Exception as e:
|
2021-04-16 20:03:27 +08:00
|
|
|
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-04-16 20:03:27 +08:00
|
|
|
prefix = colorstr('ONNX:')
|
2020-06-30 05:00:13 +08:00
|
|
|
try:
|
2020-07-02 07:14:49 +08:00
|
|
|
import onnx
|
|
|
|
|
2021-04-16 20:03:27 +08:00
|
|
|
print(f'{prefix} starting export with onnx {onnx.__version__}...')
|
2020-06-30 05:00:13 +08:00
|
|
|
f = opt.weights.replace('.pt', '.onnx') # filename
|
2020-07-02 06:46:15 +08:00
|
|
|
torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
|
2021-02-22 13:50:44 +08:00
|
|
|
output_names=['classes', 'boxes'] if y is None else ['output'],
|
|
|
|
dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
|
|
|
|
'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
|
2020-06-30 05:00:13 +08:00
|
|
|
|
|
|
|
# Checks
|
2021-04-16 20:03:27 +08:00
|
|
|
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-04-20 19:54:03 +08:00
|
|
|
if opt.simplify:
|
|
|
|
try:
|
|
|
|
check_requirements(['onnx-simplifier'])
|
|
|
|
import onnxsim
|
|
|
|
|
|
|
|
print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
|
|
|
|
model_onnx, check = onnxsim.simplify(model_onnx,
|
|
|
|
dynamic_input_shape=opt.dynamic,
|
|
|
|
input_shapes={'images': list(img.shape)} if opt.dynamic else None)
|
|
|
|
assert check, 'assert check failed'
|
|
|
|
onnx.save(model_onnx, f)
|
|
|
|
except Exception as e:
|
|
|
|
print(f'{prefix} simplifier failure: {e}')
|
2021-04-16 20:03:27 +08:00
|
|
|
print(f'{prefix} export success, saved as {f}')
|
2020-07-02 06:46:15 +08:00
|
|
|
except Exception as e:
|
2021-04-16 20:03:27 +08:00
|
|
|
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-04-16 20:03:27 +08:00
|
|
|
prefix = colorstr('CoreML:')
|
2020-07-05 08:13:43 +08:00
|
|
|
try:
|
|
|
|
import coremltools as ct
|
|
|
|
|
2021-04-24 05:50:02 +08:00
|
|
|
print(f'{prefix} starting export with coremltools {ct.__version__}...')
|
2020-07-08 14:43:33 +08:00
|
|
|
# convert model from torchscript and apply pixel scaling as per detect.py
|
2020-10-06 20:54:02 +08:00
|
|
|
model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
|
2020-07-05 08:13:43 +08:00
|
|
|
f = opt.weights.replace('.pt', '.mlmodel') # filename
|
|
|
|
model.save(f)
|
2021-04-16 20:03:27 +08:00
|
|
|
print(f'{prefix} export success, saved as {f}')
|
2020-07-05 08:13:43 +08:00
|
|
|
except Exception as e:
|
2021-04-16 20:03:27 +08:00
|
|
|
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.')
|