Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

export.py 16 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...