Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/export.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit34Format | Example | `--include ...` argument5--- | --- | ---6PyTorch | yolov5s.pt | -7TorchScript | yolov5s.torchscript | `torchscript`8ONNX | yolov5s.onnx | `onnx`9CoreML | yolov5s.mlmodel | `coreml`10OpenVINO | yolov5s_openvino_model/ | `openvino`11TensorFlow SavedModel | yolov5s_saved_model/ | `saved_model`12TensorFlow GraphDef | yolov5s.pb | `pb`13TensorFlow Lite | yolov5s.tflite | `tflite`14TensorFlow.js | yolov5s_web_model/ | `tfjs`15TensorRT | yolov5s.engine | `engine`1617Usage:18$ python path/to/export.py --weights yolov5s.pt --include torchscript onnx coreml openvino saved_model tflite tfjs1920Inference:21$ python path/to/detect.py --weights yolov5s.pt22yolov5s.torchscript23yolov5s.onnx24yolov5s.mlmodel (under development)25yolov5s_openvino_model (under development)26yolov5s_saved_model27yolov5s.pb28yolov5s.tflite29yolov5s.engine3031TensorFlow.js:32$ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example33$ npm install34$ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model35$ npm start36"""3738import argparse39import json40import os41import subprocess42import sys43import time44from pathlib import Path4546import torch47import torch.nn as nn48from torch.utils.mobile_optimizer import optimize_for_mobile4950FILE = Path(__file__).resolve()51ROOT = FILE.parents[0] # YOLOv5 root directory52if str(ROOT) not in sys.path:53sys.path.append(str(ROOT)) # add ROOT to PATH54ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative5556from models.common import Conv57from models.experimental import attempt_load58from models.yolo import Detect59from utils.activations import SiLU60from utils.datasets import LoadImages61from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, colorstr, file_size, print_args,62url2file)63from utils.torch_utils import select_device646566def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):67# YOLOv5 TorchScript model export68try:69LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')70f = file.with_suffix('.torchscript')7172ts = torch.jit.trace(model, im, strict=False)73d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}74extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()75(optimize_for_mobile(ts) if optimize else ts).save(str(f), _extra_files=extra_files)7677LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')78except Exception as e:79LOGGER.info(f'{prefix} export failure: {e}')808182def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):83# YOLOv5 ONNX export84try:85check_requirements(('onnx',))86import onnx8788LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')89f = file.with_suffix('.onnx')9091torch.onnx.export(model, im, f, verbose=False, opset_version=opset,92training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,93do_constant_folding=not train,94input_names=['images'],95output_names=['output'],96dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)97'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)98} if dynamic else None)99100# Checks101model_onnx = onnx.load(f) # load onnx model102onnx.checker.check_model(model_onnx) # check onnx model103# LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print104105# Simplify106if simplify:107try:108check_requirements(('onnx-simplifier',))109import onnxsim110111LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')112model_onnx, check = onnxsim.simplify(113model_onnx,114dynamic_input_shape=dynamic,115input_shapes={'images': list(im.shape)} if dynamic else None)116assert check, 'assert check failed'117onnx.save(model_onnx, f)118except Exception as e:119LOGGER.info(f'{prefix} simplifier failure: {e}')120LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')121LOGGER.info(f"{prefix} run --dynamic ONNX model inference with: 'python detect.py --weights {f}'")122except Exception as e:123LOGGER.info(f'{prefix} export failure: {e}')124125126def export_coreml(model, im, file, prefix=colorstr('CoreML:')):127# YOLOv5 CoreML export128ct_model = None129try:130check_requirements(('coremltools',))131import coremltools as ct132133LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')134f = file.with_suffix('.mlmodel')135136model.train() # CoreML exports should be placed in model.train() mode137ts = torch.jit.trace(model, im, strict=False) # TorchScript model138ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])139ct_model.save(f)140141LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')142except Exception as e:143LOGGER.info(f'\n{prefix} export failure: {e}')144145return ct_model146147148def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')):149# YOLOv5 OpenVINO export150try:151check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/152import openvino.inference_engine as ie153154LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')155f = str(file).replace('.pt', '_openvino_model' + os.sep)156157cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}"158subprocess.check_output(cmd, shell=True)159160LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')161except Exception as e:162LOGGER.info(f'\n{prefix} export failure: {e}')163164165def export_saved_model(model, im, file, dynamic,166tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,167conf_thres=0.25, prefix=colorstr('TensorFlow saved_model:')):168# YOLOv5 TensorFlow saved_model export169keras_model = None170try:171import tensorflow as tf172from tensorflow import keras173174from models.tf import TFDetect, TFModel175176LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')177f = str(file).replace('.pt', '_saved_model')178batch_size, ch, *imgsz = list(im.shape) # BCHW179180tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)181im = tf.zeros((batch_size, *imgsz, 3)) # BHWC order for TensorFlow182y = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)183inputs = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)184outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)185keras_model = keras.Model(inputs=inputs, outputs=outputs)186keras_model.trainable = False187keras_model.summary()188keras_model.save(f, save_format='tf')189190LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')191except Exception as e:192LOGGER.info(f'\n{prefix} export failure: {e}')193194return keras_model195196197def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):198# YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow199try:200import tensorflow as tf201from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2202203LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')204f = file.with_suffix('.pb')205206m = tf.function(lambda x: keras_model(x)) # full model207m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))208frozen_func = convert_variables_to_constants_v2(m)209frozen_func.graph.as_graph_def()210tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)211212LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')213except Exception as e:214LOGGER.info(f'\n{prefix} export failure: {e}')215216217def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')):218# YOLOv5 TensorFlow Lite export219try:220import tensorflow as tf221222from models.tf import representative_dataset_gen223224LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')225batch_size, ch, *imgsz = list(im.shape) # BCHW226f = str(file).replace('.pt', '-fp16.tflite')227228converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)229converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]230converter.target_spec.supported_types = [tf.float16]231converter.optimizations = [tf.lite.Optimize.DEFAULT]232if int8:233dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data234converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)235converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]236converter.target_spec.supported_types = []237converter.inference_input_type = tf.uint8 # or tf.int8238converter.inference_output_type = tf.uint8 # or tf.int8239converter.experimental_new_quantizer = False240f = str(file).replace('.pt', '-int8.tflite')241242tflite_model = converter.convert()243open(f, "wb").write(tflite_model)244LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')245246except Exception as e:247LOGGER.info(f'\n{prefix} export failure: {e}')248249250def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):251# YOLOv5 TensorFlow.js export252try:253check_requirements(('tensorflowjs',))254import re255256import tensorflowjs as tfjs257258LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')259f = str(file).replace('.pt', '_web_model') # js dir260f_pb = file.with_suffix('.pb') # *.pb path261f_json = f + '/model.json' # *.json path262263cmd = f"tensorflowjs_converter --input_format=tf_frozen_model " \264f"--output_node_names='Identity,Identity_1,Identity_2,Identity_3' {f_pb} {f}"265subprocess.run(cmd, shell=True)266267json = open(f_json).read()268with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order269subst = re.sub(270r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '271r'"Identity.?.?": {"name": "Identity.?.?"}, '272r'"Identity.?.?": {"name": "Identity.?.?"}, '273r'"Identity.?.?": {"name": "Identity.?.?"}}}',274r'{"outputs": {"Identity": {"name": "Identity"}, '275r'"Identity_1": {"name": "Identity_1"}, '276r'"Identity_2": {"name": "Identity_2"}, '277r'"Identity_3": {"name": "Identity_3"}}}',278json)279j.write(subst)280281LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')282except Exception as e:283LOGGER.info(f'\n{prefix} export failure: {e}')284285286def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):287try:288check_requirements(('tensorrt',))289import tensorrt as trt290291opset = (12, 13)[trt.__version__[0] == '8'] # test on TensorRT 7.x and 8.x292export_onnx(model, im, file, opset, train, False, simplify)293onnx = file.with_suffix('.onnx')294assert onnx.exists(), f'failed to export ONNX file: {onnx}'295296LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')297f = file.with_suffix('.engine') # TensorRT engine file298logger = trt.Logger(trt.Logger.INFO)299if verbose:300logger.min_severity = trt.Logger.Severity.VERBOSE301302builder = trt.Builder(logger)303config = builder.create_builder_config()304config.max_workspace_size = workspace * 1 << 30305306flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))307network = builder.create_network(flag)308parser = trt.OnnxParser(network, logger)309if not parser.parse_from_file(str(onnx)):310raise RuntimeError(f'failed to load ONNX file: {onnx}')311312inputs = [network.get_input(i) for i in range(network.num_inputs)]313outputs = [network.get_output(i) for i in range(network.num_outputs)]314LOGGER.info(f'{prefix} Network Description:')315for inp in inputs:316LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')317for out in outputs:318LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')319320half &= builder.platform_has_fast_fp16321LOGGER.info(f'{prefix} building FP{16 if half else 32} engine in {f}')322if half:323config.set_flag(trt.BuilderFlag.FP16)324with builder.build_engine(network, config) as engine, open(f, 'wb') as t:325t.write(engine.serialize())326LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')327328except Exception as e:329LOGGER.info(f'\n{prefix} export failure: {e}')330331332@torch.no_grad()333def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'334weights=ROOT / 'yolov5s.pt', # weights path335imgsz=(640, 640), # image (height, width)336batch_size=1, # batch size337device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu338include=('torchscript', 'onnx'), # include formats339half=False, # FP16 half-precision export340inplace=False, # set YOLOv5 Detect() inplace=True341train=False, # model.train() mode342optimize=False, # TorchScript: optimize for mobile343int8=False, # CoreML/TF INT8 quantization344dynamic=False, # ONNX/TF: dynamic axes345simplify=False, # ONNX: simplify model346opset=12, # ONNX: opset version347verbose=False, # TensorRT: verbose log348workspace=4, # TensorRT: workspace size (GB)349nms=False, # TF: add NMS to model350agnostic_nms=False, # TF: add agnostic NMS to model351topk_per_class=100, # TF.js NMS: topk per class to keep352topk_all=100, # TF.js NMS: topk for all classes to keep353iou_thres=0.45, # TF.js NMS: IoU threshold354conf_thres=0.25 # TF.js NMS: confidence threshold355):356t = time.time()357include = [x.lower() for x in include]358tf_exports = list(x in include for x in ('saved_model', 'pb', 'tflite', 'tfjs')) # TensorFlow exports359file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights)360361# Checks362imgsz *= 2 if len(imgsz) == 1 else 1 # expand363opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12364365# Load PyTorch model366device = select_device(device)367assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'368model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model369nc, names = model.nc, model.names # number of classes, class names370371# Input372gs = int(max(model.stride)) # grid size (max stride)373imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples374im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection375376# Update model377if half:378im, model = im.half(), model.half() # to FP16379model.train() if train else model.eval() # training mode = no Detect() layer grid construction380for k, m in model.named_modules():381if isinstance(m, Conv): # assign export-friendly activations382if isinstance(m.act, nn.SiLU):383m.act = SiLU()384elif isinstance(m, Detect):385m.inplace = inplace386m.onnx_dynamic = dynamic387# m.forward = m.forward_export # assign forward (optional)388389for _ in range(2):390y = model(im) # dry runs391LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} ({file_size(file):.1f} MB)")392393# Exports394if 'torchscript' in include:395export_torchscript(model, im, file, optimize)396if ('onnx' in include) or ('openvino' in include): # OpenVINO requires ONNX397export_onnx(model, im, file, opset, train, dynamic, simplify)398if 'engine' in include:399export_engine(model, im, file, train, half, simplify, workspace, verbose)400if 'coreml' in include:401export_coreml(model, im, file)402if 'openvino' in include:403export_openvino(model, im, file)404405# TensorFlow Exports406if any(tf_exports):407pb, tflite, tfjs = tf_exports[1:]408assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'409model = export_saved_model(model, im, file, dynamic, tf_nms=nms or agnostic_nms or tfjs,410agnostic_nms=agnostic_nms or tfjs, topk_per_class=topk_per_class, topk_all=topk_all,411conf_thres=conf_thres, iou_thres=iou_thres) # keras model412if pb or tfjs: # pb prerequisite to tfjs413export_pb(model, im, file)414if tflite:415export_tflite(model, im, file, int8=int8, data=data, ncalib=100)416if tfjs:417export_tfjs(model, im, file)418419# Finish420LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'421f"\nResults saved to {colorstr('bold', file.parent.resolve())}"422f'\nVisualize with https://netron.app')423424425def parse_opt():426parser = argparse.ArgumentParser()427parser.add_argument('--data', type=str, default=ROOT / 'data/dotav15_poly.yaml', help='dataset.yaml path')428parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'runs/train/yolov5m_finetune_dotav1.5/weights/best.pt', help='model.pt path(s)')429parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[1024, 1024], help='image (h, w)')430parser.add_argument('--batch-size', type=int, default=1, help='batch size')431parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')432parser.add_argument('--half', action='store_true', help='FP16 half-precision export')433parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')434parser.add_argument('--train', action='store_true', help='model.train() mode')435parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')436parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')437parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')438parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')439parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')440parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')441parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')442parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')443parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')444parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')445parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')446parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')447parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')448parser.add_argument('--include', nargs='+',449default=['torchscript', 'onnx'],450help='available formats are (torchscript, onnx, engine, coreml, saved_model, pb, tflite, tfjs)')451opt = parser.parse_args()452print_args(FILE.stem, opt)453return opt454455456def main(opt):457for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):458run(**vars(opt))459460461if __name__ == "__main__":462opt = parse_opt()463main(opt)464465466