No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

561 líneas
27KB

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