Ultrajonic commited on
Commit
c0e7ea8
·
1 Parent(s): 11b029f

Upload export.py

Browse files
Files changed (1) hide show
  1. export.py +595 -0
export.py ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ Format | `export.py --include` | Model
6
+ --- | --- | ---
7
+ PyTorch | - | yolov5s.pt
8
+ TorchScript | `torchscript` | yolov5s.torchscript
9
+ ONNX | `onnx` | yolov5s.onnx
10
+ OpenVINO | `openvino` | yolov5s_openvino_model/
11
+ TensorRT | `engine` | yolov5s.engine
12
+ CoreML | `coreml` | yolov5s.mlmodel
13
+ TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
14
+ TensorFlow GraphDef | `pb` | yolov5s.pb
15
+ TensorFlow Lite | `tflite` | yolov5s.tflite
16
+ TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
17
+ TensorFlow.js | `tfjs` | yolov5s_web_model/
18
+
19
+ Requirements:
20
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
21
+ $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
22
+
23
+ Usage:
24
+ $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx openvino engine coreml tflite ...
25
+
26
+ Inference:
27
+ $ python path/to/detect.py --weights yolov5s.pt # PyTorch
28
+ yolov5s.torchscript # TorchScript
29
+ yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
30
+ yolov5s.xml # OpenVINO
31
+ yolov5s.engine # TensorRT
32
+ yolov5s.mlmodel # CoreML (macOS-only)
33
+ yolov5s_saved_model # TensorFlow SavedModel
34
+ yolov5s.pb # TensorFlow GraphDef
35
+ yolov5s.tflite # TensorFlow Lite
36
+ yolov5s_edgetpu.tflite # TensorFlow Edge TPU
37
+
38
+ TensorFlow.js:
39
+ $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
40
+ $ npm install
41
+ $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
42
+ $ npm start
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import os
48
+ import platform
49
+ import subprocess
50
+ import sys
51
+ import time
52
+ import warnings
53
+ from pathlib import Path
54
+
55
+ import pandas as pd
56
+ import torch
57
+ from torch.utils.mobile_optimizer import optimize_for_mobile
58
+
59
+ FILE = Path(__file__).resolve()
60
+ ROOT = FILE.parents[0] # YOLOv5 root directory
61
+ if str(ROOT) not in sys.path:
62
+ sys.path.append(str(ROOT)) # add ROOT to PATH
63
+ if platform.system() != 'Windows':
64
+ ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
65
+
66
+ from models.experimental import attempt_load
67
+ from models.yolo import Detect
68
+ from utils.datasets import LoadImages
69
+ from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, check_version, colorstr,
70
+ file_size, print_args, url2file)
71
+ from utils.torch_utils import select_device
72
+
73
+
74
+ def export_formats():
75
+ # YOLOv5 export formats
76
+ x = [
77
+ ['PyTorch', '-', '.pt', True],
78
+ ['TorchScript', 'torchscript', '.torchscript', True],
79
+ ['ONNX', 'onnx', '.onnx', True],
80
+ ['OpenVINO', 'openvino', '_openvino_model', False],
81
+ ['TensorRT', 'engine', '.engine', True],
82
+ ['CoreML', 'coreml', '.mlmodel', False],
83
+ ['TensorFlow SavedModel', 'saved_model', '_saved_model', True],
84
+ ['TensorFlow GraphDef', 'pb', '.pb', True],
85
+ ['TensorFlow Lite', 'tflite', '.tflite', False],
86
+ ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', False],
87
+ ['TensorFlow.js', 'tfjs', '_web_model', False],]
88
+ return pd.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'GPU'])
89
+
90
+
91
+ def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
92
+ # YOLOv5 TorchScript model export
93
+ try:
94
+ LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
95
+ f = file.with_suffix('.torchscript')
96
+
97
+ ts = torch.jit.trace(model, im, strict=False)
98
+ d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
99
+ extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
100
+ if optimize: # https://pytorch.org/tutorials/recipes/mobile_interpreter.html
101
+ optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)
102
+ else:
103
+ ts.save(str(f), _extra_files=extra_files)
104
+
105
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
106
+ return f
107
+ except Exception as e:
108
+ LOGGER.info(f'{prefix} export failure: {e}')
109
+
110
+
111
+ def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
112
+ # YOLOv5 ONNX export
113
+ try:
114
+ check_requirements(('onnx',))
115
+ import onnx
116
+
117
+ LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
118
+ f = file.with_suffix('.onnx')
119
+
120
+ torch.onnx.export(
121
+ model,
122
+ im,
123
+ f,
124
+ verbose=False,
125
+ opset_version=opset,
126
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
127
+ do_constant_folding=not train,
128
+ input_names=['images'],
129
+ output_names=['output'],
130
+ dynamic_axes={
131
+ 'images': {
132
+ 0: 'batch',
133
+ 2: 'height',
134
+ 3: 'width'}, # shape(1,3,640,640)
135
+ 'output': {
136
+ 0: 'batch',
137
+ 1: 'anchors'} # shape(1,25200,85)
138
+ } if dynamic else None)
139
+
140
+ # Checks
141
+ model_onnx = onnx.load(f) # load onnx model
142
+ onnx.checker.check_model(model_onnx) # check onnx model
143
+
144
+ # Metadata
145
+ d = {'stride': int(max(model.stride)), 'names': model.names}
146
+ for k, v in d.items():
147
+ meta = model_onnx.metadata_props.add()
148
+ meta.key, meta.value = k, str(v)
149
+ onnx.save(model_onnx, f)
150
+
151
+ # Simplify
152
+ if simplify:
153
+ try:
154
+ check_requirements(('onnx-simplifier',))
155
+ import onnxsim
156
+
157
+ LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
158
+ model_onnx, check = onnxsim.simplify(model_onnx,
159
+ dynamic_input_shape=dynamic,
160
+ input_shapes={'images': list(im.shape)} if dynamic else None)
161
+ assert check, 'assert check failed'
162
+ onnx.save(model_onnx, f)
163
+ except Exception as e:
164
+ LOGGER.info(f'{prefix} simplifier failure: {e}')
165
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
166
+ return f
167
+ except Exception as e:
168
+ LOGGER.info(f'{prefix} export failure: {e}')
169
+
170
+
171
+ def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')):
172
+ # YOLOv5 OpenVINO export
173
+ try:
174
+ check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
175
+ import openvino.inference_engine as ie
176
+
177
+ LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
178
+ f = str(file).replace('.pt', '_openvino_model' + os.sep)
179
+
180
+ cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}"
181
+ subprocess.check_output(cmd, shell=True)
182
+
183
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
184
+ return f
185
+ except Exception as e:
186
+ LOGGER.info(f'\n{prefix} export failure: {e}')
187
+
188
+
189
+ def export_coreml(model, im, file, int8, half, prefix=colorstr('CoreML:')):
190
+ # YOLOv5 CoreML export
191
+ try:
192
+ check_requirements(('coremltools',))
193
+ import coremltools as ct
194
+
195
+ LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
196
+ f = file.with_suffix('.mlmodel')
197
+
198
+ ts = torch.jit.trace(model, im, strict=False) # TorchScript model
199
+ ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
200
+ bits, mode = (8, 'kmeans_lut') if int8 else (16, 'linear') if half else (32, None)
201
+ if bits < 32:
202
+ if platform.system() == 'Darwin': # quantization only supported on macOS
203
+ with warnings.catch_warnings():
204
+ warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
205
+ ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
206
+ else:
207
+ print(f'{prefix} quantization only supported on macOS, skipping...')
208
+ ct_model.save(f)
209
+
210
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
211
+ return ct_model, f
212
+ except Exception as e:
213
+ LOGGER.info(f'\n{prefix} export failure: {e}')
214
+ return None, None
215
+
216
+
217
+ def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
218
+ # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
219
+ try:
220
+ import tensorrt as trt # pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com
221
+
222
+ if trt.__version__[0] == '7': # TensorRT 7 handling https://github.com/ultralytics/yolov5/issues/6012
223
+ grid = model.model[-1].anchor_grid
224
+ model.model[-1].anchor_grid = [a[..., :1, :1, :] for a in grid]
225
+ export_onnx(model, im, file, 12, train, False, simplify) # opset 12
226
+ model.model[-1].anchor_grid = grid
227
+ else: # TensorRT >= 8
228
+ check_version(trt.__version__, '8.0.0', hard=True) # require tensorrt>=8.0.0
229
+ export_onnx(model, im, file, 13, train, False, simplify) # opset 13
230
+ onnx = file.with_suffix('.onnx')
231
+
232
+ LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
233
+ assert im.device.type != 'cpu', 'export running on CPU but must be on GPU, i.e. `python export.py --device 0`'
234
+ assert onnx.exists(), f'failed to export ONNX file: {onnx}'
235
+ f = file.with_suffix('.engine') # TensorRT engine file
236
+ logger = trt.Logger(trt.Logger.INFO)
237
+ if verbose:
238
+ logger.min_severity = trt.Logger.Severity.VERBOSE
239
+
240
+ builder = trt.Builder(logger)
241
+ config = builder.create_builder_config()
242
+ config.max_workspace_size = workspace * 1 << 30
243
+ # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30) # fix TRT 8.4 deprecation notice
244
+
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
+
251
+ inputs = [network.get_input(i) for i in range(network.num_inputs)]
252
+ outputs = [network.get_output(i) for i in range(network.num_outputs)]
253
+ LOGGER.info(f'{prefix} Network Description:')
254
+ for inp in inputs:
255
+ LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
256
+ for out in outputs:
257
+ LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
258
+
259
+ LOGGER.info(f'{prefix} building FP{16 if builder.platform_has_fast_fp16 else 32} engine in {f}')
260
+ if builder.platform_has_fast_fp16:
261
+ config.set_flag(trt.BuilderFlag.FP16)
262
+ with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
263
+ t.write(engine.serialize())
264
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
265
+ return f
266
+ except Exception as e:
267
+ LOGGER.info(f'\n{prefix} export failure: {e}')
268
+
269
+
270
+ def export_saved_model(model,
271
+ im,
272
+ file,
273
+ dynamic,
274
+ tf_nms=False,
275
+ agnostic_nms=False,
276
+ topk_per_class=100,
277
+ topk_all=100,
278
+ iou_thres=0.45,
279
+ conf_thres=0.25,
280
+ keras=False,
281
+ prefix=colorstr('TensorFlow SavedModel:')):
282
+ # YOLOv5 TensorFlow SavedModel export
283
+ try:
284
+ import tensorflow as tf
285
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
286
+
287
+ from models.tf import TFDetect, TFModel
288
+
289
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
290
+ f = str(file).replace('.pt', '_saved_model')
291
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
292
+
293
+ tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
294
+ im = tf.zeros((batch_size, *imgsz, ch)) # BHWC order for TensorFlow
295
+ _ = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
296
+ inputs = tf.keras.Input(shape=(*imgsz, ch), batch_size=None if dynamic else batch_size)
297
+ outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
298
+ keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)
299
+ keras_model.trainable = False
300
+ keras_model.summary()
301
+ if keras:
302
+ keras_model.save(f, save_format='tf')
303
+ else:
304
+ spec = tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype)
305
+ m = tf.function(lambda x: keras_model(x)) # full model
306
+ m = m.get_concrete_function(spec)
307
+ frozen_func = convert_variables_to_constants_v2(m)
308
+ tfm = tf.Module()
309
+ tfm.__call__ = tf.function(lambda x: frozen_func(x)[:4] if tf_nms else frozen_func(x)[0], [spec])
310
+ tfm.__call__(im)
311
+ tf.saved_model.save(tfm,
312
+ f,
313
+ options=tf.saved_model.SaveOptions(experimental_custom_gradients=False)
314
+ if check_version(tf.__version__, '2.6') else tf.saved_model.SaveOptions())
315
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
316
+ return keras_model, f
317
+ except Exception as e:
318
+ LOGGER.info(f'\n{prefix} export failure: {e}')
319
+ return None, None
320
+
321
+
322
+ def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):
323
+ # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
324
+ try:
325
+ import tensorflow as tf
326
+ from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
327
+
328
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
329
+ f = file.with_suffix('.pb')
330
+
331
+ m = tf.function(lambda x: keras_model(x)) # full model
332
+ m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
333
+ frozen_func = convert_variables_to_constants_v2(m)
334
+ frozen_func.graph.as_graph_def()
335
+ tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
336
+
337
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
338
+ return f
339
+ except Exception as e:
340
+ LOGGER.info(f'\n{prefix} export failure: {e}')
341
+
342
+
343
+ def export_tflite(keras_model, im, file, int8, data, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):
344
+ # YOLOv5 TensorFlow Lite export
345
+ try:
346
+ import tensorflow as tf
347
+
348
+ LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
349
+ batch_size, ch, *imgsz = list(im.shape) # BCHW
350
+ f = str(file).replace('.pt', '-fp16.tflite')
351
+
352
+ converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
353
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
354
+ converter.target_spec.supported_types = [tf.float16]
355
+ converter.optimizations = [tf.lite.Optimize.DEFAULT]
356
+ if int8:
357
+ from models.tf import representative_dataset_gen
358
+ dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
359
+ converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib=100)
360
+ converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
361
+ converter.target_spec.supported_types = []
362
+ converter.inference_input_type = tf.uint8 # or tf.int8
363
+ converter.inference_output_type = tf.uint8 # or tf.int8
364
+ converter.experimental_new_quantizer = True
365
+ f = str(file).replace('.pt', '-int8.tflite')
366
+ if nms or agnostic_nms:
367
+ converter.target_spec.supported_ops.append(tf.lite.OpsSet.SELECT_TF_OPS)
368
+
369
+ tflite_model = converter.convert()
370
+ open(f, "wb").write(tflite_model)
371
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
372
+ return f
373
+ except Exception as e:
374
+ LOGGER.info(f'\n{prefix} export failure: {e}')
375
+
376
+
377
+ def export_edgetpu(keras_model, im, file, prefix=colorstr('Edge TPU:')):
378
+ # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
379
+ try:
380
+ cmd = 'edgetpu_compiler --version'
381
+ help_url = 'https://coral.ai/docs/edgetpu/compiler/'
382
+ assert platform.system() == 'Linux', f'export only supported on Linux. See {help_url}'
383
+ if subprocess.run(cmd + ' >/dev/null', shell=True).returncode != 0:
384
+ LOGGER.info(f'\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')
385
+ sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0 # sudo installed on system
386
+ for c in (
387
+ 'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',
388
+ 'echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',
389
+ 'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):
390
+ subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)
391
+ ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]
392
+
393
+ LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
394
+ f = str(file).replace('.pt', '-int8_edgetpu.tflite') # Edge TPU model
395
+ f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
396
+
397
+ cmd = f"edgetpu_compiler -s -o {file.parent} {f_tfl}"
398
+ subprocess.run(cmd, shell=True, check=True)
399
+
400
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
401
+ return f
402
+ except Exception as e:
403
+ LOGGER.info(f'\n{prefix} export failure: {e}')
404
+
405
+
406
+ def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):
407
+ # YOLOv5 TensorFlow.js export
408
+ try:
409
+ check_requirements(('tensorflowjs',))
410
+ import re
411
+
412
+ import tensorflowjs as tfjs
413
+
414
+ LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
415
+ f = str(file).replace('.pt', '_web_model') # js dir
416
+ f_pb = file.with_suffix('.pb') # *.pb path
417
+ f_json = f + '/model.json' # *.json path
418
+
419
+ cmd = f'tensorflowjs_converter --input_format=tf_frozen_model ' \
420
+ f'--output_node_names="Identity,Identity_1,Identity_2,Identity_3" {f_pb} {f}'
421
+ subprocess.run(cmd, shell=True)
422
+
423
+ with open(f_json) as j:
424
+ json = j.read()
425
+ with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
426
+ subst = re.sub(
427
+ r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
428
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
429
+ r'"Identity.?.?": {"name": "Identity.?.?"}, '
430
+ r'"Identity.?.?": {"name": "Identity.?.?"}}}', r'{"outputs": {"Identity": {"name": "Identity"}, '
431
+ r'"Identity_1": {"name": "Identity_1"}, '
432
+ r'"Identity_2": {"name": "Identity_2"}, '
433
+ r'"Identity_3": {"name": "Identity_3"}}}', json)
434
+ j.write(subst)
435
+
436
+ LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
437
+ return f
438
+ except Exception as e:
439
+ LOGGER.info(f'\n{prefix} export failure: {e}')
440
+
441
+
442
+ @torch.no_grad()
443
+ def run(
444
+ data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
445
+ weights=ROOT / 'yolov5s.pt', # weights path
446
+ imgsz=(640, 640), # image (height, width)
447
+ batch_size=1, # batch size
448
+ device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
449
+ include=('torchscript', 'onnx'), # include formats
450
+ half=False, # FP16 half-precision export
451
+ inplace=False, # set YOLOv5 Detect() inplace=True
452
+ train=False, # model.train() mode
453
+ optimize=False, # TorchScript: optimize for mobile
454
+ int8=False, # CoreML/TF INT8 quantization
455
+ dynamic=False, # ONNX/TF: dynamic axes
456
+ simplify=False, # ONNX: simplify model
457
+ opset=12, # ONNX: opset version
458
+ verbose=False, # TensorRT: verbose log
459
+ workspace=4, # TensorRT: workspace size (GB)
460
+ nms=False, # TF: add NMS to model
461
+ agnostic_nms=False, # TF: add agnostic NMS to model
462
+ topk_per_class=100, # TF.js NMS: topk per class to keep
463
+ topk_all=100, # TF.js NMS: topk for all classes to keep
464
+ iou_thres=0.45, # TF.js NMS: IoU threshold
465
+ conf_thres=0.25, # TF.js NMS: confidence threshold
466
+ ):
467
+ t = time.time()
468
+ include = [x.lower() for x in include] # to lowercase
469
+ formats = tuple(export_formats()['Argument'][1:]) # --include arguments
470
+ flags = [x in include for x in formats]
471
+ assert sum(flags) == len(include), f'ERROR: Invalid --include {include}, valid --include arguments are {formats}'
472
+ jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = flags # export booleans
473
+ file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights) # PyTorch weights
474
+
475
+ # Load PyTorch model
476
+ device = select_device(device)
477
+ if half:
478
+ assert device.type != 'cpu' or coreml, '--half only compatible with GPU export, i.e. use --device 0'
479
+ model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
480
+ nc, names = model.nc, model.names # number of classes, class names
481
+
482
+ # Checks
483
+ imgsz *= 2 if len(imgsz) == 1 else 1 # expand
484
+ assert nc == len(names), f'Model class count {nc} != len(names) {len(names)}'
485
+
486
+ # Input
487
+ gs = int(max(model.stride)) # grid size (max stride)
488
+ imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
489
+ im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
490
+
491
+ # Update model
492
+ if half and not coreml:
493
+ im, model = im.half(), model.half() # to FP16
494
+ model.train() if train else model.eval() # training mode = no Detect() layer grid construction
495
+ for k, m in model.named_modules():
496
+ if isinstance(m, Detect):
497
+ m.inplace = inplace
498
+ m.onnx_dynamic = dynamic
499
+ m.export = True
500
+
501
+ for _ in range(2):
502
+ y = model(im) # dry runs
503
+ shape = tuple(y[0].shape) # model output shape
504
+ LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} with output shape {shape} ({file_size(file):.1f} MB)")
505
+
506
+ # Exports
507
+ f = [''] * 10 # exported filenames
508
+ warnings.filterwarnings(action='ignore', category=torch.jit.TracerWarning) # suppress TracerWarning
509
+ if jit:
510
+ f[0] = export_torchscript(model, im, file, optimize)
511
+ if engine: # TensorRT required before ONNX
512
+ f[1] = export_engine(model, im, file, train, half, simplify, workspace, verbose)
513
+ if onnx or xml: # OpenVINO requires ONNX
514
+ f[2] = export_onnx(model, im, file, opset, train, dynamic, simplify)
515
+ if xml: # OpenVINO
516
+ f[3] = export_openvino(model, im, file)
517
+ if coreml:
518
+ _, f[4] = export_coreml(model, im, file, int8, half)
519
+
520
+ # TensorFlow Exports
521
+ if any((saved_model, pb, tflite, edgetpu, tfjs)):
522
+ if int8 or edgetpu: # TFLite --int8 bug https://github.com/ultralytics/yolov5/issues/5707
523
+ check_requirements(('flatbuffers==1.12',)) # required before `import tensorflow`
524
+ assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'
525
+ model, f[5] = export_saved_model(model.cpu(),
526
+ im,
527
+ file,
528
+ dynamic,
529
+ tf_nms=nms or agnostic_nms or tfjs,
530
+ agnostic_nms=agnostic_nms or tfjs,
531
+ topk_per_class=topk_per_class,
532
+ topk_all=topk_all,
533
+ conf_thres=conf_thres,
534
+ iou_thres=iou_thres) # keras model
535
+ if pb or tfjs: # pb prerequisite to tfjs
536
+ f[6] = export_pb(model, im, file)
537
+ if tflite or edgetpu:
538
+ f[7] = export_tflite(model, im, file, int8=int8 or edgetpu, data=data, nms=nms, agnostic_nms=agnostic_nms)
539
+ if edgetpu:
540
+ f[8] = export_edgetpu(model, im, file)
541
+ if tfjs:
542
+ f[9] = export_tfjs(model, im, file)
543
+
544
+ # Finish
545
+ f = [str(x) for x in f if x] # filter out '' and None
546
+ if any(f):
547
+ LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
548
+ f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
549
+ f"\nDetect: python detect.py --weights {f[-1]}"
550
+ f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{f[-1]}')"
551
+ f"\nValidate: python val.py --weights {f[-1]}"
552
+ f"\nVisualize: https://netron.app")
553
+ return f # return list of exported files/dirs
554
+
555
+
556
+ def parse_opt():
557
+ parser = argparse.ArgumentParser()
558
+ parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
559
+ parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
560
+ parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
561
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
562
+ parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
563
+ parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
564
+ parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
565
+ parser.add_argument('--train', action='store_true', help='model.train() mode')
566
+ parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
567
+ parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
568
+ parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
569
+ parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
570
+ parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
571
+ parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
572
+ parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
573
+ parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
574
+ parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
575
+ parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
576
+ parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
577
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
578
+ parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
579
+ parser.add_argument('--include',
580
+ nargs='+',
581
+ default=['torchscript', 'onnx'],
582
+ help='torchscript, onnx, openvino, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs')
583
+ opt = parser.parse_args()
584
+ print_args(vars(opt))
585
+ return opt
586
+
587
+
588
+ def main(opt):
589
+ for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
590
+ run(**vars(opt))
591
+
592
+
593
+ if __name__ == "__main__":
594
+ opt = parse_opt()
595
+ main(opt)