Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

465 lines
21KB

  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 | Example | `--include ...` argument
  5. --- | --- | ---
  6. PyTorch | yolov5s.pt | -
  7. TorchScript | yolov5s.torchscript | `torchscript`
  8. ONNX | yolov5s.onnx | `onnx`
  9. CoreML | yolov5s.mlmodel | `coreml`
  10. OpenVINO | yolov5s_openvino_model/ | `openvino`
  11. TensorFlow SavedModel | yolov5s_saved_model/ | `saved_model`
  12. TensorFlow GraphDef | yolov5s.pb | `pb`
  13. TensorFlow Lite | yolov5s.tflite | `tflite`
  14. TensorFlow.js | yolov5s_web_model/ | `tfjs`
  15. TensorRT | yolov5s.engine | `engine`
  16. Usage:
  17. $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx coreml openvino saved_model tflite tfjs
  18. Inference:
  19. $ python path/to/detect.py --weights yolov5s.pt
  20. yolov5s.torchscript
  21. yolov5s.onnx
  22. yolov5s.mlmodel (under development)
  23. yolov5s_openvino_model (under development)
  24. yolov5s_saved_model
  25. yolov5s.pb
  26. yolov5s.tflite
  27. yolov5s.engine
  28. TensorFlow.js:
  29. $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
  30. $ npm install
  31. $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
  32. $ npm start
  33. """
  34. import argparse
  35. import json
  36. import os
  37. import subprocess
  38. import sys
  39. import time
  40. from pathlib import Path
  41. import torch
  42. import torch.nn as nn
  43. from torch.utils.mobile_optimizer import optimize_for_mobile
  44. FILE = Path(__file__).resolve()
  45. ROOT = FILE.parents[0] # YOLOv5 root directory
  46. if str(ROOT) not in sys.path:
  47. sys.path.append(str(ROOT)) # add ROOT to PATH
  48. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  49. from models.common import Conv
  50. from models.experimental import attempt_load
  51. from models.yolo import Detect
  52. from utils.activations import SiLU
  53. from utils.datasets import LoadImages
  54. from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, colorstr, file_size, print_args,
  55. url2file)
  56. from utils.torch_utils import select_device
  57. def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
  58. # YOLOv5 TorchScript model export
  59. try:
  60. LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
  61. f = file.with_suffix('.torchscript')
  62. ts = torch.jit.trace(model, im, strict=False)
  63. d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
  64. extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
  65. (optimize_for_mobile(ts) if optimize else ts).save(str(f), _extra_files=extra_files)
  66. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  67. except Exception as e:
  68. LOGGER.info(f'{prefix} export failure: {e}')
  69. def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
  70. # YOLOv5 ONNX export
  71. try:
  72. check_requirements(('onnx',))
  73. import onnx
  74. LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
  75. f = file.with_suffix('.onnx')
  76. torch.onnx.export(model, im, f, verbose=False, opset_version=opset,
  77. training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
  78. do_constant_folding=not train,
  79. input_names=['images'],
  80. output_names=['output'],
  81. dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
  82. 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
  83. } if dynamic else None)
  84. # Checks
  85. model_onnx = onnx.load(f) # load onnx model
  86. onnx.checker.check_model(model_onnx) # check onnx model
  87. # LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print
  88. # Simplify
  89. if simplify:
  90. try:
  91. check_requirements(('onnx-simplifier',))
  92. import onnxsim
  93. LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
  94. model_onnx, check = onnxsim.simplify(
  95. model_onnx,
  96. dynamic_input_shape=dynamic,
  97. input_shapes={'images': list(im.shape)} if dynamic else None)
  98. assert check, 'assert check failed'
  99. onnx.save(model_onnx, f)
  100. except Exception as e:
  101. LOGGER.info(f'{prefix} simplifier failure: {e}')
  102. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  103. LOGGER.info(f"{prefix} run --dynamic ONNX model inference with: 'python detect.py --weights {f}'")
  104. except Exception as e:
  105. LOGGER.info(f'{prefix} export failure: {e}')
  106. def export_coreml(model, im, file, prefix=colorstr('CoreML:')):
  107. # YOLOv5 CoreML export
  108. ct_model = None
  109. try:
  110. check_requirements(('coremltools',))
  111. import coremltools as ct
  112. LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
  113. f = file.with_suffix('.mlmodel')
  114. model.train() # CoreML exports should be placed in model.train() mode
  115. ts = torch.jit.trace(model, im, strict=False) # TorchScript model
  116. ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
  117. ct_model.save(f)
  118. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  119. except Exception as e:
  120. LOGGER.info(f'\n{prefix} export failure: {e}')
  121. return ct_model
  122. def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')):
  123. # YOLOv5 OpenVINO export
  124. try:
  125. check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
  126. import openvino.inference_engine as ie
  127. LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
  128. f = str(file).replace('.pt', '_openvino_model' + os.sep)
  129. cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}"
  130. subprocess.check_output(cmd, shell=True)
  131. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  132. except Exception as e:
  133. LOGGER.info(f'\n{prefix} export failure: {e}')
  134. def export_saved_model(model, im, file, dynamic,
  135. tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
  136. conf_thres=0.25, prefix=colorstr('TensorFlow saved_model:')):
  137. # YOLOv5 TensorFlow saved_model export
  138. keras_model = None
  139. try:
  140. import tensorflow as tf
  141. from tensorflow import keras
  142. from models.tf import TFDetect, TFModel
  143. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  144. f = str(file).replace('.pt', '_saved_model')
  145. batch_size, ch, *imgsz = list(im.shape) # BCHW
  146. tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
  147. im = tf.zeros((batch_size, *imgsz, 3)) # BHWC order for TensorFlow
  148. y = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
  149. inputs = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
  150. outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
  151. keras_model = keras.Model(inputs=inputs, outputs=outputs)
  152. keras_model.trainable = False
  153. keras_model.summary()
  154. keras_model.save(f, save_format='tf')
  155. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  156. except Exception as e:
  157. LOGGER.info(f'\n{prefix} export failure: {e}')
  158. return keras_model
  159. def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):
  160. # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
  161. try:
  162. import tensorflow as tf
  163. from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
  164. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  165. f = file.with_suffix('.pb')
  166. m = tf.function(lambda x: keras_model(x)) # full model
  167. m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
  168. frozen_func = convert_variables_to_constants_v2(m)
  169. frozen_func.graph.as_graph_def()
  170. tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
  171. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  172. except Exception as e:
  173. LOGGER.info(f'\n{prefix} export failure: {e}')
  174. def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')):
  175. # YOLOv5 TensorFlow Lite export
  176. try:
  177. import tensorflow as tf
  178. from models.tf import representative_dataset_gen
  179. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  180. batch_size, ch, *imgsz = list(im.shape) # BCHW
  181. f = str(file).replace('.pt', '-fp16.tflite')
  182. converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
  183. converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
  184. converter.target_spec.supported_types = [tf.float16]
  185. converter.optimizations = [tf.lite.Optimize.DEFAULT]
  186. if int8:
  187. dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
  188. converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
  189. converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
  190. converter.target_spec.supported_types = []
  191. converter.inference_input_type = tf.uint8 # or tf.int8
  192. converter.inference_output_type = tf.uint8 # or tf.int8
  193. converter.experimental_new_quantizer = False
  194. f = str(file).replace('.pt', '-int8.tflite')
  195. tflite_model = converter.convert()
  196. open(f, "wb").write(tflite_model)
  197. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  198. except Exception as e:
  199. LOGGER.info(f'\n{prefix} export failure: {e}')
  200. def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):
  201. # YOLOv5 TensorFlow.js export
  202. try:
  203. check_requirements(('tensorflowjs',))
  204. import re
  205. import tensorflowjs as tfjs
  206. LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
  207. f = str(file).replace('.pt', '_web_model') # js dir
  208. f_pb = file.with_suffix('.pb') # *.pb path
  209. f_json = f + '/model.json' # *.json path
  210. cmd = f"tensorflowjs_converter --input_format=tf_frozen_model " \
  211. f"--output_node_names='Identity,Identity_1,Identity_2,Identity_3' {f_pb} {f}"
  212. subprocess.run(cmd, shell=True)
  213. json = open(f_json).read()
  214. with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
  215. subst = re.sub(
  216. r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
  217. r'"Identity.?.?": {"name": "Identity.?.?"}, '
  218. r'"Identity.?.?": {"name": "Identity.?.?"}, '
  219. r'"Identity.?.?": {"name": "Identity.?.?"}}}',
  220. r'{"outputs": {"Identity": {"name": "Identity"}, '
  221. r'"Identity_1": {"name": "Identity_1"}, '
  222. r'"Identity_2": {"name": "Identity_2"}, '
  223. r'"Identity_3": {"name": "Identity_3"}}}',
  224. json)
  225. j.write(subst)
  226. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  227. except Exception as e:
  228. LOGGER.info(f'\n{prefix} export failure: {e}')
  229. def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
  230. try:
  231. check_requirements(('tensorrt',))
  232. import tensorrt as trt
  233. opset = (12, 13)[trt.__version__[0] == '8'] # test on TensorRT 7.x and 8.x
  234. export_onnx(model, im, file, opset, train, False, simplify)
  235. onnx = file.with_suffix('.onnx')
  236. assert onnx.exists(), f'failed to export ONNX file: {onnx}'
  237. LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
  238. f = file.with_suffix('.engine') # TensorRT engine file
  239. logger = trt.Logger(trt.Logger.INFO)
  240. if verbose:
  241. logger.min_severity = trt.Logger.Severity.VERBOSE
  242. builder = trt.Builder(logger)
  243. config = builder.create_builder_config()
  244. config.max_workspace_size = workspace * 1 << 30
  245. flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
  246. network = builder.create_network(flag)
  247. parser = trt.OnnxParser(network, logger)
  248. if not parser.parse_from_file(str(onnx)):
  249. raise RuntimeError(f'failed to load ONNX file: {onnx}')
  250. inputs = [network.get_input(i) for i in range(network.num_inputs)]
  251. outputs = [network.get_output(i) for i in range(network.num_outputs)]
  252. LOGGER.info(f'{prefix} Network Description:')
  253. for inp in inputs:
  254. LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
  255. for out in outputs:
  256. LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
  257. half &= builder.platform_has_fast_fp16
  258. LOGGER.info(f'{prefix} building FP{16 if half else 32} engine in {f}')
  259. if half:
  260. config.set_flag(trt.BuilderFlag.FP16)
  261. with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
  262. t.write(engine.serialize())
  263. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  264. except Exception as e:
  265. LOGGER.info(f'\n{prefix} export failure: {e}')
  266. @torch.no_grad()
  267. def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
  268. weights=ROOT / 'yolov5s.pt', # weights path
  269. imgsz=(640, 640), # image (height, width)
  270. batch_size=1, # batch size
  271. device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  272. include=('torchscript', 'onnx'), # include formats
  273. half=False, # FP16 half-precision export
  274. inplace=False, # set YOLOv5 Detect() inplace=True
  275. train=False, # model.train() mode
  276. optimize=False, # TorchScript: optimize for mobile
  277. int8=False, # CoreML/TF INT8 quantization
  278. dynamic=False, # ONNX/TF: dynamic axes
  279. simplify=False, # ONNX: simplify model
  280. opset=12, # ONNX: opset version
  281. verbose=False, # TensorRT: verbose log
  282. workspace=4, # TensorRT: workspace size (GB)
  283. nms=False, # TF: add NMS to model
  284. agnostic_nms=False, # TF: add agnostic NMS to model
  285. topk_per_class=100, # TF.js NMS: topk per class to keep
  286. topk_all=100, # TF.js NMS: topk for all classes to keep
  287. iou_thres=0.45, # TF.js NMS: IoU threshold
  288. conf_thres=0.25 # TF.js NMS: confidence threshold
  289. ):
  290. t = time.time()
  291. include = [x.lower() for x in include]
  292. tf_exports = list(x in include for x in ('saved_model', 'pb', 'tflite', 'tfjs')) # TensorFlow exports
  293. file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights)
  294. # Checks
  295. imgsz *= 2 if len(imgsz) == 1 else 1 # expand
  296. opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12
  297. # Load PyTorch model
  298. device = select_device(device)
  299. assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
  300. model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
  301. nc, names = model.nc, model.names # number of classes, class names
  302. # Input
  303. gs = int(max(model.stride)) # grid size (max stride)
  304. imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
  305. im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
  306. # Update model
  307. if half:
  308. im, model = im.half(), model.half() # to FP16
  309. model.train() if train else model.eval() # training mode = no Detect() layer grid construction
  310. for k, m in model.named_modules():
  311. if isinstance(m, Conv): # assign export-friendly activations
  312. if isinstance(m.act, nn.SiLU):
  313. m.act = SiLU()
  314. elif isinstance(m, Detect):
  315. m.inplace = inplace
  316. m.onnx_dynamic = dynamic
  317. # m.forward = m.forward_export # assign forward (optional)
  318. for _ in range(2):
  319. y = model(im) # dry runs
  320. LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} ({file_size(file):.1f} MB)")
  321. # Exports
  322. if 'torchscript' in include:
  323. export_torchscript(model, im, file, optimize)
  324. if ('onnx' in include) or ('openvino' in include): # OpenVINO requires ONNX
  325. export_onnx(model, im, file, opset, train, dynamic, simplify)
  326. if 'engine' in include:
  327. export_engine(model, im, file, train, half, simplify, workspace, verbose)
  328. if 'coreml' in include:
  329. export_coreml(model, im, file)
  330. if 'openvino' in include:
  331. export_openvino(model, im, file)
  332. # TensorFlow Exports
  333. if any(tf_exports):
  334. pb, tflite, tfjs = tf_exports[1:]
  335. assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'
  336. model = export_saved_model(model, im, file, dynamic, tf_nms=nms or agnostic_nms or tfjs,
  337. agnostic_nms=agnostic_nms or tfjs, topk_per_class=topk_per_class, topk_all=topk_all,
  338. conf_thres=conf_thres, iou_thres=iou_thres) # keras model
  339. if pb or tfjs: # pb prerequisite to tfjs
  340. export_pb(model, im, file)
  341. if tflite:
  342. export_tflite(model, im, file, int8=int8, data=data, ncalib=100)
  343. if tfjs:
  344. export_tfjs(model, im, file)
  345. # Finish
  346. LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
  347. f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
  348. f'\nVisualize with https://netron.app')
  349. def parse_opt():
  350. parser = argparse.ArgumentParser()
  351. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
  352. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
  353. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
  354. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  355. parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  356. parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
  357. parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
  358. parser.add_argument('--train', action='store_true', help='model.train() mode')
  359. parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
  360. parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
  361. parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
  362. parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
  363. parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
  364. parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
  365. parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
  366. parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
  367. parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
  368. parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
  369. parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
  370. parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
  371. parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
  372. parser.add_argument('--include', nargs='+',
  373. default=['torchscript', 'onnx'],
  374. help='available formats are (torchscript, onnx, engine, coreml, saved_model, pb, tflite, tfjs)')
  375. opt = parser.parse_args()
  376. print_args(FILE.stem, opt)
  377. return opt
  378. def main(opt):
  379. for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
  380. run(**vars(opt))
  381. if __name__ == "__main__":
  382. opt = parse_opt()
  383. main(opt)