yolov5/models/export.py

105 lines
4.3 KiB
Python
Raw Normal View History

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:
$ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
"""
import argparse
import sys
2020-10-06 20:54:02 +08:00
import time
sys.path.append('./') # to run '$ python *.py' files in subdirectories
2020-06-30 05:00:13 +08:00
import torch
import torch.nn as nn
2020-09-03 04:23:29 +08:00
import models
from models.experimental import attempt_load
2020-12-17 09:55:57 +08:00
from utils.activations import Hardswish, SiLU
2020-10-06 20:54:02 +08:00
from utils.general import set_logging, check_img_size
from utils.torch_utils import select_device
2020-06-30 05:00:13 +08:00
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') # from yolov5/models/
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')
parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes')
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')
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)
set_logging()
2020-10-06 20:54:02 +08:00
t = time.time()
2020-06-30 05:00:13 +08:00
# Load PyTorch model
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
# Input
img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
2020-08-25 10:27:54 +08:00
# Update model
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)
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
2020-07-02 07:14:49 +08:00
# TorchScript export
2020-06-30 05:00:13 +08:00
try:
2020-07-04 02:50:59 +08:00
print('\nStarting TorchScript export with torch %s...' % torch.__version__)
f = opt.weights.replace('.pt', '.torchscript.pt') # filename
ts = torch.jit.trace(model, img, strict=False)
2020-06-30 05:00:13 +08:00
ts.save(f)
2020-07-02 06:46:15 +08:00
print('TorchScript export success, saved as %s' % f)
except Exception as e:
2020-07-04 11:05:50 +08:00
print('TorchScript export failure: %s' % e)
2020-06-30 05:00:13 +08:00
2020-07-02 07:14:49 +08:00
# ONNX export
2020-06-30 05:00:13 +08:00
try:
2020-07-02 07:14:49 +08:00
import onnx
2020-07-04 02:29:53 +08:00
print('\nStarting ONNX export with onnx %s...' % 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'],
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
onnx_model = onnx.load(f) # load onnx model
onnx.checker.check_model(onnx_model) # check onnx model
# print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
2020-07-04 02:50:59 +08:00
print('ONNX export success, saved as %s' % f)
2020-07-02 06:46:15 +08:00
except Exception as e:
2020-07-04 11:05:50 +08:00
print('ONNX export failure: %s' % e)
2020-07-04 02:50:59 +08:00
2020-07-05 08:13:43 +08:00
# CoreML export
try:
import coremltools as ct
print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
# 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)
print('CoreML export success, saved as %s' % f)
except Exception as e:
print('CoreML export failure: %s' % e)
2020-07-04 02:50:59 +08:00
# Finish
2020-10-06 20:54:02 +08:00
print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))