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.

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