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.

331 lines
14KB

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