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.

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