You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

581 lines
28KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
  4. Format | `export.py --include` | Model
  5. --- | --- | ---
  6. PyTorch | - | yolov5s.pt
  7. TorchScript | `torchscript` | yolov5s.torchscript
  8. ONNX | `onnx` | yolov5s.onnx
  9. OpenVINO | `openvino` | yolov5s_openvino_model/
  10. TensorRT | `engine` | yolov5s.engine
  11. CoreML | `coreml` | yolov5s.mlmodel
  12. TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
  13. TensorFlow GraphDef | `pb` | yolov5s.pb
  14. TensorFlow Lite | `tflite` | yolov5s.tflite
  15. TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
  16. TensorFlow.js | `tfjs` | yolov5s_web_model/
  17. Requirements:
  18. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
  19. $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
  20. Usage:
  21. $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
  22. Inference:
  23. $ python path/to/detect.py --weights yolov5s.pt # PyTorch
  24. yolov5s.torchscript # TorchScript
  25. yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
  26. yolov5s.xml # OpenVINO
  27. yolov5s.engine # TensorRT
  28. yolov5s.mlmodel # CoreML (MacOS-only)
  29. yolov5s_saved_model # TensorFlow SavedModel
  30. yolov5s.pb # TensorFlow GraphDef
  31. yolov5s.tflite # TensorFlow Lite
  32. yolov5s_edgetpu.tflite # TensorFlow Edge TPU
  33. TensorFlow.js:
  34. $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
  35. $ npm install
  36. $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
  37. $ npm start
  38. """
  39. import argparse
  40. import json
  41. import os
  42. import platform
  43. import subprocess
  44. import sys
  45. import time
  46. import warnings
  47. from pathlib import Path
  48. import pandas as pd
  49. import torch
  50. import torch.nn as nn
  51. from torch.utils.mobile_optimizer import optimize_for_mobile
  52. FILE = Path(__file__).resolve()
  53. ROOT = FILE.parents[0] # YOLOv5 root directory
  54. if str(ROOT) not in sys.path:
  55. sys.path.append(str(ROOT)) # add ROOT to PATH
  56. if platform.system() != 'Windows':
  57. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  58. from models.common import Conv
  59. from models.experimental import attempt_load
  60. from models.yolo import Detect
  61. from utils.activations import SiLU
  62. from utils.datasets import LoadImages
  63. from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
  64. file_size, print_args, url2file)
  65. from utils.torch_utils import select_device
  66. def export_formats():
  67. # YOLOv5 export formats
  68. x = [['PyTorch', '-', '.pt', True], ['TorchScript', 'torchscript', '.torchscript', True],
  69. ['ONNX', 'onnx', '.onnx', True], ['OpenVINO', 'openvino', '_openvino_model', False],
  70. ['TensorRT', 'engine', '.engine', True], ['CoreML', 'coreml', '.mlmodel', False],
  71. ['TensorFlow SavedModel', 'saved_model', '_saved_model', True], ['TensorFlow GraphDef', 'pb', '.pb', True],
  72. ['TensorFlow Lite', 'tflite', '.tflite', False], ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False],
  73. ['TensorFlow.js', 'tfjs', '_web_model', False]]
  74. return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'GPU'])
  75. def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
  76. # YOLOv5 TorchScript model export
  77. try:
  78. LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
  79. f = file.with_suffix('.torchscript')
  80. ts = torch.jit.trace(model, im, strict=False)
  81. d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
  82. extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
  83. if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
  84. optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
  85. else:
  86. ts.save(str(f), _extra_files=extra_files)
  87. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  88. return f
  89. except Exception as e:
  90. LOGGER.info(f'{prefix} export failure: {e}')
  91. def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
  92. # YOLOv5 ONNX export
  93. try:
  94. check_requirements(('onnx',))
  95. import onnx
  96. LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
  97. f = file.with_suffix('.onnx')
  98. torch.onnx.export(
  99. model,
  100. im,
  101. f,
  102. verbose=False,
  103. opset_version=opset,
  104. training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
  105. do_constant_folding=not train,
  106. input_names=['images'],
  107. output_names=['output'],
  108. dynamic_axes={
  109. 'images': {
  110. 0: 'batch',
  111. 2: 'height',
  112. 3: 'width'}, # shape(1,3,640,640)
  113. 'output': {
  114. 0: 'batch',
  115. 1: 'anchors'} # shape(1,25200,85)
  116. } if dynamic else None)
  117. # Checks
  118. model_onnx = onnx.load(f) # load onnx model
  119. onnx.checker.check_model(model_onnx) # check onnx model
  120. # LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print
  121. # Simplify
  122. if simplify:
  123. try:
  124. check_requirements(('onnx-simplifier',))
  125. import onnxsim
  126. LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
  127. model_onnx, check = onnxsim.simplify(model_onnx,
  128. dynamic_input_shape=dynamic,
  129. input_shapes={'images': list(im.shape)} if dynamic else None)
  130. assert check, 'assert check failed'
  131. onnx.save(model_onnx, f)
  132. except Exception as e:
  133. LOGGER.info(f'{prefix} simplifier failure: {e}')
  134. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  135. return f
  136. except Exception as e:
  137. LOGGER.info(f'{prefix} export failure: {e}')
  138. def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')):
  139. # YOLOv5 OpenVINO export
  140. try:
  141. check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
  142. import openvino.inference_engine as ie
  143. LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
  144. f = str(file).replace('.pt', '_openvino_model' + os.sep)
  145. cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}"
  146. subprocess.check_output(cmd, shell=True)
  147. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  148. return f
  149. except Exception as e:
  150. LOGGER.info(f'\n{prefix} export failure: {e}')
  151. def export_coreml(model, im, file, prefix=colorstr('CoreML:')):
  152. # YOLOv5 CoreML export
  153. try:
  154. check_requirements(('coremltools',))
  155. import coremltools as ct
  156. LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
  157. f = file.with_suffix('.mlmodel')
  158. ts = torch.jit.trace(model, im, strict=False) # TorchScript model
  159. ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
  160. ct_model.save(f)
  161. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  162. return ct_model, f
  163. except Exception as e:
  164. LOGGER.info(f'\n{prefix} export failure: {e}')
  165. return None, None
  166. def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
  167. # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
  168. try:
  169. check_requirements(('tensorrt',))
  170. import tensorrt as trt
  171. if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
  172. grid = model.model[-1].anchor_grid
  173. model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
  174. export_onnx(model, im, file, 12, train, False, simplify) # opset 12
  175. model.model[-1].anchor_grid = grid
  176. else: # TensorRT >= 8
  177. check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
  178. export_onnx(model, im, file, 13, train, False, simplify) # opset 13
  179. onnx = file.with_suffix('.onnx')
  180. LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
  181. assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
  182. assert onnx.exists(), f'failed to export ONNX file: {onnx}'
  183. f = file.with_suffix('.engine') # TensorRT engine file
  184. logger = trt.Logger(trt.Logger.INFO)
  185. if verbose:
  186. logger.min_severity = trt.Logger.Severity.VERBOSE
  187. builder = trt.Builder(logger)
  188. config = builder.create_builder_config()
  189. config.max_workspace_size = workspace * 1 << 30
  190. # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
  191. flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
  192. network = builder.create_network(flag)
  193. parser = trt.OnnxParser(network, logger)
  194. if not parser.parse_from_file(str(onnx)):
  195. raise RuntimeError(f'failed to load ONNX file: {onnx}')
  196. inputs = [network.get_input(i) for i in range(network.num_inputs)]
  197. outputs = [network.get_output(i) for i in range(network.num_outputs)]
  198. LOGGER.info(f'{prefix} Network Description:')
  199. for inp in inputs:
  200. LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
  201. for out in outputs:
  202. LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
  203. LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 else 32} engine in {f}')
  204. if builder.platform_has_fast_fp16:
  205. config.set_flag(trt.BuilderFlag.FP16)
  206. with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
  207. t.write(engine.serialize())
  208. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  209. return f
  210. except Exception as e:
  211. LOGGER.info(f'\n{prefix} export failure: {e}')
  212. def export_saved_model(model,
  213. im,
  214. file,
  215. dynamic,
  216. tf_nms=False,
  217. agnostic_nms=False,
  218. topk_per_class=100,
  219. topk_all=100,
  220. iou_thres=0.45,
  221. conf_thres=0.25,
  222. keras=False,
  223. prefix=colorstr('TensorFlow SavedModel:')):
  224. # YOLOv5 TensorFlow SavedModel export
  225. try:
  226. import tensorflow as tf
  227. from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
  228. from models.tf import TFDetect, TFModel
  229. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  230. f = str(file).replace('.pt', '_saved_model')
  231. batch_size, ch, *imgsz = list(im.shape) # BCHW
  232. tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
  233. im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
  234. _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
  235. inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
  236. outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
  237. keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
  238. keras_model.trainable = False
  239. keras_model.summary()
  240. if keras:
  241. keras_model.save(f, save_format='tf')
  242. else:
  243. spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
  244. m = tf.function(lambda x: keras_model(x)) # full model
  245. m = m.get_concrete_function(spec)
  246. frozen_func = convert_variables_to_constants_v2(m)
  247. tfm = tf.Module()
  248. tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
  249. tfm.__call__(im)
  250. tf.saved_model.save(tfm,
  251. f,
  252. options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
  253. if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
  254. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  255. return keras_model, f
  256. except Exception as e:
  257. LOGGER.info(f'\n{prefix} export failure: {e}')
  258. return None, None
  259. def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):
  260. # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
  261. try:
  262. import tensorflow as tf
  263. from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
  264. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  265. f = file.with_suffix('.pb')
  266. m = tf.function(lambda x: keras_model(x)) # full model
  267. m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
  268. frozen_func = convert_variables_to_constants_v2(m)
  269. frozen_func.graph.as_graph_def()
  270. tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
  271. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  272. return f
  273. except Exception as e:
  274. LOGGER.info(f'\n{prefix} export failure: {e}')
  275. def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')):
  276. # YOLOv5 TensorFlow Lite export
  277. try:
  278. import tensorflow as tf
  279. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  280. batch_size, ch, *imgsz = list(im.shape) # BCHW
  281. f = str(file).replace('.pt', '-fp16.tflite')
  282. converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
  283. converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
  284. converter.target_spec.supported_types = [tf.float16]
  285. converter.optimizations = [tf.lite.Optimize.DEFAULT]
  286. if int8:
  287. from models.tf import representative_dataset_gen
  288. dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
  289. converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
  290. converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
  291. converter.target_spec.supported_types = []
  292. converter.inference_input_type = tf.uint8 # or tf.int8
  293. converter.inference_output_type = tf.uint8 # or tf.int8
  294. converter.experimental_new_quantizer = True
  295. f = str(file).replace('.pt', '-int8.tflite')
  296. tflite_model = converter.convert()
  297. open(f, "wb").write(tflite_model)
  298. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  299. return f
  300. except Exception as e:
  301. LOGGER.info(f'\n{prefix} export failure: {e}')
  302. def export_edgetpu(keras_model, im, file, prefix=colorstr('Edge TPU:')):
  303. # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
  304. try:
  305. cmd = 'edgetpu_compiler --version'
  306. help_url = 'https://coral.ai/docs/edgetpu/compiler/'
  307. assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
  308. if subprocess.run(cmd + ' >/dev/null', shell=True).returncode != 0:
  309. LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
  310. sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
  311. for c in (
  312. 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
  313. 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
  314. 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
  315. subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
  316. ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
  317. LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
  318. f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
  319. f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
  320. cmd = f"edgetpu_compiler -s {f_tfl}"
  321. subprocess.run(cmd, shell=True, check=True)
  322. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  323. return f
  324. except Exception as e:
  325. LOGGER.info(f'\n{prefix} export failure: {e}')
  326. def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):
  327. # YOLOv5 TensorFlow.js export
  328. try:
  329. check_requirements(('tensorflowjs',))
  330. import re
  331. import tensorflowjs as tfjs
  332. LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
  333. f = str(file).replace('.pt', '_web_model') # js dir
  334. f_pb = file.with_suffix('.pb') # *.pb path
  335. f_json = f + '/model.json' # *.json path
  336. cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
  337. f'--output_node_names="Identity,Identity_1,Identity_2,Identity_3" {f_pb} {f}'
  338. subprocess.run(cmd, shell=True)
  339. json = open(f_json).read()
  340. with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
  341. subst = re.sub(
  342. r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
  343. r'"Identity.?.?": {"name": "Identity.?.?"}, '
  344. r'"Identity.?.?": {"name": "Identity.?.?"}, '
  345. r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
  346. r'"Identity_1": {"name": "Identity_1"}, '
  347. r'"Identity_2": {"name": "Identity_2"}, '
  348. r'"Identity_3": {"name": "Identity_3"}}}', json)
  349. j.write(subst)
  350. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  351. return f
  352. except Exception as e:
  353. LOGGER.info(f'\n{prefix} export failure: {e}')
  354. @torch.no_grad()
  355. def run(
  356. data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
  357. weights=ROOT / 'yolov5s.pt', # weights path
  358. imgsz=(640, 640), # image (height, width)
  359. batch_size=1, # batch size
  360. device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  361. include=('torchscript', 'onnx'), # include formats
  362. half=False, # FP16 half-precision export
  363. inplace=False, # set YOLOv5 Detect() inplace=True
  364. train=False, # model.train() mode
  365. optimize=False, # TorchScript: optimize for mobile
  366. int8=False, # CoreML/TF INT8 quantization
  367. dynamic=False, # ONNX/TF: dynamic axes
  368. simplify=False, # ONNX: simplify model
  369. opset=12, # ONNX: opset version
  370. verbose=False, # TensorRT: verbose log
  371. workspace=4, # TensorRT: workspace size (GB)
  372. nms=False, # TF: add NMS to model
  373. agnostic_nms=False, # TF: add agnostic NMS to model
  374. topk_per_class=100, # TF.js NMS: topk per class to keep
  375. topk_all=100, # TF.js NMS: topk for all classes to keep
  376. iou_thres=0.45, # TF.js NMS: IoU threshold
  377. conf_thres=0.25, # TF.js NMS: confidence threshold
  378. ):
  379. t = time.time()
  380. include = [x.lower() for x in include] # to lowercase
  381. formats = tuple(export_formats()['Argument'][1:]) # --include arguments
  382. flags = [x in include for x in formats]
  383. assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {formats}'
  384. jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
  385. file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
  386. # Load PyTorch model
  387. device = select_device(device)
  388. assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
  389. model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
  390. nc, names = model.nc, model.names # number of classes, class names
  391. # Checks
  392. imgsz *= 2 if len(imgsz) == 1 else 1 # expand
  393. opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12
  394. assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
  395. # Input
  396. gs = int(max(model.stride)) # grid size (max stride)
  397. imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
  398. im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
  399. # Update model
  400. if half:
  401. im, model = im.half(), model.half() # to FP16
  402. model.train() if train else model.eval() # training mode = no Detect() layer grid construction
  403. for k, m in model.named_modules():
  404. if isinstance(m, Conv): # assign export-friendly activations
  405. if isinstance(m.act, nn.SiLU):
  406. m.act = SiLU()
  407. elif isinstance(m, Detect):
  408. m.inplace = inplace
  409. m.onnx_dynamic = dynamic
  410. if hasattr(m, 'forward_export'):
  411. m.forward = m.forward_export # assign custom forward (optional)
  412. for _ in range(2):
  413. y = model(im) # dry runs
  414. shape = tuple(y[0].shape) # model output shape
  415. LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
  416. # Exports
  417. f = [''] * 10 # exported filenames
  418. warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
  419. if jit:
  420. f[0] = export_torchscript(model, im, file, optimize)
  421. if engine: # TensorRT required before ONNX
  422. f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose)
  423. if onnx or xml: # OpenVINO requires ONNX
  424. f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
  425. if xml: # OpenVINO
  426. f[3] = export_openvino(model, im, file)
  427. if coreml:
  428. _, f[4] = export_coreml(model, im, file)
  429. # TensorFlow Exports
  430. if any((saved_model, pb, tflite, edgetpu, tfjs)):
  431. if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
  432. check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
  433. assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'
  434. model, f[5] = export_saved_model(model.cpu(),
  435. im,
  436. file,
  437. dynamic,
  438. tf_nms=nms or agnostic_nms or tfjs,
  439. agnostic_nms=agnostic_nms or tfjs,
  440. topk_per_class=topk_per_class,
  441. topk_all=topk_all,
  442. conf_thres=conf_thres,
  443. iou_thres=iou_thres) # keras model
  444. if pb or tfjs: # pb prerequisite to tfjs
  445. f[6] = export_pb(model, im, file)
  446. if tflite or edgetpu:
  447. f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, ncalib=100)
  448. if edgetpu:
  449. f[8] = export_edgetpu(model, im, file)
  450. if tfjs:
  451. f[9] = export_tfjs(model, im, file)
  452. # Finish
  453. f = [str(x) for x in f if x] # filter out '' and None
  454. if any(f):
  455. LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
  456. f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
  457. f"\nDetect: python detect.py --weights {f[-1]}"
  458. f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
  459. f"\nValidate: python val.py --weights {f[-1]}"
  460. f"\nVisualize: https://netron.app")
  461. return f # return list of exported files/dirs
  462. def parse_opt():
  463. parser = argparse.ArgumentParser()
  464. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
  465. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
  466. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
  467. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  468. parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  469. parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
  470. parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
  471. parser.add_argument('--train', action='store_true', help='model.train() mode')
  472. parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
  473. parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
  474. parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
  475. parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
  476. parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
  477. parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
  478. parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
  479. parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
  480. parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
  481. parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
  482. parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
  483. parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
  484. parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
  485. parser.add_argument('--include',
  486. nargs='+',
  487. default=['torchscript', 'onnx'],
  488. help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
  489. opt = parser.parse_args()
  490. print_args(vars(opt))
  491. return opt
  492. def main(opt):
  493. for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
  494. run(**vars(opt))
  495. if __name__ == "__main__":
  496. opt = parse_opt()
  497. main(opt)