您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

602 行
29KB

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