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

370 行
16KB

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